babylon.2.0-alpha.debug.js 1.3 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748
  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. Color4.prototype.copyFrom = function (source) {
  188. this.r = source.r;
  189. this.g = source.g;
  190. this.b = source.b;
  191. this.a = source.a;
  192. };
  193. // Statics
  194. Color4.Lerp = function (left, right, amount) {
  195. var result = new Color4(0, 0, 0, 0);
  196. Color4.LerpToRef(left, right, amount, result);
  197. return result;
  198. };
  199. Color4.LerpToRef = function (left, right, amount, result) {
  200. result.r = left.r + (right.r - left.r) * amount;
  201. result.g = left.g + (right.g - left.g) * amount;
  202. result.b = left.b + (right.b - left.b) * amount;
  203. result.a = left.a + (right.a - left.a) * amount;
  204. };
  205. Color4.FromArray = function (array, offset) {
  206. if (typeof offset === "undefined") { offset = 0; }
  207. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  208. };
  209. Color4.FromInts = function (r, g, b, a) {
  210. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  211. };
  212. return Color4;
  213. })();
  214. BABYLON.Color4 = Color4;
  215. var Vector2 = (function () {
  216. function Vector2(x, y) {
  217. this.x = x;
  218. this.y = y;
  219. }
  220. Vector2.prototype.toString = function () {
  221. return "{X: " + this.x + " Y:" + this.y + "}";
  222. };
  223. // Operators
  224. Vector2.prototype.toArray = function (array, index) {
  225. if (index === undefined) {
  226. index = 0;
  227. }
  228. array[index] = this.x;
  229. array[index + 1] = this.y;
  230. };
  231. Vector2.prototype.asArray = function () {
  232. var result = [];
  233. this.toArray(result, 0);
  234. return result;
  235. };
  236. Vector2.prototype.copyFrom = function (source) {
  237. this.x = source.x;
  238. this.y = source.y;
  239. };
  240. Vector2.prototype.copyFromFloats = function (x, y) {
  241. this.x = x;
  242. this.y = y;
  243. };
  244. Vector2.prototype.add = function (otherVector) {
  245. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  246. };
  247. Vector2.prototype.addVector3 = function (otherVector) {
  248. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  249. };
  250. Vector2.prototype.subtract = function (otherVector) {
  251. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  252. };
  253. Vector2.prototype.subtractInPlace = function (otherVector) {
  254. this.x -= otherVector.x;
  255. this.y -= otherVector.y;
  256. };
  257. Vector2.prototype.multiplyInPlace = function (otherVector) {
  258. this.x *= otherVector.x;
  259. this.y *= otherVector.y;
  260. };
  261. Vector2.prototype.multiply = function (otherVector) {
  262. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  263. };
  264. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  265. result.x = this.x * otherVector.x;
  266. result.y = this.y * otherVector.y;
  267. };
  268. Vector2.prototype.multiplyByFloats = function (x, y) {
  269. return new Vector2(this.x * x, this.y * y);
  270. };
  271. Vector2.prototype.divide = function (otherVector) {
  272. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  273. };
  274. Vector2.prototype.divideToRef = function (otherVector, result) {
  275. result.x = this.x / otherVector.x;
  276. result.y = this.y / otherVector.y;
  277. };
  278. Vector2.prototype.negate = function () {
  279. return new Vector2(-this.x, -this.y);
  280. };
  281. Vector2.prototype.scaleInPlace = function (scale) {
  282. this.x *= scale;
  283. this.y *= scale;
  284. return this;
  285. };
  286. Vector2.prototype.scale = function (scale) {
  287. return new Vector2(this.x * scale, this.y * scale);
  288. };
  289. Vector2.prototype.equals = function (otherVector) {
  290. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  291. };
  292. // Properties
  293. Vector2.prototype.length = function () {
  294. return Math.sqrt(this.x * this.x + this.y * this.y);
  295. };
  296. Vector2.prototype.lengthSquared = function () {
  297. return (this.x * this.x + this.y * this.y);
  298. };
  299. // Methods
  300. Vector2.prototype.normalize = function () {
  301. var len = this.length();
  302. if (len === 0)
  303. return this;
  304. var num = 1.0 / len;
  305. this.x *= num;
  306. this.y *= num;
  307. return this;
  308. };
  309. Vector2.prototype.clone = function () {
  310. return new Vector2(this.x, this.y);
  311. };
  312. // Statics
  313. Vector2.Zero = function () {
  314. return new Vector2(0, 0);
  315. };
  316. Vector2.FromArray = function (array, offset) {
  317. if (!offset) {
  318. offset = 0;
  319. }
  320. return new Vector2(array[offset], array[offset + 1]);
  321. };
  322. Vector2.FromArrayToRef = function (array, offset, result) {
  323. result.x = array[offset];
  324. result.y = array[offset + 1];
  325. };
  326. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  327. var squared = amount * amount;
  328. var cubed = amount * squared;
  329. 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));
  330. 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));
  331. return new Vector2(x, y);
  332. };
  333. Vector2.Clamp = function (value, min, max) {
  334. var x = value.x;
  335. x = (x > max.x) ? max.x : x;
  336. x = (x < min.x) ? min.x : x;
  337. var y = value.y;
  338. y = (y > max.y) ? max.y : y;
  339. y = (y < min.y) ? min.y : y;
  340. return new Vector2(x, y);
  341. };
  342. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  346. var part2 = (-2.0 * cubed) + (3.0 * squared);
  347. var part3 = (cubed - (2.0 * squared)) + amount;
  348. var part4 = cubed - squared;
  349. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  350. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  351. return new Vector2(x, y);
  352. };
  353. Vector2.Lerp = function (start, end, amount) {
  354. var x = start.x + ((end.x - start.x) * amount);
  355. var y = start.y + ((end.y - start.y) * amount);
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Dot = function (left, right) {
  359. return left.x * right.x + left.y * right.y;
  360. };
  361. Vector2.Normalize = function (vector) {
  362. var newVector = vector.clone();
  363. newVector.normalize();
  364. return newVector;
  365. };
  366. Vector2.Minimize = function (left, right) {
  367. var x = (left.x < right.x) ? left.x : right.x;
  368. var y = (left.y < right.y) ? left.y : right.y;
  369. return new Vector2(x, y);
  370. };
  371. Vector2.Maximize = function (left, right) {
  372. var x = (left.x > right.x) ? left.x : right.x;
  373. var y = (left.y > right.y) ? left.y : right.y;
  374. return new Vector2(x, y);
  375. };
  376. Vector2.Transform = function (vector, transformation) {
  377. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  378. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  379. return new Vector2(x, y);
  380. };
  381. Vector2.Distance = function (value1, value2) {
  382. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  383. };
  384. Vector2.DistanceSquared = function (value1, value2) {
  385. var x = value1.x - value2.x;
  386. var y = value1.y - value2.y;
  387. return (x * x) + (y * y);
  388. };
  389. return Vector2;
  390. })();
  391. BABYLON.Vector2 = Vector2;
  392. var Vector3 = (function () {
  393. function Vector3(x, y, z) {
  394. this.x = x;
  395. this.y = y;
  396. this.z = z;
  397. }
  398. Vector3.prototype.toString = function () {
  399. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  400. };
  401. // Operators
  402. Vector3.prototype.asArray = function () {
  403. var result = [];
  404. this.toArray(result, 0);
  405. return result;
  406. };
  407. Vector3.prototype.toArray = function (array, index) {
  408. if (index === undefined) {
  409. index = 0;
  410. }
  411. array[index] = this.x;
  412. array[index + 1] = this.y;
  413. array[index + 2] = this.z;
  414. };
  415. Vector3.prototype.addInPlace = function (otherVector) {
  416. this.x += otherVector.x;
  417. this.y += otherVector.y;
  418. this.z += otherVector.z;
  419. };
  420. Vector3.prototype.add = function (otherVector) {
  421. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  422. };
  423. Vector3.prototype.addToRef = function (otherVector, result) {
  424. result.x = this.x + otherVector.x;
  425. result.y = this.y + otherVector.y;
  426. result.z = this.z + otherVector.z;
  427. };
  428. Vector3.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. this.z -= otherVector.z;
  432. };
  433. Vector3.prototype.subtract = function (otherVector) {
  434. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  435. };
  436. Vector3.prototype.subtractToRef = function (otherVector, result) {
  437. result.x = this.x - otherVector.x;
  438. result.y = this.y - otherVector.y;
  439. result.z = this.z - otherVector.z;
  440. };
  441. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  442. return new Vector3(this.x - x, this.y - y, this.z - z);
  443. };
  444. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  445. result.x = this.x - x;
  446. result.y = this.y - y;
  447. result.z = this.z - z;
  448. };
  449. Vector3.prototype.negate = function () {
  450. return new Vector3(-this.x, -this.y, -this.z);
  451. };
  452. Vector3.prototype.scaleInPlace = function (scale) {
  453. this.x *= scale;
  454. this.y *= scale;
  455. this.z *= scale;
  456. return this;
  457. };
  458. Vector3.prototype.scale = function (scale) {
  459. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  460. };
  461. Vector3.prototype.scaleToRef = function (scale, result) {
  462. result.x = this.x * scale;
  463. result.y = this.y * scale;
  464. result.z = this.z * scale;
  465. };
  466. Vector3.prototype.equals = function (otherVector) {
  467. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  468. };
  469. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  470. 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;
  471. };
  472. Vector3.prototype.equalsToFloats = function (x, y, z) {
  473. return this.x === x && this.y === y && this.z === z;
  474. };
  475. Vector3.prototype.multiplyInPlace = function (otherVector) {
  476. this.x *= otherVector.x;
  477. this.y *= otherVector.y;
  478. this.z *= otherVector.z;
  479. };
  480. Vector3.prototype.multiply = function (otherVector) {
  481. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  482. };
  483. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  484. result.x = this.x * otherVector.x;
  485. result.y = this.y * otherVector.y;
  486. result.z = this.z * otherVector.z;
  487. };
  488. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  489. return new Vector3(this.x * x, this.y * y, this.z * z);
  490. };
  491. Vector3.prototype.divide = function (otherVector) {
  492. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  493. };
  494. Vector3.prototype.divideToRef = function (otherVector, result) {
  495. result.x = this.x / otherVector.x;
  496. result.y = this.y / otherVector.y;
  497. result.z = this.z / otherVector.z;
  498. };
  499. Vector3.prototype.MinimizeInPlace = function (other) {
  500. if (other.x < this.x)
  501. this.x = other.x;
  502. if (other.y < this.y)
  503. this.y = other.y;
  504. if (other.z < this.z)
  505. this.z = other.z;
  506. };
  507. Vector3.prototype.MaximizeInPlace = function (other) {
  508. if (other.x > this.x)
  509. this.x = other.x;
  510. if (other.y > this.y)
  511. this.y = other.y;
  512. if (other.z > this.z)
  513. this.z = other.z;
  514. };
  515. // Properties
  516. Vector3.prototype.length = function () {
  517. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  518. };
  519. Vector3.prototype.lengthSquared = function () {
  520. return (this.x * this.x + this.y * this.y + this.z * this.z);
  521. };
  522. // Methods
  523. Vector3.prototype.normalize = function () {
  524. var len = this.length();
  525. if (len === 0)
  526. return this;
  527. var num = 1.0 / len;
  528. this.x *= num;
  529. this.y *= num;
  530. this.z *= num;
  531. return this;
  532. };
  533. Vector3.prototype.clone = function () {
  534. return new Vector3(this.x, this.y, this.z);
  535. };
  536. Vector3.prototype.copyFrom = function (source) {
  537. this.x = source.x;
  538. this.y = source.y;
  539. this.z = source.z;
  540. };
  541. Vector3.prototype.copyFromFloats = function (x, y, z) {
  542. this.x = x;
  543. this.y = y;
  544. this.z = z;
  545. };
  546. // Statics
  547. Vector3.FromArray = function (array, offset) {
  548. if (!offset) {
  549. offset = 0;
  550. }
  551. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  552. };
  553. Vector3.FromArrayToRef = function (array, offset, result) {
  554. result.x = array[offset];
  555. result.y = array[offset + 1];
  556. result.z = array[offset + 2];
  557. };
  558. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  559. result.x = array[offset];
  560. result.y = array[offset + 1];
  561. result.z = array[offset + 2];
  562. };
  563. Vector3.FromFloatsToRef = function (x, y, z, result) {
  564. result.x = x;
  565. result.y = y;
  566. result.z = z;
  567. };
  568. Vector3.Zero = function () {
  569. return new Vector3(0, 0, 0);
  570. };
  571. Vector3.Up = function () {
  572. return new Vector3(0, 1.0, 0);
  573. };
  574. Vector3.TransformCoordinates = function (vector, transformation) {
  575. var result = Vector3.Zero();
  576. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  577. return result;
  578. };
  579. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  580. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  581. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  582. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  583. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  584. result.x = x / w;
  585. result.y = y / w;
  586. result.z = z / w;
  587. };
  588. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  589. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  590. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  591. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  592. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  593. result.x = rx / rw;
  594. result.y = ry / rw;
  595. result.z = rz / rw;
  596. };
  597. Vector3.TransformNormal = function (vector, transformation) {
  598. var result = Vector3.Zero();
  599. Vector3.TransformNormalToRef(vector, transformation, result);
  600. return result;
  601. };
  602. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  603. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  604. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  605. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  606. };
  607. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  608. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  609. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  610. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  611. };
  612. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  613. var squared = amount * amount;
  614. var cubed = amount * squared;
  615. 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));
  616. 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));
  617. 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));
  618. return new Vector3(x, y, z);
  619. };
  620. Vector3.Clamp = function (value, min, max) {
  621. var x = value.x;
  622. x = (x > max.x) ? max.x : x;
  623. x = (x < min.x) ? min.x : x;
  624. var y = value.y;
  625. y = (y > max.y) ? max.y : y;
  626. y = (y < min.y) ? min.y : y;
  627. var z = value.z;
  628. z = (z > max.z) ? max.z : z;
  629. z = (z < min.z) ? min.z : z;
  630. return new Vector3(x, y, z);
  631. };
  632. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  633. var squared = amount * amount;
  634. var cubed = amount * squared;
  635. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  636. var part2 = (-2.0 * cubed) + (3.0 * squared);
  637. var part3 = (cubed - (2.0 * squared)) + amount;
  638. var part4 = cubed - squared;
  639. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  640. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  641. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  642. return new Vector3(x, y, z);
  643. };
  644. Vector3.Lerp = function (start, end, amount) {
  645. var x = start.x + ((end.x - start.x) * amount);
  646. var y = start.y + ((end.y - start.y) * amount);
  647. var z = start.z + ((end.z - start.z) * amount);
  648. return new Vector3(x, y, z);
  649. };
  650. Vector3.Dot = function (left, right) {
  651. return (left.x * right.x + left.y * right.y + left.z * right.z);
  652. };
  653. Vector3.Cross = function (left, right) {
  654. var result = Vector3.Zero();
  655. Vector3.CrossToRef(left, right, result);
  656. return result;
  657. };
  658. Vector3.CrossToRef = function (left, right, result) {
  659. result.x = left.y * right.z - left.z * right.y;
  660. result.y = left.z * right.x - left.x * right.z;
  661. result.z = left.x * right.y - left.y * right.x;
  662. };
  663. Vector3.Normalize = function (vector) {
  664. var result = Vector3.Zero();
  665. Vector3.NormalizeToRef(vector, result);
  666. return result;
  667. };
  668. Vector3.NormalizeToRef = function (vector, result) {
  669. result.copyFrom(vector);
  670. result.normalize();
  671. };
  672. Vector3.Project = function (vector, world, transform, viewport) {
  673. var cw = viewport.width;
  674. var ch = viewport.height;
  675. var cx = viewport.x;
  676. var cy = viewport.y;
  677. 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);
  678. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  679. return Vector3.TransformCoordinates(vector, finalMatrix);
  680. };
  681. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  682. var matrix = world.multiply(transform);
  683. matrix.invert();
  684. source.x = source.x / viewportWidth * 2 - 1;
  685. source.y = -(source.y / viewportHeight * 2 - 1);
  686. var vector = Vector3.TransformCoordinates(source, matrix);
  687. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  688. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  689. vector = vector.scale(1.0 / num);
  690. }
  691. return vector;
  692. };
  693. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  694. var matrix = world.multiply(view).multiply(projection);
  695. matrix.invert();
  696. source.x = source.x / viewportWidth * 2 - 1;
  697. source.y = -(source.y / viewportHeight * 2 - 1);
  698. var vector = Vector3.TransformCoordinates(source, matrix);
  699. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  700. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  701. vector = vector.scale(1.0 / num);
  702. }
  703. return vector;
  704. };
  705. Vector3.Minimize = function (left, right) {
  706. var min = left.clone();
  707. min.MinimizeInPlace(right);
  708. return min;
  709. };
  710. Vector3.Maximize = function (left, right) {
  711. var max = left.clone();
  712. max.MaximizeInPlace(right);
  713. return max;
  714. };
  715. Vector3.Distance = function (value1, value2) {
  716. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  717. };
  718. Vector3.DistanceSquared = function (value1, value2) {
  719. var x = value1.x - value2.x;
  720. var y = value1.y - value2.y;
  721. var z = value1.z - value2.z;
  722. return (x * x) + (y * y) + (z * z);
  723. };
  724. Vector3.Center = function (value1, value2) {
  725. var center = value1.add(value2);
  726. center.scaleInPlace(0.5);
  727. return center;
  728. };
  729. return Vector3;
  730. })();
  731. BABYLON.Vector3 = Vector3;
  732. //Vector4 class created for EulerAngle class conversion to Quaternion
  733. var Vector4 = (function () {
  734. function Vector4(x, y, z, w) {
  735. this.x = x;
  736. this.y = y;
  737. this.z = z;
  738. this.w = w;
  739. }
  740. Vector4.prototype.toString = function () {
  741. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  742. };
  743. // Operators
  744. Vector4.prototype.asArray = function () {
  745. var result = [];
  746. this.toArray(result, 0);
  747. return result;
  748. };
  749. Vector4.prototype.toArray = function (array, index) {
  750. if (index === undefined) {
  751. index = 0;
  752. }
  753. array[index] = this.x;
  754. array[index + 1] = this.y;
  755. array[index + 2] = this.z;
  756. array[index + 3] = this.w;
  757. };
  758. Vector4.prototype.addInPlace = function (otherVector) {
  759. this.x += otherVector.x;
  760. this.y += otherVector.y;
  761. this.z += otherVector.z;
  762. this.w += otherVector.w;
  763. };
  764. Vector4.prototype.add = function (otherVector) {
  765. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  766. };
  767. Vector4.prototype.addToRef = function (otherVector, result) {
  768. result.x = this.x + otherVector.x;
  769. result.y = this.y + otherVector.y;
  770. result.z = this.z + otherVector.z;
  771. result.w = this.w + otherVector.w;
  772. };
  773. Vector4.prototype.subtractInPlace = function (otherVector) {
  774. this.x -= otherVector.x;
  775. this.y -= otherVector.y;
  776. this.z -= otherVector.z;
  777. this.w -= otherVector.w;
  778. };
  779. Vector4.prototype.subtract = function (otherVector) {
  780. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  781. };
  782. Vector4.prototype.subtractToRef = function (otherVector, result) {
  783. result.x = this.x - otherVector.x;
  784. result.y = this.y - otherVector.y;
  785. result.z = this.z - otherVector.z;
  786. result.w = this.w - otherVector.w;
  787. };
  788. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  789. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  790. };
  791. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  792. result.x = this.x - x;
  793. result.y = this.y - y;
  794. result.z = this.z - z;
  795. result.w = this.w - w;
  796. };
  797. Vector4.prototype.negate = function () {
  798. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  799. };
  800. Vector4.prototype.scaleInPlace = function (scale) {
  801. this.x *= scale;
  802. this.y *= scale;
  803. this.z *= scale;
  804. this.w *= scale;
  805. return this;
  806. };
  807. Vector4.prototype.scale = function (scale) {
  808. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  809. };
  810. Vector4.prototype.scaleToRef = function (scale, result) {
  811. result.x = this.x * scale;
  812. result.y = this.y * scale;
  813. result.z = this.z * scale;
  814. result.w = this.w * scale;
  815. };
  816. Vector4.prototype.equals = function (otherVector) {
  817. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  818. };
  819. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  820. 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;
  821. };
  822. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  823. return this.x === x && this.y === y && this.z === z && this.w === w;
  824. };
  825. Vector4.prototype.multiplyInPlace = function (otherVector) {
  826. this.x *= otherVector.x;
  827. this.y *= otherVector.y;
  828. this.z *= otherVector.z;
  829. this.w *= otherVector.w;
  830. };
  831. Vector4.prototype.multiply = function (otherVector) {
  832. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  833. };
  834. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  835. result.x = this.x * otherVector.x;
  836. result.y = this.y * otherVector.y;
  837. result.z = this.z * otherVector.z;
  838. result.w = this.w * otherVector.w;
  839. };
  840. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  841. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  842. };
  843. Vector4.prototype.divide = function (otherVector) {
  844. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  845. };
  846. Vector4.prototype.divideToRef = function (otherVector, result) {
  847. result.x = this.x / otherVector.x;
  848. result.y = this.y / otherVector.y;
  849. result.z = this.z / otherVector.z;
  850. result.w = this.w / otherVector.w;
  851. };
  852. Vector4.prototype.MinimizeInPlace = function (other) {
  853. if (other.x < this.x)
  854. this.x = other.x;
  855. if (other.y < this.y)
  856. this.y = other.y;
  857. if (other.z < this.z)
  858. this.z = other.z;
  859. if (other.w < this.w)
  860. this.w = other.w;
  861. };
  862. Vector4.prototype.MaximizeInPlace = function (other) {
  863. if (other.x > this.x)
  864. this.x = other.x;
  865. if (other.y > this.y)
  866. this.y = other.y;
  867. if (other.z > this.z)
  868. this.z = other.z;
  869. if (other.w > this.w)
  870. this.w = other.w;
  871. };
  872. // Properties
  873. Vector4.prototype.length = function () {
  874. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  875. };
  876. Vector4.prototype.lengthSquared = function () {
  877. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  878. };
  879. // Methods
  880. Vector4.prototype.normalize = function () {
  881. var len = this.length();
  882. if (len === 0)
  883. return this;
  884. var num = 1.0 / len;
  885. this.x *= num;
  886. this.y *= num;
  887. this.z *= num;
  888. this.w *= num;
  889. return this;
  890. };
  891. Vector4.prototype.clone = function () {
  892. return new Vector4(this.x, this.y, this.z, this.w);
  893. };
  894. Vector4.prototype.copyFrom = function (source) {
  895. this.x = source.x;
  896. this.y = source.y;
  897. this.z = source.z;
  898. this.w = source.w;
  899. };
  900. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  901. this.x = x;
  902. this.y = y;
  903. this.z = z;
  904. this.w = w;
  905. };
  906. // Statics
  907. Vector4.FromArray = function (array, offset) {
  908. if (!offset) {
  909. offset = 0;
  910. }
  911. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  912. };
  913. Vector4.FromArrayToRef = 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.FromFloatArrayToRef = function (array, offset, result) {
  920. result.x = array[offset];
  921. result.y = array[offset + 1];
  922. result.z = array[offset + 2];
  923. result.w = array[offset + 3];
  924. };
  925. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  926. result.x = x;
  927. result.y = y;
  928. result.z = z;
  929. result.w = w;
  930. };
  931. Vector4.Zero = function () {
  932. return new Vector4(0, 0, 0, 0);
  933. };
  934. Vector4.Normalize = function (vector) {
  935. var result = Vector4.Zero();
  936. Vector4.NormalizeToRef(vector, result);
  937. return result;
  938. };
  939. Vector4.NormalizeToRef = function (vector, result) {
  940. result.copyFrom(vector);
  941. result.normalize();
  942. };
  943. Vector4.Minimize = function (left, right) {
  944. var min = left.clone();
  945. min.MinimizeInPlace(right);
  946. return min;
  947. };
  948. Vector4.Maximize = function (left, right) {
  949. var max = left.clone();
  950. max.MaximizeInPlace(right);
  951. return max;
  952. };
  953. Vector4.Distance = function (value1, value2) {
  954. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  955. };
  956. Vector4.DistanceSquared = function (value1, value2) {
  957. var x = value1.x - value2.x;
  958. var y = value1.y - value2.y;
  959. var z = value1.z - value2.z;
  960. var w = value1.w - value2.w;
  961. return (x * x) + (y * y) + (z * z) + (w * w);
  962. };
  963. Vector4.Center = function (value1, value2) {
  964. var center = value1.add(value2);
  965. center.scaleInPlace(0.5);
  966. return center;
  967. };
  968. return Vector4;
  969. })();
  970. BABYLON.Vector4 = Vector4;
  971. var Quaternion = (function () {
  972. function Quaternion(x, y, z, w) {
  973. if (typeof x === "undefined") { x = 0; }
  974. if (typeof y === "undefined") { y = 0; }
  975. if (typeof z === "undefined") { z = 0; }
  976. if (typeof w === "undefined") { w = 1; }
  977. this.x = x;
  978. this.y = y;
  979. this.z = z;
  980. this.w = w;
  981. }
  982. Quaternion.prototype.toString = function () {
  983. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  984. };
  985. Quaternion.prototype.asArray = function () {
  986. return [this.x, this.y, this.z, this.w];
  987. };
  988. Quaternion.prototype.equals = function (otherQuaternion) {
  989. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  990. };
  991. Quaternion.prototype.clone = function () {
  992. return new Quaternion(this.x, this.y, this.z, this.w);
  993. };
  994. Quaternion.prototype.copyFrom = function (other) {
  995. this.x = other.x;
  996. this.y = other.y;
  997. this.z = other.z;
  998. this.w = other.w;
  999. };
  1000. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1001. this.x = x;
  1002. this.y = y;
  1003. this.z = z;
  1004. this.w = w;
  1005. };
  1006. Quaternion.prototype.add = function (other) {
  1007. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1008. };
  1009. Quaternion.prototype.subtract = function (other) {
  1010. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1011. };
  1012. Quaternion.prototype.scale = function (value) {
  1013. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1014. };
  1015. Quaternion.prototype.multiply = function (q1) {
  1016. var result = new Quaternion(0, 0, 0, 1.0);
  1017. this.multiplyToRef(q1, result);
  1018. return result;
  1019. };
  1020. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1021. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1022. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1023. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1024. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1025. };
  1026. Quaternion.prototype.length = function () {
  1027. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1028. };
  1029. Quaternion.prototype.normalize = function () {
  1030. var length = 1.0 / this.length();
  1031. this.x *= length;
  1032. this.y *= length;
  1033. this.z *= length;
  1034. this.w *= length;
  1035. };
  1036. Quaternion.prototype.toEulerAngles = function () {
  1037. var result = Vector3.Zero();
  1038. this.toEulerAnglesToRef(result);
  1039. return result;
  1040. };
  1041. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1042. //result is an EulerAngles in the in the z-x-z convention
  1043. var qx = this.x;
  1044. var qy = this.y;
  1045. var qz = this.z;
  1046. var qw = this.w;
  1047. var qxy = qx * qy;
  1048. var qxz = qx * qz;
  1049. var qwy = qw * qy;
  1050. var qwz = qw * qz;
  1051. var qwx = qw * qx;
  1052. var qyz = qy * qz;
  1053. var sqx = qx * qx;
  1054. var sqy = qy * qy;
  1055. var determinant = sqx + sqy;
  1056. if (determinant !== 0.000 && determinant !== 1.000) {
  1057. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1058. result.y = Math.acos(1 - 2 * determinant);
  1059. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1060. } else {
  1061. if (determinant === 0.0) {
  1062. result.x = 0.0;
  1063. result.y = 0.0;
  1064. 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)
  1065. } else {
  1066. 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)
  1067. result.y = Math.PI;
  1068. result.z = 0.0;
  1069. }
  1070. }
  1071. };
  1072. Quaternion.prototype.toRotationMatrix = function (result) {
  1073. var xx = this.x * this.x;
  1074. var yy = this.y * this.y;
  1075. var zz = this.z * this.z;
  1076. var xy = this.x * this.y;
  1077. var zw = this.z * this.w;
  1078. var zx = this.z * this.x;
  1079. var yw = this.y * this.w;
  1080. var yz = this.y * this.z;
  1081. var xw = this.x * this.w;
  1082. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1083. result.m[1] = 2.0 * (xy + zw);
  1084. result.m[2] = 2.0 * (zx - yw);
  1085. result.m[3] = 0;
  1086. result.m[4] = 2.0 * (xy - zw);
  1087. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1088. result.m[6] = 2.0 * (yz + xw);
  1089. result.m[7] = 0;
  1090. result.m[8] = 2.0 * (zx + yw);
  1091. result.m[9] = 2.0 * (yz - xw);
  1092. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1093. result.m[11] = 0;
  1094. result.m[12] = 0;
  1095. result.m[13] = 0;
  1096. result.m[14] = 0;
  1097. result.m[15] = 1.0;
  1098. };
  1099. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1100. var data = matrix.m;
  1101. var m11 = data[0], m12 = data[4], m13 = data[8];
  1102. var m21 = data[1], m22 = data[5], m23 = data[9];
  1103. var m31 = data[2], m32 = data[6], m33 = data[10];
  1104. var trace = m11 + m22 + m33;
  1105. var s;
  1106. if (trace > 0) {
  1107. s = 0.5 / Math.sqrt(trace + 1.0);
  1108. this.w = 0.25 / s;
  1109. this.x = (m32 - m23) * s;
  1110. this.y = (m13 - m31) * s;
  1111. this.z = (m21 - m12) * s;
  1112. return;
  1113. }
  1114. if (m11 > m22 && m11 > m33) {
  1115. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1116. this.w = (m32 - m23) / s;
  1117. this.x = 0.25 * s;
  1118. this.y = (m12 + m21) / s;
  1119. this.z = (m13 + m31) / s;
  1120. return;
  1121. }
  1122. if (m22 > m33) {
  1123. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1124. this.w = (m13 - m31) / s;
  1125. this.x = (m12 + m21) / s;
  1126. this.y = 0.25 * s;
  1127. this.z = (m23 + m32) / s;
  1128. return;
  1129. }
  1130. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1131. this.w = (m21 - m12) / s;
  1132. this.x = (m13 + m31) / s;
  1133. this.y = (m23 + m32) / s;
  1134. this.z = 0.25 * s;
  1135. };
  1136. // Statics
  1137. Quaternion.Inverse = function (q) {
  1138. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1139. };
  1140. Quaternion.Identity = function () {
  1141. return new Quaternion(0, 0, 0, 1);
  1142. };
  1143. Quaternion.RotationAxis = function (axis, angle) {
  1144. var result = new Quaternion();
  1145. var sin = Math.sin(angle / 2);
  1146. result.w = Math.cos(angle / 2);
  1147. result.x = axis.x * sin;
  1148. result.y = axis.y * sin;
  1149. result.z = axis.z * sin;
  1150. return result;
  1151. };
  1152. Quaternion.FromArray = function (array, offset) {
  1153. if (!offset) {
  1154. offset = 0;
  1155. }
  1156. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1157. };
  1158. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1159. var result = new Quaternion();
  1160. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1161. return result;
  1162. };
  1163. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1164. var halfRoll = roll * 0.5;
  1165. var halfPitch = pitch * 0.5;
  1166. var halfYaw = yaw * 0.5;
  1167. var sinRoll = Math.sin(halfRoll);
  1168. var cosRoll = Math.cos(halfRoll);
  1169. var sinPitch = Math.sin(halfPitch);
  1170. var cosPitch = Math.cos(halfPitch);
  1171. var sinYaw = Math.sin(halfYaw);
  1172. var cosYaw = Math.cos(halfYaw);
  1173. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1174. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1175. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1176. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1177. };
  1178. Quaternion.Slerp = function (left, right, amount) {
  1179. var num2;
  1180. var num3;
  1181. var num = amount;
  1182. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1183. var flag = false;
  1184. if (num4 < 0) {
  1185. flag = true;
  1186. num4 = -num4;
  1187. }
  1188. if (num4 > 0.999999) {
  1189. num3 = 1 - num;
  1190. num2 = flag ? -num : num;
  1191. } else {
  1192. var num5 = Math.acos(num4);
  1193. var num6 = (1.0 / Math.sin(num5));
  1194. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1195. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1196. }
  1197. 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));
  1198. };
  1199. return Quaternion;
  1200. })();
  1201. BABYLON.Quaternion = Quaternion;
  1202. var Matrix = (function () {
  1203. function Matrix() {
  1204. this.m = new Float32Array(16);
  1205. }
  1206. // Properties
  1207. Matrix.prototype.isIdentity = function () {
  1208. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1209. return false;
  1210. 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)
  1211. return false;
  1212. return true;
  1213. };
  1214. Matrix.prototype.determinant = function () {
  1215. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1216. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1217. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1218. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1219. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1220. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1221. 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))));
  1222. };
  1223. // Methods
  1224. Matrix.prototype.toArray = function () {
  1225. return this.m;
  1226. };
  1227. Matrix.prototype.asArray = function () {
  1228. return this.toArray();
  1229. };
  1230. Matrix.prototype.invert = function () {
  1231. this.invertToRef(this);
  1232. };
  1233. Matrix.prototype.invertToRef = function (other) {
  1234. var l1 = this.m[0];
  1235. var l2 = this.m[1];
  1236. var l3 = this.m[2];
  1237. var l4 = this.m[3];
  1238. var l5 = this.m[4];
  1239. var l6 = this.m[5];
  1240. var l7 = this.m[6];
  1241. var l8 = this.m[7];
  1242. var l9 = this.m[8];
  1243. var l10 = this.m[9];
  1244. var l11 = this.m[10];
  1245. var l12 = this.m[11];
  1246. var l13 = this.m[12];
  1247. var l14 = this.m[13];
  1248. var l15 = this.m[14];
  1249. var l16 = this.m[15];
  1250. var l17 = (l11 * l16) - (l12 * l15);
  1251. var l18 = (l10 * l16) - (l12 * l14);
  1252. var l19 = (l10 * l15) - (l11 * l14);
  1253. var l20 = (l9 * l16) - (l12 * l13);
  1254. var l21 = (l9 * l15) - (l11 * l13);
  1255. var l22 = (l9 * l14) - (l10 * l13);
  1256. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1257. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1258. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1259. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1260. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1261. var l28 = (l7 * l16) - (l8 * l15);
  1262. var l29 = (l6 * l16) - (l8 * l14);
  1263. var l30 = (l6 * l15) - (l7 * l14);
  1264. var l31 = (l5 * l16) - (l8 * l13);
  1265. var l32 = (l5 * l15) - (l7 * l13);
  1266. var l33 = (l5 * l14) - (l6 * l13);
  1267. var l34 = (l7 * l12) - (l8 * l11);
  1268. var l35 = (l6 * l12) - (l8 * l10);
  1269. var l36 = (l6 * l11) - (l7 * l10);
  1270. var l37 = (l5 * l12) - (l8 * l9);
  1271. var l38 = (l5 * l11) - (l7 * l9);
  1272. var l39 = (l5 * l10) - (l6 * l9);
  1273. other.m[0] = l23 * l27;
  1274. other.m[4] = l24 * l27;
  1275. other.m[8] = l25 * l27;
  1276. other.m[12] = l26 * l27;
  1277. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1278. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1279. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1280. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1281. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1282. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1283. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1284. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1285. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1286. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1287. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1288. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1289. };
  1290. Matrix.prototype.setTranslation = function (vector3) {
  1291. this.m[12] = vector3.x;
  1292. this.m[13] = vector3.y;
  1293. this.m[14] = vector3.z;
  1294. };
  1295. Matrix.prototype.multiply = function (other) {
  1296. var result = new Matrix();
  1297. this.multiplyToRef(other, result);
  1298. return result;
  1299. };
  1300. Matrix.prototype.copyFrom = function (other) {
  1301. for (var index = 0; index < 16; index++) {
  1302. this.m[index] = other.m[index];
  1303. }
  1304. };
  1305. Matrix.prototype.copyToArray = function (array, offset) {
  1306. if (typeof offset === "undefined") { offset = 0; }
  1307. for (var index = 0; index < 16; index++) {
  1308. array[offset + index] = this.m[index];
  1309. }
  1310. };
  1311. Matrix.prototype.multiplyToRef = function (other, result) {
  1312. this.multiplyToArray(other, result.m, 0);
  1313. };
  1314. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1315. var tm0 = this.m[0];
  1316. var tm1 = this.m[1];
  1317. var tm2 = this.m[2];
  1318. var tm3 = this.m[3];
  1319. var tm4 = this.m[4];
  1320. var tm5 = this.m[5];
  1321. var tm6 = this.m[6];
  1322. var tm7 = this.m[7];
  1323. var tm8 = this.m[8];
  1324. var tm9 = this.m[9];
  1325. var tm10 = this.m[10];
  1326. var tm11 = this.m[11];
  1327. var tm12 = this.m[12];
  1328. var tm13 = this.m[13];
  1329. var tm14 = this.m[14];
  1330. var tm15 = this.m[15];
  1331. var om0 = other.m[0];
  1332. var om1 = other.m[1];
  1333. var om2 = other.m[2];
  1334. var om3 = other.m[3];
  1335. var om4 = other.m[4];
  1336. var om5 = other.m[5];
  1337. var om6 = other.m[6];
  1338. var om7 = other.m[7];
  1339. var om8 = other.m[8];
  1340. var om9 = other.m[9];
  1341. var om10 = other.m[10];
  1342. var om11 = other.m[11];
  1343. var om12 = other.m[12];
  1344. var om13 = other.m[13];
  1345. var om14 = other.m[14];
  1346. var om15 = other.m[15];
  1347. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1348. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1349. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1350. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1351. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1352. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1353. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1354. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1355. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1356. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1357. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1358. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1359. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1360. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1361. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1362. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1363. };
  1364. Matrix.prototype.equals = function (value) {
  1365. 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]);
  1366. };
  1367. Matrix.prototype.clone = function () {
  1368. 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]);
  1369. };
  1370. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1371. translation.x = this.m[12];
  1372. translation.y = this.m[13];
  1373. translation.z = this.m[14];
  1374. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1375. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1376. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1377. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1378. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1379. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1380. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1381. rotation.x = 0;
  1382. rotation.y = 0;
  1383. rotation.z = 0;
  1384. rotation.w = 1;
  1385. return false;
  1386. }
  1387. var rotationMatrix = BABYLON.Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1388. rotation.fromRotationMatrix(rotationMatrix);
  1389. return true;
  1390. };
  1391. // Statics
  1392. Matrix.FromArray = function (array, offset) {
  1393. var result = new Matrix();
  1394. if (!offset) {
  1395. offset = 0;
  1396. }
  1397. Matrix.FromArrayToRef(array, offset, result);
  1398. return result;
  1399. };
  1400. Matrix.FromArrayToRef = function (array, offset, result) {
  1401. for (var index = 0; index < 16; index++) {
  1402. result.m[index] = array[index + offset];
  1403. }
  1404. };
  1405. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1406. result.m[0] = initialM11;
  1407. result.m[1] = initialM12;
  1408. result.m[2] = initialM13;
  1409. result.m[3] = initialM14;
  1410. result.m[4] = initialM21;
  1411. result.m[5] = initialM22;
  1412. result.m[6] = initialM23;
  1413. result.m[7] = initialM24;
  1414. result.m[8] = initialM31;
  1415. result.m[9] = initialM32;
  1416. result.m[10] = initialM33;
  1417. result.m[11] = initialM34;
  1418. result.m[12] = initialM41;
  1419. result.m[13] = initialM42;
  1420. result.m[14] = initialM43;
  1421. result.m[15] = initialM44;
  1422. };
  1423. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1424. var result = new Matrix();
  1425. result.m[0] = initialM11;
  1426. result.m[1] = initialM12;
  1427. result.m[2] = initialM13;
  1428. result.m[3] = initialM14;
  1429. result.m[4] = initialM21;
  1430. result.m[5] = initialM22;
  1431. result.m[6] = initialM23;
  1432. result.m[7] = initialM24;
  1433. result.m[8] = initialM31;
  1434. result.m[9] = initialM32;
  1435. result.m[10] = initialM33;
  1436. result.m[11] = initialM34;
  1437. result.m[12] = initialM41;
  1438. result.m[13] = initialM42;
  1439. result.m[14] = initialM43;
  1440. result.m[15] = initialM44;
  1441. return result;
  1442. };
  1443. Matrix.Compose = function (scale, rotation, translation) {
  1444. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1445. var rotationMatrix = Matrix.Identity();
  1446. rotation.toRotationMatrix(rotationMatrix);
  1447. result = result.multiply(rotationMatrix);
  1448. result.setTranslation(translation);
  1449. return result;
  1450. };
  1451. Matrix.Identity = function () {
  1452. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1453. };
  1454. Matrix.IdentityToRef = function (result) {
  1455. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1456. };
  1457. Matrix.Zero = function () {
  1458. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1459. };
  1460. Matrix.RotationX = function (angle) {
  1461. var result = new Matrix();
  1462. Matrix.RotationXToRef(angle, result);
  1463. return result;
  1464. };
  1465. Matrix.Invert = function (source) {
  1466. var result = new Matrix();
  1467. source.invertToRef(result);
  1468. return result;
  1469. };
  1470. Matrix.RotationXToRef = function (angle, result) {
  1471. var s = Math.sin(angle);
  1472. var c = Math.cos(angle);
  1473. result.m[0] = 1.0;
  1474. result.m[15] = 1.0;
  1475. result.m[5] = c;
  1476. result.m[10] = c;
  1477. result.m[9] = -s;
  1478. result.m[6] = s;
  1479. result.m[1] = 0;
  1480. result.m[2] = 0;
  1481. result.m[3] = 0;
  1482. result.m[4] = 0;
  1483. result.m[7] = 0;
  1484. result.m[8] = 0;
  1485. result.m[11] = 0;
  1486. result.m[12] = 0;
  1487. result.m[13] = 0;
  1488. result.m[14] = 0;
  1489. };
  1490. Matrix.RotationY = function (angle) {
  1491. var result = new Matrix();
  1492. Matrix.RotationYToRef(angle, result);
  1493. return result;
  1494. };
  1495. Matrix.RotationYToRef = function (angle, result) {
  1496. var s = Math.sin(angle);
  1497. var c = Math.cos(angle);
  1498. result.m[5] = 1.0;
  1499. result.m[15] = 1.0;
  1500. result.m[0] = c;
  1501. result.m[2] = -s;
  1502. result.m[8] = s;
  1503. result.m[10] = c;
  1504. result.m[1] = 0;
  1505. result.m[3] = 0;
  1506. result.m[4] = 0;
  1507. result.m[6] = 0;
  1508. result.m[7] = 0;
  1509. result.m[9] = 0;
  1510. result.m[11] = 0;
  1511. result.m[12] = 0;
  1512. result.m[13] = 0;
  1513. result.m[14] = 0;
  1514. };
  1515. Matrix.RotationZ = function (angle) {
  1516. var result = new Matrix();
  1517. Matrix.RotationZToRef(angle, result);
  1518. return result;
  1519. };
  1520. Matrix.RotationZToRef = function (angle, result) {
  1521. var s = Math.sin(angle);
  1522. var c = Math.cos(angle);
  1523. result.m[10] = 1.0;
  1524. result.m[15] = 1.0;
  1525. result.m[0] = c;
  1526. result.m[1] = s;
  1527. result.m[4] = -s;
  1528. result.m[5] = c;
  1529. result.m[2] = 0;
  1530. result.m[3] = 0;
  1531. result.m[6] = 0;
  1532. result.m[7] = 0;
  1533. result.m[8] = 0;
  1534. result.m[9] = 0;
  1535. result.m[11] = 0;
  1536. result.m[12] = 0;
  1537. result.m[13] = 0;
  1538. result.m[14] = 0;
  1539. };
  1540. Matrix.RotationAxis = function (axis, angle) {
  1541. var s = Math.sin(-angle);
  1542. var c = Math.cos(-angle);
  1543. var c1 = 1 - c;
  1544. axis.normalize();
  1545. var result = Matrix.Zero();
  1546. result.m[0] = (axis.x * axis.x) * c1 + c;
  1547. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1548. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1549. result.m[3] = 0.0;
  1550. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1551. result.m[5] = (axis.y * axis.y) * c1 + c;
  1552. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1553. result.m[7] = 0.0;
  1554. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1555. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1556. result.m[10] = (axis.z * axis.z) * c1 + c;
  1557. result.m[11] = 0.0;
  1558. result.m[15] = 1.0;
  1559. return result;
  1560. };
  1561. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1562. var result = new Matrix();
  1563. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1564. return result;
  1565. };
  1566. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1567. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1568. this._tempQuaternion.toRotationMatrix(result);
  1569. };
  1570. Matrix.Scaling = function (x, y, z) {
  1571. var result = Matrix.Zero();
  1572. Matrix.ScalingToRef(x, y, z, result);
  1573. return result;
  1574. };
  1575. Matrix.ScalingToRef = function (x, y, z, result) {
  1576. result.m[0] = x;
  1577. result.m[1] = 0;
  1578. result.m[2] = 0;
  1579. result.m[3] = 0;
  1580. result.m[4] = 0;
  1581. result.m[5] = y;
  1582. result.m[6] = 0;
  1583. result.m[7] = 0;
  1584. result.m[8] = 0;
  1585. result.m[9] = 0;
  1586. result.m[10] = z;
  1587. result.m[11] = 0;
  1588. result.m[12] = 0;
  1589. result.m[13] = 0;
  1590. result.m[14] = 0;
  1591. result.m[15] = 1.0;
  1592. };
  1593. Matrix.Translation = function (x, y, z) {
  1594. var result = Matrix.Identity();
  1595. Matrix.TranslationToRef(x, y, z, result);
  1596. return result;
  1597. };
  1598. Matrix.TranslationToRef = function (x, y, z, result) {
  1599. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1600. };
  1601. Matrix.LookAtLH = function (eye, target, up) {
  1602. var result = Matrix.Zero();
  1603. Matrix.LookAtLHToRef(eye, target, up, result);
  1604. return result;
  1605. };
  1606. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1607. // Z axis
  1608. target.subtractToRef(eye, this._zAxis);
  1609. this._zAxis.normalize();
  1610. // X axis
  1611. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1612. this._xAxis.normalize();
  1613. // Y axis
  1614. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1615. this._yAxis.normalize();
  1616. // Eye angles
  1617. var ex = -Vector3.Dot(this._xAxis, eye);
  1618. var ey = -Vector3.Dot(this._yAxis, eye);
  1619. var ez = -Vector3.Dot(this._zAxis, eye);
  1620. 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);
  1621. };
  1622. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1623. var hw = 2.0 / width;
  1624. var hh = 2.0 / height;
  1625. var id = 1.0 / (zfar - znear);
  1626. var nid = znear / (znear - zfar);
  1627. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1628. };
  1629. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1630. var matrix = Matrix.Zero();
  1631. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1632. return matrix;
  1633. };
  1634. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1635. result.m[0] = 2.0 / (right - left);
  1636. result.m[1] = result.m[2] = result.m[3] = 0;
  1637. result.m[5] = 2.0 / (top - bottom);
  1638. result.m[4] = result.m[6] = result.m[7] = 0;
  1639. result.m[10] = -1.0 / (znear - zfar);
  1640. result.m[8] = result.m[9] = result.m[11] = 0;
  1641. result.m[12] = (left + right) / (left - right);
  1642. result.m[13] = (top + bottom) / (bottom - top);
  1643. result.m[14] = znear / (znear - zfar);
  1644. result.m[15] = 1.0;
  1645. };
  1646. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1647. var matrix = Matrix.Zero();
  1648. matrix.m[0] = (2.0 * znear) / width;
  1649. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1650. matrix.m[5] = (2.0 * znear) / height;
  1651. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1652. matrix.m[10] = -zfar / (znear - zfar);
  1653. matrix.m[8] = matrix.m[9] = 0.0;
  1654. matrix.m[11] = 1.0;
  1655. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1656. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1657. return matrix;
  1658. };
  1659. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1660. var matrix = Matrix.Zero();
  1661. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1662. return matrix;
  1663. };
  1664. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1665. var tan = 1.0 / (Math.tan(fov * 0.5));
  1666. result.m[0] = tan / aspect;
  1667. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1668. result.m[5] = tan;
  1669. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1670. result.m[8] = result.m[9] = 0.0;
  1671. result.m[10] = -zfar / (znear - zfar);
  1672. result.m[11] = 1.0;
  1673. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1674. result.m[14] = (znear * zfar) / (znear - zfar);
  1675. };
  1676. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1677. var cw = viewport.width;
  1678. var ch = viewport.height;
  1679. var cx = viewport.x;
  1680. var cy = viewport.y;
  1681. 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);
  1682. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1683. };
  1684. Matrix.Transpose = function (matrix) {
  1685. var result = new Matrix();
  1686. result.m[0] = matrix.m[0];
  1687. result.m[1] = matrix.m[4];
  1688. result.m[2] = matrix.m[8];
  1689. result.m[3] = matrix.m[12];
  1690. result.m[4] = matrix.m[1];
  1691. result.m[5] = matrix.m[5];
  1692. result.m[6] = matrix.m[9];
  1693. result.m[7] = matrix.m[13];
  1694. result.m[8] = matrix.m[2];
  1695. result.m[9] = matrix.m[6];
  1696. result.m[10] = matrix.m[10];
  1697. result.m[11] = matrix.m[14];
  1698. result.m[12] = matrix.m[3];
  1699. result.m[13] = matrix.m[7];
  1700. result.m[14] = matrix.m[11];
  1701. result.m[15] = matrix.m[15];
  1702. return result;
  1703. };
  1704. Matrix.Reflection = function (plane) {
  1705. var matrix = new Matrix();
  1706. Matrix.ReflectionToRef(plane, matrix);
  1707. return matrix;
  1708. };
  1709. Matrix.ReflectionToRef = function (plane, result) {
  1710. plane.normalize();
  1711. var x = plane.normal.x;
  1712. var y = plane.normal.y;
  1713. var z = plane.normal.z;
  1714. var temp = -2 * x;
  1715. var temp2 = -2 * y;
  1716. var temp3 = -2 * z;
  1717. result.m[0] = (temp * x) + 1;
  1718. result.m[1] = temp2 * x;
  1719. result.m[2] = temp3 * x;
  1720. result.m[3] = 0.0;
  1721. result.m[4] = temp * y;
  1722. result.m[5] = (temp2 * y) + 1;
  1723. result.m[6] = temp3 * y;
  1724. result.m[7] = 0.0;
  1725. result.m[8] = temp * z;
  1726. result.m[9] = temp2 * z;
  1727. result.m[10] = (temp3 * z) + 1;
  1728. result.m[11] = 0.0;
  1729. result.m[12] = temp * plane.d;
  1730. result.m[13] = temp2 * plane.d;
  1731. result.m[14] = temp3 * plane.d;
  1732. result.m[15] = 1.0;
  1733. };
  1734. Matrix._tempQuaternion = new Quaternion();
  1735. Matrix._xAxis = Vector3.Zero();
  1736. Matrix._yAxis = Vector3.Zero();
  1737. Matrix._zAxis = Vector3.Zero();
  1738. return Matrix;
  1739. })();
  1740. BABYLON.Matrix = Matrix;
  1741. var Plane = (function () {
  1742. function Plane(a, b, c, d) {
  1743. this.normal = new Vector3(a, b, c);
  1744. this.d = d;
  1745. }
  1746. Plane.prototype.asArray = function () {
  1747. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1748. };
  1749. // Methods
  1750. Plane.prototype.clone = function () {
  1751. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1752. };
  1753. Plane.prototype.normalize = function () {
  1754. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1755. var magnitude = 0;
  1756. if (norm !== 0) {
  1757. magnitude = 1.0 / norm;
  1758. }
  1759. this.normal.x *= magnitude;
  1760. this.normal.y *= magnitude;
  1761. this.normal.z *= magnitude;
  1762. this.d *= magnitude;
  1763. };
  1764. Plane.prototype.transform = function (transformation) {
  1765. var transposedMatrix = Matrix.Transpose(transformation);
  1766. var x = this.normal.x;
  1767. var y = this.normal.y;
  1768. var z = this.normal.z;
  1769. var d = this.d;
  1770. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1771. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1772. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1773. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1774. return new Plane(normalX, normalY, normalZ, finalD);
  1775. };
  1776. Plane.prototype.dotCoordinate = function (point) {
  1777. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1778. };
  1779. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1780. var x1 = point2.x - point1.x;
  1781. var y1 = point2.y - point1.y;
  1782. var z1 = point2.z - point1.z;
  1783. var x2 = point3.x - point1.x;
  1784. var y2 = point3.y - point1.y;
  1785. var z2 = point3.z - point1.z;
  1786. var yz = (y1 * z2) - (z1 * y2);
  1787. var xz = (z1 * x2) - (x1 * z2);
  1788. var xy = (x1 * y2) - (y1 * x2);
  1789. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1790. var invPyth;
  1791. if (pyth !== 0) {
  1792. invPyth = 1.0 / pyth;
  1793. } else {
  1794. invPyth = 0;
  1795. }
  1796. this.normal.x = yz * invPyth;
  1797. this.normal.y = xz * invPyth;
  1798. this.normal.z = xy * invPyth;
  1799. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1800. };
  1801. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1802. var dot = Vector3.Dot(this.normal, direction);
  1803. return (dot <= epsilon);
  1804. };
  1805. Plane.prototype.signedDistanceTo = function (point) {
  1806. return Vector3.Dot(point, this.normal) + this.d;
  1807. };
  1808. // Statics
  1809. Plane.FromArray = function (array) {
  1810. return new Plane(array[0], array[1], array[2], array[3]);
  1811. };
  1812. Plane.FromPoints = function (point1, point2, point3) {
  1813. var result = new Plane(0, 0, 0, 0);
  1814. result.copyFromPoints(point1, point2, point3);
  1815. return result;
  1816. };
  1817. Plane.FromPositionAndNormal = function (origin, normal) {
  1818. var result = new Plane(0, 0, 0, 0);
  1819. normal.normalize();
  1820. result.normal = normal;
  1821. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1822. return result;
  1823. };
  1824. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1825. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1826. return Vector3.Dot(point, normal) + d;
  1827. };
  1828. return Plane;
  1829. })();
  1830. BABYLON.Plane = Plane;
  1831. var Viewport = (function () {
  1832. function Viewport(x, y, width, height) {
  1833. this.x = x;
  1834. this.y = y;
  1835. this.width = width;
  1836. this.height = height;
  1837. }
  1838. Viewport.prototype.toGlobal = function (engine) {
  1839. var width = engine.getRenderWidth();
  1840. var height = engine.getRenderHeight();
  1841. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1842. };
  1843. return Viewport;
  1844. })();
  1845. BABYLON.Viewport = Viewport;
  1846. var Frustum = (function () {
  1847. function Frustum() {
  1848. }
  1849. Frustum.GetPlanes = function (transform) {
  1850. var frustumPlanes = [];
  1851. for (var index = 0; index < 6; index++) {
  1852. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1853. }
  1854. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1855. return frustumPlanes;
  1856. };
  1857. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1858. // Near
  1859. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1860. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1861. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1862. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1863. frustumPlanes[0].normalize();
  1864. // Far
  1865. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1866. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1867. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1868. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1869. frustumPlanes[1].normalize();
  1870. // Left
  1871. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1872. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1873. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1874. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1875. frustumPlanes[2].normalize();
  1876. // Right
  1877. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1878. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1879. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1880. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1881. frustumPlanes[3].normalize();
  1882. // Top
  1883. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1884. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1885. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1886. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1887. frustumPlanes[4].normalize();
  1888. // Bottom
  1889. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1890. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1891. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1892. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1893. frustumPlanes[5].normalize();
  1894. };
  1895. return Frustum;
  1896. })();
  1897. BABYLON.Frustum = Frustum;
  1898. var Ray = (function () {
  1899. function Ray(origin, direction, length) {
  1900. if (typeof length === "undefined") { length = Number.MAX_VALUE; }
  1901. this.origin = origin;
  1902. this.direction = direction;
  1903. this.length = length;
  1904. }
  1905. // Methods
  1906. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1907. var d = 0.0;
  1908. var maxValue = Number.MAX_VALUE;
  1909. if (Math.abs(this.direction.x) < 0.0000001) {
  1910. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1911. return false;
  1912. }
  1913. } else {
  1914. var inv = 1.0 / this.direction.x;
  1915. var min = (minimum.x - this.origin.x) * inv;
  1916. var max = (maximum.x - this.origin.x) * inv;
  1917. if (max === -Infinity) {
  1918. max = Infinity;
  1919. }
  1920. if (min > max) {
  1921. var temp = min;
  1922. min = max;
  1923. max = temp;
  1924. }
  1925. d = Math.max(min, d);
  1926. maxValue = Math.min(max, maxValue);
  1927. if (d > maxValue) {
  1928. return false;
  1929. }
  1930. }
  1931. if (Math.abs(this.direction.y) < 0.0000001) {
  1932. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1933. return false;
  1934. }
  1935. } else {
  1936. inv = 1.0 / this.direction.y;
  1937. min = (minimum.y - this.origin.y) * inv;
  1938. max = (maximum.y - this.origin.y) * inv;
  1939. if (max === -Infinity) {
  1940. max = Infinity;
  1941. }
  1942. if (min > max) {
  1943. temp = min;
  1944. min = max;
  1945. max = temp;
  1946. }
  1947. d = Math.max(min, d);
  1948. maxValue = Math.min(max, maxValue);
  1949. if (d > maxValue) {
  1950. return false;
  1951. }
  1952. }
  1953. if (Math.abs(this.direction.z) < 0.0000001) {
  1954. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1955. return false;
  1956. }
  1957. } else {
  1958. inv = 1.0 / this.direction.z;
  1959. min = (minimum.z - this.origin.z) * inv;
  1960. max = (maximum.z - this.origin.z) * inv;
  1961. if (max === -Infinity) {
  1962. max = Infinity;
  1963. }
  1964. if (min > max) {
  1965. temp = min;
  1966. min = max;
  1967. max = temp;
  1968. }
  1969. d = Math.max(min, d);
  1970. maxValue = Math.min(max, maxValue);
  1971. if (d > maxValue) {
  1972. return false;
  1973. }
  1974. }
  1975. return true;
  1976. };
  1977. Ray.prototype.intersectsBox = function (box) {
  1978. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1979. };
  1980. Ray.prototype.intersectsSphere = function (sphere) {
  1981. var x = sphere.center.x - this.origin.x;
  1982. var y = sphere.center.y - this.origin.y;
  1983. var z = sphere.center.z - this.origin.z;
  1984. var pyth = (x * x) + (y * y) + (z * z);
  1985. var rr = sphere.radius * sphere.radius;
  1986. if (pyth <= rr) {
  1987. return true;
  1988. }
  1989. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1990. if (dot < 0.0) {
  1991. return false;
  1992. }
  1993. var temp = pyth - (dot * dot);
  1994. return temp <= rr;
  1995. };
  1996. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  1997. if (!this._edge1) {
  1998. this._edge1 = Vector3.Zero();
  1999. this._edge2 = Vector3.Zero();
  2000. this._pvec = Vector3.Zero();
  2001. this._tvec = Vector3.Zero();
  2002. this._qvec = Vector3.Zero();
  2003. }
  2004. vertex1.subtractToRef(vertex0, this._edge1);
  2005. vertex2.subtractToRef(vertex0, this._edge2);
  2006. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2007. var det = Vector3.Dot(this._edge1, this._pvec);
  2008. if (det === 0) {
  2009. return null;
  2010. }
  2011. var invdet = 1 / det;
  2012. this.origin.subtractToRef(vertex0, this._tvec);
  2013. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2014. if (bu < 0 || bu > 1.0) {
  2015. return null;
  2016. }
  2017. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2018. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2019. if (bv < 0 || bu + bv > 1.0) {
  2020. return null;
  2021. }
  2022. //check if the distance is longer than the predefined length.
  2023. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2024. if (distance > this.length) {
  2025. return null;
  2026. }
  2027. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2028. };
  2029. // Statics
  2030. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2031. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2032. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2033. var direction = end.subtract(start);
  2034. direction.normalize();
  2035. return new Ray(start, direction);
  2036. };
  2037. /**
  2038. * 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
  2039. * transformed to the given world matrix.
  2040. * @param origin The origin point
  2041. * @param end The end point
  2042. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2043. */
  2044. Ray.CreateNewFromTo = function (origin, end, world) {
  2045. if (typeof world === "undefined") { world = Matrix.Identity(); }
  2046. var direction = end.subtract(origin);
  2047. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2048. direction.normalize();
  2049. return Ray.Transform(new Ray(origin, direction, length), world);
  2050. };
  2051. Ray.Transform = function (ray, matrix) {
  2052. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2053. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2054. return new Ray(newOrigin, newDirection, ray.length);
  2055. };
  2056. return Ray;
  2057. })();
  2058. BABYLON.Ray = Ray;
  2059. (function (Space) {
  2060. Space[Space["LOCAL"] = 0] = "LOCAL";
  2061. Space[Space["WORLD"] = 1] = "WORLD";
  2062. })(BABYLON.Space || (BABYLON.Space = {}));
  2063. var Space = BABYLON.Space;
  2064. var Axis = (function () {
  2065. function Axis() {
  2066. }
  2067. Axis.X = new Vector3(1, 0, 0);
  2068. Axis.Y = new Vector3(0, 1, 0);
  2069. Axis.Z = new Vector3(0, 0, 1);
  2070. return Axis;
  2071. })();
  2072. BABYLON.Axis = Axis;
  2073. ;
  2074. var BezierCurve = (function () {
  2075. function BezierCurve() {
  2076. }
  2077. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2078. // Extract X (which is equal to time here)
  2079. var f0 = 1 - 3 * x2 + 3 * x1;
  2080. var f1 = 3 * x2 - 6 * x1;
  2081. var f2 = 3 * x1;
  2082. var refinedT = t;
  2083. for (var i = 0; i < 5; i++) {
  2084. var refinedT2 = refinedT * refinedT;
  2085. var refinedT3 = refinedT2 * refinedT;
  2086. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2087. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2088. refinedT -= (x - t) * slope;
  2089. refinedT = Math.min(1, Math.max(0, refinedT));
  2090. }
  2091. // Resolve cubic bezier for the given x
  2092. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2093. };
  2094. return BezierCurve;
  2095. })();
  2096. BABYLON.BezierCurve = BezierCurve;
  2097. (function (Orientation) {
  2098. Orientation[Orientation["CW"] = 0] = "CW";
  2099. Orientation[Orientation["CCW"] = 1] = "CCW";
  2100. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2101. var Orientation = BABYLON.Orientation;
  2102. var Angle = (function () {
  2103. function Angle(radians) {
  2104. var _this = this;
  2105. this.degrees = function () {
  2106. return _this._radians * 180 / Math.PI;
  2107. };
  2108. this.radians = function () {
  2109. return _this._radians;
  2110. };
  2111. this._radians = radians;
  2112. if (this._radians < 0)
  2113. this._radians += (2 * Math.PI);
  2114. }
  2115. Angle.BetweenTwoPoints = function (a, b) {
  2116. var delta = b.subtract(a);
  2117. var theta = Math.atan2(delta.y, delta.x);
  2118. return new Angle(theta);
  2119. };
  2120. Angle.FromRadians = function (radians) {
  2121. return new Angle(radians);
  2122. };
  2123. Angle.FromDegrees = function (degrees) {
  2124. return new Angle(degrees * Math.PI / 180);
  2125. };
  2126. return Angle;
  2127. })();
  2128. BABYLON.Angle = Angle;
  2129. var Arc2 = (function () {
  2130. function Arc2(startPoint, midPoint, endPoint) {
  2131. this.startPoint = startPoint;
  2132. this.midPoint = midPoint;
  2133. this.endPoint = endPoint;
  2134. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2135. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2136. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2137. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2138. 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);
  2139. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2140. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2141. var a1 = this.startAngle.degrees();
  2142. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2143. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2144. // angles correction
  2145. if (a2 - a1 > +180.0)
  2146. a2 -= 360.0;
  2147. if (a2 - a1 < -180.0)
  2148. a2 += 360.0;
  2149. if (a3 - a2 > +180.0)
  2150. a3 -= 360.0;
  2151. if (a3 - a2 < -180.0)
  2152. a3 += 360.0;
  2153. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2154. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2155. }
  2156. return Arc2;
  2157. })();
  2158. BABYLON.Arc2 = Arc2;
  2159. var PathCursor = (function () {
  2160. function PathCursor(path) {
  2161. this.path = path;
  2162. this._onchange = new Array();
  2163. this.value = 0;
  2164. this.animations = new Array();
  2165. }
  2166. PathCursor.prototype.getPoint = function () {
  2167. var point = this.path.getPointAtLengthPosition(this.value);
  2168. return new Vector3(point.x, 0, point.y);
  2169. };
  2170. PathCursor.prototype.moveAhead = function (step) {
  2171. if (typeof step === "undefined") { step = 0.002; }
  2172. this.move(step);
  2173. };
  2174. PathCursor.prototype.moveBack = function (step) {
  2175. if (typeof step === "undefined") { step = 0.002; }
  2176. this.move(-step);
  2177. };
  2178. PathCursor.prototype.move = function (step) {
  2179. if (Math.abs(step) > 1) {
  2180. throw "step size should be less than 1.";
  2181. }
  2182. this.value += step;
  2183. this.ensureLimits();
  2184. this.raiseOnChange();
  2185. };
  2186. PathCursor.prototype.ensureLimits = function () {
  2187. while (this.value > 1) {
  2188. this.value -= 1;
  2189. }
  2190. while (this.value < 0) {
  2191. this.value += 1;
  2192. }
  2193. };
  2194. // used by animation engine
  2195. PathCursor.prototype.markAsDirty = function (propertyName) {
  2196. this.ensureLimits();
  2197. this.raiseOnChange();
  2198. };
  2199. PathCursor.prototype.raiseOnChange = function () {
  2200. var _this = this;
  2201. this._onchange.forEach(function (f) {
  2202. return f(_this);
  2203. });
  2204. };
  2205. PathCursor.prototype.onchange = function (f) {
  2206. this._onchange.push(f);
  2207. };
  2208. return PathCursor;
  2209. })();
  2210. BABYLON.PathCursor = PathCursor;
  2211. var Path2 = (function () {
  2212. function Path2(x, y) {
  2213. this._points = [];
  2214. this._length = 0;
  2215. this.closed = false;
  2216. this._points.push(new Vector2(x, y));
  2217. }
  2218. Path2.prototype.addLineTo = function (x, y) {
  2219. if (closed) {
  2220. BABYLON.Tools.Error("cannot add lines to closed paths");
  2221. return this;
  2222. }
  2223. var newPoint = new Vector2(x, y);
  2224. var previousPoint = this._points[this._points.length - 1];
  2225. this._points.push(newPoint);
  2226. this._length += newPoint.subtract(previousPoint).length();
  2227. return this;
  2228. };
  2229. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2230. if (typeof numberOfSegments === "undefined") { numberOfSegments = 36; }
  2231. if (closed) {
  2232. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2233. return this;
  2234. }
  2235. var startPoint = this._points[this._points.length - 1];
  2236. var midPoint = new Vector2(midX, midY);
  2237. var endPoint = new Vector2(endX, endY);
  2238. var arc = new Arc2(startPoint, midPoint, endPoint);
  2239. var increment = arc.angle.radians() / numberOfSegments;
  2240. if (arc.orientation === 0 /* CW */)
  2241. increment *= -1;
  2242. var currentAngle = arc.startAngle.radians() + increment;
  2243. for (var i = 0; i < numberOfSegments; i++) {
  2244. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2245. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2246. this.addLineTo(x, y);
  2247. currentAngle += increment;
  2248. }
  2249. return this;
  2250. };
  2251. Path2.prototype.close = function () {
  2252. this.closed = true;
  2253. return this;
  2254. };
  2255. Path2.prototype.length = function () {
  2256. var result = this._length;
  2257. if (!this.closed) {
  2258. var lastPoint = this._points[this._points.length - 1];
  2259. var firstPoint = this._points[0];
  2260. result += (firstPoint.subtract(lastPoint).length());
  2261. }
  2262. return result;
  2263. };
  2264. Path2.prototype.getPoints = function () {
  2265. return this._points;
  2266. };
  2267. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2268. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2269. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2270. return;
  2271. }
  2272. var lengthPosition = normalizedLengthPosition * this.length();
  2273. var previousOffset = 0;
  2274. for (var i = 0; i < this._points.length; i++) {
  2275. var j = (i + 1) % this._points.length;
  2276. var a = this._points[i];
  2277. var b = this._points[j];
  2278. var bToA = b.subtract(a);
  2279. var nextOffset = (bToA.length() + previousOffset);
  2280. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2281. var dir = bToA.normalize();
  2282. var localOffset = lengthPosition - previousOffset;
  2283. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2284. }
  2285. previousOffset = nextOffset;
  2286. }
  2287. BABYLON.Tools.Error("internal error");
  2288. };
  2289. Path2.StartingAt = function (x, y) {
  2290. return new Path2(x, y);
  2291. };
  2292. return Path2;
  2293. })();
  2294. BABYLON.Path2 = Path2;
  2295. })(BABYLON || (BABYLON = {}));
  2296. //# sourceMappingURL=babylon.math.js.map
  2297. var BABYLON;
  2298. (function (BABYLON) {
  2299. // Screenshots
  2300. var screenshotCanvas;
  2301. var cloneValue = function (source, destinationObject) {
  2302. if (!source)
  2303. return null;
  2304. if (source instanceof BABYLON.Mesh) {
  2305. return null;
  2306. }
  2307. if (source instanceof BABYLON.SubMesh) {
  2308. return source.clone(destinationObject);
  2309. } else if (source.clone) {
  2310. return source.clone();
  2311. }
  2312. return null;
  2313. };
  2314. var Tools = (function () {
  2315. function Tools() {
  2316. }
  2317. Tools.GetFilename = function (path) {
  2318. var index = path.lastIndexOf("/");
  2319. if (index < 0)
  2320. return path;
  2321. return path.substring(index + 1);
  2322. };
  2323. Tools.GetDOMTextContent = function (element) {
  2324. var result = "";
  2325. var child = element.firstChild;
  2326. while (child) {
  2327. if (child.nodeType == 3) {
  2328. result += child.textContent;
  2329. }
  2330. child = child.nextSibling;
  2331. }
  2332. return result;
  2333. };
  2334. Tools.ToDegrees = function (angle) {
  2335. return angle * 180 / Math.PI;
  2336. };
  2337. Tools.ToRadians = function (angle) {
  2338. return angle * Math.PI / 180;
  2339. };
  2340. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2341. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2342. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2343. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2344. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2345. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2346. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2347. }
  2348. return {
  2349. minimum: minimum,
  2350. maximum: maximum
  2351. };
  2352. };
  2353. Tools.ExtractMinAndMax = function (positions, start, count) {
  2354. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2355. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2356. for (var index = start; index < start + count; index++) {
  2357. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2358. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2359. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2360. }
  2361. return {
  2362. minimum: minimum,
  2363. maximum: maximum
  2364. };
  2365. };
  2366. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2367. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2368. return undefined;
  2369. return Array.isArray(obj) ? obj : [obj];
  2370. };
  2371. // Misc.
  2372. Tools.GetPointerPrefix = function () {
  2373. var eventPrefix = "pointer";
  2374. // Check if hand.js is referenced or if the browser natively supports pointer events
  2375. if (!navigator.pointerEnabled) {
  2376. eventPrefix = "mouse";
  2377. }
  2378. return eventPrefix;
  2379. };
  2380. Tools.QueueNewFrame = function (func) {
  2381. if (window.requestAnimationFrame)
  2382. window.requestAnimationFrame(func);
  2383. else if (window.msRequestAnimationFrame)
  2384. window.msRequestAnimationFrame(func);
  2385. else if (window.webkitRequestAnimationFrame)
  2386. window.webkitRequestAnimationFrame(func);
  2387. else if (window.mozRequestAnimationFrame)
  2388. window.mozRequestAnimationFrame(func);
  2389. else if (window.oRequestAnimationFrame)
  2390. window.oRequestAnimationFrame(func);
  2391. else {
  2392. window.setTimeout(func, 16);
  2393. }
  2394. };
  2395. Tools.RequestFullscreen = function (element) {
  2396. if (element.requestFullscreen)
  2397. element.requestFullscreen();
  2398. else if (element.msRequestFullscreen)
  2399. element.msRequestFullscreen();
  2400. else if (element.webkitRequestFullscreen)
  2401. element.webkitRequestFullscreen();
  2402. else if (element.mozRequestFullScreen)
  2403. element.mozRequestFullScreen();
  2404. };
  2405. Tools.ExitFullscreen = function () {
  2406. if (document.exitFullscreen) {
  2407. document.exitFullscreen();
  2408. } else if (document.mozCancelFullScreen) {
  2409. document.mozCancelFullScreen();
  2410. } else if (document.webkitCancelFullScreen) {
  2411. document.webkitCancelFullScreen();
  2412. } else if (document.msCancelFullScreen) {
  2413. document.msCancelFullScreen();
  2414. }
  2415. };
  2416. // External files
  2417. Tools.CleanUrl = function (url) {
  2418. url = url.replace(/#/mg, "%23");
  2419. return url;
  2420. };
  2421. Tools.LoadImage = function (url, onload, onerror, database) {
  2422. url = Tools.CleanUrl(url);
  2423. var img = new Image();
  2424. if (url.substr(0, 5) != "data:")
  2425. img.crossOrigin = 'anonymous';
  2426. img.onload = function () {
  2427. onload(img);
  2428. };
  2429. img.onerror = function (err) {
  2430. onerror(img, err);
  2431. };
  2432. var noIndexedDB = function () {
  2433. img.src = url;
  2434. };
  2435. var loadFromIndexedDB = function () {
  2436. database.loadImageFromDB(url, img);
  2437. };
  2438. //ANY database to do!
  2439. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2440. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2441. } else {
  2442. if (url.indexOf("file:") === -1) {
  2443. noIndexedDB();
  2444. } else {
  2445. try {
  2446. var textureName = url.substring(5);
  2447. var blobURL;
  2448. try {
  2449. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2450. } catch (ex) {
  2451. // Chrome doesn't support oneTimeOnly parameter
  2452. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2453. }
  2454. img.src = blobURL;
  2455. } catch (e) {
  2456. Tools.Log("Error while trying to load texture: " + textureName);
  2457. img.src = null;
  2458. }
  2459. }
  2460. }
  2461. return img;
  2462. };
  2463. //ANY
  2464. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2465. url = Tools.CleanUrl(url);
  2466. var noIndexedDB = function () {
  2467. var request = new XMLHttpRequest();
  2468. var loadUrl = Tools.BaseUrl + url;
  2469. request.open('GET', loadUrl, true);
  2470. if (useArrayBuffer) {
  2471. request.responseType = "arraybuffer";
  2472. }
  2473. request.onprogress = progressCallBack;
  2474. request.onreadystatechange = function () {
  2475. if (request.readyState == 4) {
  2476. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2477. callback(!useArrayBuffer ? request.responseText : request.response);
  2478. } else {
  2479. if (onError) {
  2480. onError();
  2481. } else {
  2482. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2483. }
  2484. }
  2485. }
  2486. };
  2487. request.send(null);
  2488. };
  2489. var loadFromIndexedDB = function () {
  2490. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2491. };
  2492. if (url.indexOf("file:") !== -1) {
  2493. var fileName = url.substring(5);
  2494. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2495. } else {
  2496. // Caching all files
  2497. if (database && database.enableSceneOffline) {
  2498. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2499. } else {
  2500. noIndexedDB();
  2501. }
  2502. }
  2503. };
  2504. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2505. var reader = new FileReader();
  2506. reader.onload = function (e) {
  2507. callback(e.target.result);
  2508. };
  2509. reader.onprogress = progressCallback;
  2510. reader.readAsDataURL(fileToLoad);
  2511. };
  2512. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2513. var reader = new FileReader();
  2514. reader.onload = function (e) {
  2515. callback(e.target.result);
  2516. };
  2517. reader.onprogress = progressCallBack;
  2518. if (!useArrayBuffer) {
  2519. // Asynchronous read
  2520. reader.readAsText(fileToLoad);
  2521. } else {
  2522. reader.readAsArrayBuffer(fileToLoad);
  2523. }
  2524. };
  2525. // Misc.
  2526. Tools.Clamp = function (value, min, max) {
  2527. if (typeof min === "undefined") { min = 0; }
  2528. if (typeof max === "undefined") { max = 1; }
  2529. return Math.min(max, Math.max(min, value));
  2530. };
  2531. // Returns -1 when value is a negative number and
  2532. // +1 when value is a positive number.
  2533. Tools.Sign = function (value) {
  2534. value = +value; // convert to a number
  2535. if (value === 0 || isNaN(value))
  2536. return value;
  2537. return value > 0 ? 1 : -1;
  2538. };
  2539. Tools.Format = function (value, decimals) {
  2540. if (typeof decimals === "undefined") { decimals = 2; }
  2541. return value.toFixed(decimals);
  2542. };
  2543. Tools.CheckExtends = function (v, min, max) {
  2544. if (v.x < min.x)
  2545. min.x = v.x;
  2546. if (v.y < min.y)
  2547. min.y = v.y;
  2548. if (v.z < min.z)
  2549. min.z = v.z;
  2550. if (v.x > max.x)
  2551. max.x = v.x;
  2552. if (v.y > max.y)
  2553. max.y = v.y;
  2554. if (v.z > max.z)
  2555. max.z = v.z;
  2556. };
  2557. Tools.WithinEpsilon = function (a, b, epsilon) {
  2558. if (typeof epsilon === "undefined") { epsilon = 1.401298E-45; }
  2559. var num = a - b;
  2560. return -epsilon <= num && num <= epsilon;
  2561. };
  2562. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2563. for (var prop in source) {
  2564. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2565. continue;
  2566. }
  2567. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2568. continue;
  2569. }
  2570. var sourceValue = source[prop];
  2571. var typeOfSourceValue = typeof sourceValue;
  2572. if (typeOfSourceValue == "function") {
  2573. continue;
  2574. }
  2575. if (typeOfSourceValue == "object") {
  2576. if (sourceValue instanceof Array) {
  2577. destination[prop] = [];
  2578. if (sourceValue.length > 0) {
  2579. if (typeof sourceValue[0] == "object") {
  2580. for (var index = 0; index < sourceValue.length; index++) {
  2581. var clonedValue = cloneValue(sourceValue[index], destination);
  2582. if (destination[prop].indexOf(clonedValue) === -1) {
  2583. destination[prop].push(clonedValue);
  2584. }
  2585. }
  2586. } else {
  2587. destination[prop] = sourceValue.slice(0);
  2588. }
  2589. }
  2590. } else {
  2591. destination[prop] = cloneValue(sourceValue, destination);
  2592. }
  2593. } else {
  2594. destination[prop] = sourceValue;
  2595. }
  2596. }
  2597. };
  2598. Tools.IsEmpty = function (obj) {
  2599. for (var i in obj) {
  2600. return false;
  2601. }
  2602. return true;
  2603. };
  2604. Tools.RegisterTopRootEvents = function (events) {
  2605. for (var index = 0; index < events.length; index++) {
  2606. var event = events[index];
  2607. window.addEventListener(event.name, event.handler, false);
  2608. try {
  2609. if (window.parent) {
  2610. window.parent.addEventListener(event.name, event.handler, false);
  2611. }
  2612. } catch (e) {
  2613. // Silently fails...
  2614. }
  2615. }
  2616. };
  2617. Tools.UnregisterTopRootEvents = function (events) {
  2618. for (var index = 0; index < events.length; index++) {
  2619. var event = events[index];
  2620. window.removeEventListener(event.name, event.handler);
  2621. try {
  2622. if (window.parent) {
  2623. window.parent.removeEventListener(event.name, event.handler);
  2624. }
  2625. } catch (e) {
  2626. // Silently fails...
  2627. }
  2628. }
  2629. };
  2630. Tools.CreateScreenshot = function (engine, camera, size) {
  2631. var width;
  2632. var height;
  2633. var scene = camera.getScene();
  2634. var previousCamera = null;
  2635. if (scene.activeCamera !== camera) {
  2636. previousCamera = scene.activeCamera;
  2637. scene.activeCamera = camera;
  2638. }
  2639. //If a precision value is specified
  2640. if (size.precision) {
  2641. width = Math.round(engine.getRenderWidth() * size.precision);
  2642. height = Math.round(width / engine.getAspectRatio(camera));
  2643. size = { width: width, height: height };
  2644. } else if (size.width && size.height) {
  2645. width = size.width;
  2646. height = size.height;
  2647. } else if (size.width && !size.height) {
  2648. width = size.width;
  2649. height = Math.round(width / engine.getAspectRatio(camera));
  2650. size = { width: width, height: height };
  2651. } else if (size.height && !size.width) {
  2652. height = size.height;
  2653. width = Math.round(height * engine.getAspectRatio(camera));
  2654. size = { width: width, height: height };
  2655. } else if (!isNaN(size)) {
  2656. height = size;
  2657. width = size;
  2658. } else {
  2659. Tools.Error("Invalid 'size' parameter !");
  2660. return;
  2661. }
  2662. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2663. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2664. texture.renderList = scene.meshes;
  2665. texture.onAfterRender = function () {
  2666. // Read the contents of the framebuffer
  2667. var numberOfChannelsByLine = width * 4;
  2668. var halfHeight = height / 2;
  2669. //Reading datas from WebGL
  2670. var data = engine.readPixels(0, 0, width, height);
  2671. for (var i = 0; i < halfHeight; i++) {
  2672. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2673. var currentCell = j + i * numberOfChannelsByLine;
  2674. var targetLine = height - i - 1;
  2675. var targetCell = j + targetLine * numberOfChannelsByLine;
  2676. var temp = data[currentCell];
  2677. data[currentCell] = data[targetCell];
  2678. data[targetCell] = temp;
  2679. }
  2680. }
  2681. // Create a 2D canvas to store the result
  2682. if (!screenshotCanvas) {
  2683. screenshotCanvas = document.createElement('canvas');
  2684. }
  2685. screenshotCanvas.width = width;
  2686. screenshotCanvas.height = height;
  2687. var context = screenshotCanvas.getContext('2d');
  2688. // Copy the pixels to a 2D canvas
  2689. var imageData = context.createImageData(width, height);
  2690. imageData.data.set(data);
  2691. context.putImageData(imageData, 0, 0);
  2692. var base64Image = screenshotCanvas.toDataURL();
  2693. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2694. if (("download" in document.createElement("a"))) {
  2695. var a = window.document.createElement("a");
  2696. a.href = base64Image;
  2697. var date = new Date();
  2698. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2699. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2700. window.document.body.appendChild(a);
  2701. a.addEventListener("click", function () {
  2702. a.parentElement.removeChild(a);
  2703. });
  2704. a.click();
  2705. //Or opening a new tab with the image if it is not possible to automatically start download.
  2706. } else {
  2707. var newWindow = window.open("");
  2708. var img = newWindow.document.createElement("img");
  2709. img.src = base64Image;
  2710. newWindow.document.body.appendChild(img);
  2711. }
  2712. };
  2713. texture.render(true);
  2714. texture.dispose();
  2715. if (previousCamera) {
  2716. scene.activeCamera = previousCamera;
  2717. }
  2718. };
  2719. // XHR response validator for local file scenario
  2720. Tools.ValidateXHRData = function (xhr, dataType) {
  2721. if (typeof dataType === "undefined") { dataType = 7; }
  2722. try {
  2723. if (dataType & 1) {
  2724. if (xhr.responseText && xhr.responseText.length > 0) {
  2725. return true;
  2726. } else if (dataType === 1) {
  2727. return false;
  2728. }
  2729. }
  2730. if (dataType & 2) {
  2731. // Check header width and height since there is no "TGA" magic number
  2732. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2733. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2734. return true;
  2735. } else if (dataType === 2) {
  2736. return false;
  2737. }
  2738. }
  2739. if (dataType & 4) {
  2740. // Check for the "DDS" magic number
  2741. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2742. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2743. return true;
  2744. } else {
  2745. return false;
  2746. }
  2747. }
  2748. } catch (e) {
  2749. // Global protection
  2750. }
  2751. return false;
  2752. };
  2753. Object.defineProperty(Tools, "NoneLogLevel", {
  2754. get: function () {
  2755. return Tools._NoneLogLevel;
  2756. },
  2757. enumerable: true,
  2758. configurable: true
  2759. });
  2760. Object.defineProperty(Tools, "MessageLogLevel", {
  2761. get: function () {
  2762. return Tools._MessageLogLevel;
  2763. },
  2764. enumerable: true,
  2765. configurable: true
  2766. });
  2767. Object.defineProperty(Tools, "WarningLogLevel", {
  2768. get: function () {
  2769. return Tools._WarningLogLevel;
  2770. },
  2771. enumerable: true,
  2772. configurable: true
  2773. });
  2774. Object.defineProperty(Tools, "ErrorLogLevel", {
  2775. get: function () {
  2776. return Tools._ErrorLogLevel;
  2777. },
  2778. enumerable: true,
  2779. configurable: true
  2780. });
  2781. Object.defineProperty(Tools, "AllLogLevel", {
  2782. get: function () {
  2783. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2784. },
  2785. enumerable: true,
  2786. configurable: true
  2787. });
  2788. Tools._AddLogEntry = function (entry) {
  2789. Tools._LogCache = entry + Tools._LogCache;
  2790. if (Tools.OnNewCacheEntry) {
  2791. Tools.OnNewCacheEntry(entry);
  2792. }
  2793. };
  2794. Tools._FormatMessage = function (message) {
  2795. var padStr = function (i) {
  2796. return (i < 10) ? "0" + i : "" + i;
  2797. };
  2798. var date = new Date();
  2799. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2800. };
  2801. Tools._LogDisabled = function (message) {
  2802. // nothing to do
  2803. };
  2804. Tools._LogEnabled = function (message) {
  2805. var formattedMessage = Tools._FormatMessage(message);
  2806. console.log("BJS - " + formattedMessage);
  2807. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2808. Tools._AddLogEntry(entry);
  2809. };
  2810. Tools._WarnDisabled = function (message) {
  2811. // nothing to do
  2812. };
  2813. Tools._WarnEnabled = function (message) {
  2814. var formattedMessage = Tools._FormatMessage(message);
  2815. console.warn("BJS - " + formattedMessage);
  2816. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2817. Tools._AddLogEntry(entry);
  2818. };
  2819. Tools._ErrorDisabled = function (message) {
  2820. // nothing to do
  2821. };
  2822. Tools._ErrorEnabled = function (message) {
  2823. var formattedMessage = Tools._FormatMessage(message);
  2824. console.error("BJS - " + formattedMessage);
  2825. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2826. Tools._AddLogEntry(entry);
  2827. };
  2828. Object.defineProperty(Tools, "LogCache", {
  2829. get: function () {
  2830. return Tools._LogCache;
  2831. },
  2832. enumerable: true,
  2833. configurable: true
  2834. });
  2835. Object.defineProperty(Tools, "LogLevels", {
  2836. set: function (level) {
  2837. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2838. Tools.Log = Tools._LogEnabled;
  2839. } else {
  2840. Tools.Log = Tools._LogDisabled;
  2841. }
  2842. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2843. Tools.Warn = Tools._WarnEnabled;
  2844. } else {
  2845. Tools.Warn = Tools._WarnDisabled;
  2846. }
  2847. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2848. Tools.Error = Tools._ErrorEnabled;
  2849. } else {
  2850. Tools.Error = Tools._ErrorDisabled;
  2851. }
  2852. },
  2853. enumerable: true,
  2854. configurable: true
  2855. });
  2856. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2857. get: function () {
  2858. return Tools._PerformanceNoneLogLevel;
  2859. },
  2860. enumerable: true,
  2861. configurable: true
  2862. });
  2863. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2864. get: function () {
  2865. return Tools._PerformanceUserMarkLogLevel;
  2866. },
  2867. enumerable: true,
  2868. configurable: true
  2869. });
  2870. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2871. get: function () {
  2872. return Tools._PerformanceConsoleLogLevel;
  2873. },
  2874. enumerable: true,
  2875. configurable: true
  2876. });
  2877. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2878. set: function (level) {
  2879. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2880. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2881. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2882. return;
  2883. }
  2884. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2885. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2886. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2887. return;
  2888. }
  2889. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2890. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2891. },
  2892. enumerable: true,
  2893. configurable: true
  2894. });
  2895. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2896. };
  2897. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2898. };
  2899. Tools._StartUserMark = function (counterName, condition) {
  2900. if (typeof condition === "undefined") { condition = true; }
  2901. if (!condition || !Tools._performance.mark) {
  2902. return;
  2903. }
  2904. Tools._performance.mark(counterName + "-Begin");
  2905. };
  2906. Tools._EndUserMark = function (counterName, condition) {
  2907. if (typeof condition === "undefined") { condition = true; }
  2908. if (!condition || !Tools._performance.mark) {
  2909. return;
  2910. }
  2911. Tools._performance.mark(counterName + "-End");
  2912. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2913. };
  2914. Tools._StartPerformanceConsole = function (counterName, condition) {
  2915. if (typeof condition === "undefined") { condition = true; }
  2916. if (!condition) {
  2917. return;
  2918. }
  2919. Tools._StartUserMark(counterName, condition);
  2920. if (console.time) {
  2921. console.time(counterName);
  2922. }
  2923. };
  2924. Tools._EndPerformanceConsole = function (counterName, condition) {
  2925. if (typeof condition === "undefined") { condition = true; }
  2926. if (!condition) {
  2927. return;
  2928. }
  2929. Tools._EndUserMark(counterName, condition);
  2930. if (console.time) {
  2931. console.timeEnd(counterName);
  2932. }
  2933. };
  2934. Object.defineProperty(Tools, "Now", {
  2935. get: function () {
  2936. if (window.performance && window.performance.now) {
  2937. return window.performance.now();
  2938. }
  2939. return new Date().getTime();
  2940. },
  2941. enumerable: true,
  2942. configurable: true
  2943. });
  2944. // Deprecated
  2945. Tools.GetFps = function () {
  2946. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2947. return 0;
  2948. };
  2949. Tools.BaseUrl = "";
  2950. Tools.GetExponantOfTwo = function (value, max) {
  2951. var count = 1;
  2952. do {
  2953. count *= 2;
  2954. } while(count < value);
  2955. if (count > max)
  2956. count = max;
  2957. return count;
  2958. };
  2959. Tools._NoneLogLevel = 0;
  2960. Tools._MessageLogLevel = 1;
  2961. Tools._WarningLogLevel = 2;
  2962. Tools._ErrorLogLevel = 4;
  2963. Tools._LogCache = "";
  2964. Tools.Log = Tools._LogEnabled;
  2965. Tools.Warn = Tools._WarnEnabled;
  2966. Tools.Error = Tools._ErrorEnabled;
  2967. Tools._PerformanceNoneLogLevel = 0;
  2968. Tools._PerformanceUserMarkLogLevel = 1;
  2969. Tools._PerformanceConsoleLogLevel = 2;
  2970. Tools._performance = window.performance;
  2971. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2972. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2973. return Tools;
  2974. })();
  2975. BABYLON.Tools = Tools;
  2976. /**
  2977. * An implementation of a loop for asynchronous functions.
  2978. */
  2979. var AsyncLoop = (function () {
  2980. /**
  2981. * Constroctor.
  2982. * @param iterations the number of iterations.
  2983. * @param _fn the function to run each iteration
  2984. * @param _successCallback the callback that will be called upon succesful execution
  2985. * @param offset starting offset.
  2986. */
  2987. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  2988. if (typeof offset === "undefined") { offset = 0; }
  2989. this.iterations = iterations;
  2990. this._fn = _fn;
  2991. this._successCallback = _successCallback;
  2992. this.index = offset - 1;
  2993. this._done = false;
  2994. }
  2995. /**
  2996. * Execute the next iteration. Must be called after the last iteration was finished.
  2997. */
  2998. AsyncLoop.prototype.executeNext = function () {
  2999. if (!this._done) {
  3000. if (this.index < this.iterations) {
  3001. ++this.index;
  3002. this._fn(this);
  3003. } else {
  3004. this.breakLoop();
  3005. }
  3006. }
  3007. };
  3008. /**
  3009. * Break the loop and run the success callback.
  3010. */
  3011. AsyncLoop.prototype.breakLoop = function () {
  3012. this._done = true;
  3013. this._successCallback();
  3014. };
  3015. /**
  3016. * Helper function
  3017. */
  3018. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3019. if (typeof offset === "undefined") { offset = 0; }
  3020. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3021. loop.executeNext();
  3022. return loop;
  3023. };
  3024. /**
  3025. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3026. * @param iterations total number of iterations
  3027. * @param syncedIterations number of synchronous iterations in each async iteration.
  3028. * @param fn the function to call each iteration.
  3029. * @param callback a success call back that will be called when iterating stops.
  3030. * @param breakFunction a break condition (optional)
  3031. * @param timeout timeout settings for the setTimeout function. default - 0.
  3032. * @constructor
  3033. */
  3034. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3035. if (typeof timeout === "undefined") { timeout = 0; }
  3036. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3037. if (breakFunction && breakFunction())
  3038. loop.breakLoop();
  3039. else {
  3040. setTimeout(function () {
  3041. for (var i = 0; i < syncedIterations; ++i) {
  3042. var iteration = (loop.index * syncedIterations) + i;
  3043. if (iteration >= iterations)
  3044. break;
  3045. fn(iteration);
  3046. if (breakFunction && breakFunction()) {
  3047. loop.breakLoop();
  3048. break;
  3049. }
  3050. }
  3051. loop.executeNext();
  3052. }, timeout);
  3053. }
  3054. }, callback);
  3055. };
  3056. return AsyncLoop;
  3057. })();
  3058. BABYLON.AsyncLoop = AsyncLoop;
  3059. })(BABYLON || (BABYLON = {}));
  3060. //# sourceMappingURL=babylon.tools.js.map
  3061. var BABYLON;
  3062. (function (BABYLON) {
  3063. var _DepthCullingState = (function () {
  3064. function _DepthCullingState() {
  3065. this._isDepthTestDirty = false;
  3066. this._isDepthMaskDirty = false;
  3067. this._isDepthFuncDirty = false;
  3068. this._isCullFaceDirty = false;
  3069. this._isCullDirty = false;
  3070. }
  3071. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3072. get: function () {
  3073. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3074. },
  3075. enumerable: true,
  3076. configurable: true
  3077. });
  3078. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3079. get: function () {
  3080. return this._cullFace;
  3081. },
  3082. set: function (value) {
  3083. if (this._cullFace === value) {
  3084. return;
  3085. }
  3086. this._cullFace = value;
  3087. this._isCullFaceDirty = true;
  3088. },
  3089. enumerable: true,
  3090. configurable: true
  3091. });
  3092. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3093. get: function () {
  3094. return this._cull;
  3095. },
  3096. set: function (value) {
  3097. if (this._cull === value) {
  3098. return;
  3099. }
  3100. this._cull = value;
  3101. this._isCullDirty = true;
  3102. },
  3103. enumerable: true,
  3104. configurable: true
  3105. });
  3106. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3107. get: function () {
  3108. return this._depthFunc;
  3109. },
  3110. set: function (value) {
  3111. if (this._depthFunc === value) {
  3112. return;
  3113. }
  3114. this._depthFunc = value;
  3115. this._isDepthFuncDirty = true;
  3116. },
  3117. enumerable: true,
  3118. configurable: true
  3119. });
  3120. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3121. get: function () {
  3122. return this._depthMask;
  3123. },
  3124. set: function (value) {
  3125. if (this._depthMask === value) {
  3126. return;
  3127. }
  3128. this._depthMask = value;
  3129. this._isDepthMaskDirty = true;
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3135. get: function () {
  3136. return this._depthTest;
  3137. },
  3138. set: function (value) {
  3139. if (this._depthTest === value) {
  3140. return;
  3141. }
  3142. this._depthTest = value;
  3143. this._isDepthTestDirty = true;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. _DepthCullingState.prototype.reset = function () {
  3149. this._depthMask = true;
  3150. this._depthTest = true;
  3151. this._depthFunc = null;
  3152. this._cull = null;
  3153. this._cullFace = null;
  3154. this._isDepthTestDirty = true;
  3155. this._isDepthMaskDirty = true;
  3156. this._isDepthFuncDirty = false;
  3157. this._isCullFaceDirty = false;
  3158. this._isCullDirty = false;
  3159. };
  3160. _DepthCullingState.prototype.apply = function (gl) {
  3161. if (!this.isDirty) {
  3162. return;
  3163. }
  3164. // Cull
  3165. if (this._isCullDirty) {
  3166. if (this.cull) {
  3167. gl.enable(gl.CULL_FACE);
  3168. } else {
  3169. gl.disable(gl.CULL_FACE);
  3170. }
  3171. this._isCullDirty = false;
  3172. }
  3173. // Cull face
  3174. if (this._isCullFaceDirty) {
  3175. gl.cullFace(this.cullFace);
  3176. this._isCullFaceDirty = false;
  3177. }
  3178. // Depth mask
  3179. if (this._isDepthMaskDirty) {
  3180. gl.depthMask(this.depthMask);
  3181. this._isDepthMaskDirty = false;
  3182. }
  3183. // Depth test
  3184. if (this._isDepthTestDirty) {
  3185. if (this.depthTest) {
  3186. gl.enable(gl.DEPTH_TEST);
  3187. } else {
  3188. gl.disable(gl.DEPTH_TEST);
  3189. }
  3190. this._isDepthTestDirty = false;
  3191. }
  3192. // Depth func
  3193. if (this._isDepthFuncDirty) {
  3194. gl.depthFunc(this.depthFunc);
  3195. this._isDepthFuncDirty = false;
  3196. }
  3197. };
  3198. return _DepthCullingState;
  3199. })();
  3200. BABYLON._DepthCullingState = _DepthCullingState;
  3201. var _AlphaState = (function () {
  3202. function _AlphaState() {
  3203. this._isAlphaBlendDirty = false;
  3204. this._isBlendFunctionParametersDirty = false;
  3205. this._alphaBlend = false;
  3206. this._blendFunctionParameters = new Array(4);
  3207. }
  3208. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3209. get: function () {
  3210. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3211. },
  3212. enumerable: true,
  3213. configurable: true
  3214. });
  3215. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3216. get: function () {
  3217. return this._alphaBlend;
  3218. },
  3219. set: function (value) {
  3220. if (this._alphaBlend === value) {
  3221. return;
  3222. }
  3223. this._alphaBlend = value;
  3224. this._isAlphaBlendDirty = true;
  3225. },
  3226. enumerable: true,
  3227. configurable: true
  3228. });
  3229. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3230. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3231. return;
  3232. }
  3233. this._blendFunctionParameters[0] = value0;
  3234. this._blendFunctionParameters[1] = value1;
  3235. this._blendFunctionParameters[2] = value2;
  3236. this._blendFunctionParameters[3] = value3;
  3237. this._isBlendFunctionParametersDirty = true;
  3238. };
  3239. _AlphaState.prototype.reset = function () {
  3240. this._alphaBlend = false;
  3241. this._blendFunctionParameters[0] = null;
  3242. this._blendFunctionParameters[1] = null;
  3243. this._blendFunctionParameters[2] = null;
  3244. this._blendFunctionParameters[3] = null;
  3245. this._isAlphaBlendDirty = true;
  3246. this._isBlendFunctionParametersDirty = false;
  3247. };
  3248. _AlphaState.prototype.apply = function (gl) {
  3249. if (!this.isDirty) {
  3250. return;
  3251. }
  3252. // Alpha blend
  3253. if (this._isAlphaBlendDirty) {
  3254. if (this._alphaBlend) {
  3255. gl.enable(gl.BLEND);
  3256. } else {
  3257. gl.disable(gl.BLEND);
  3258. }
  3259. this._isAlphaBlendDirty = false;
  3260. }
  3261. // Alpha function
  3262. if (this._isBlendFunctionParametersDirty) {
  3263. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3264. this._isBlendFunctionParametersDirty = false;
  3265. }
  3266. };
  3267. return _AlphaState;
  3268. })();
  3269. BABYLON._AlphaState = _AlphaState;
  3270. var compileShader = function (gl, source, type, defines) {
  3271. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3272. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3273. gl.compileShader(shader);
  3274. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3275. throw new Error(gl.getShaderInfoLog(shader));
  3276. }
  3277. return shader;
  3278. };
  3279. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3280. var magFilter = gl.NEAREST;
  3281. var minFilter = gl.NEAREST;
  3282. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3283. magFilter = gl.LINEAR;
  3284. if (generateMipMaps) {
  3285. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3286. } else {
  3287. minFilter = gl.LINEAR;
  3288. }
  3289. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3290. magFilter = gl.LINEAR;
  3291. if (generateMipMaps) {
  3292. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3293. } else {
  3294. minFilter = gl.LINEAR;
  3295. }
  3296. } else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3297. magFilter = gl.NEAREST;
  3298. if (generateMipMaps) {
  3299. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3300. } else {
  3301. minFilter = gl.NEAREST;
  3302. }
  3303. }
  3304. return {
  3305. min: minFilter,
  3306. mag: magFilter
  3307. };
  3308. };
  3309. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3310. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3311. var engine = scene.getEngine();
  3312. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3313. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3314. gl.bindTexture(gl.TEXTURE_2D, texture);
  3315. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3316. processFunction(potWidth, potHeight);
  3317. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3318. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3319. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3320. if (!noMipmap && !isCompressed) {
  3321. gl.generateMipmap(gl.TEXTURE_2D);
  3322. }
  3323. gl.bindTexture(gl.TEXTURE_2D, null);
  3324. engine._activeTexturesCache = [];
  3325. texture._baseWidth = width;
  3326. texture._baseHeight = height;
  3327. texture._width = potWidth;
  3328. texture._height = potHeight;
  3329. texture.isReady = true;
  3330. texture.samplingMode = samplingMode;
  3331. scene._removePendingData(texture);
  3332. };
  3333. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3334. var onload = function () {
  3335. loadedImages[index] = img;
  3336. loadedImages._internalCount++;
  3337. scene._removePendingData(img);
  3338. if (loadedImages._internalCount === 6) {
  3339. onfinish(loadedImages);
  3340. }
  3341. };
  3342. var onerror = function () {
  3343. scene._removePendingData(img);
  3344. };
  3345. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3346. scene._addPendingData(img);
  3347. };
  3348. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3349. var loadedImages = [];
  3350. loadedImages._internalCount = 0;
  3351. for (var index = 0; index < 6; index++) {
  3352. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3353. }
  3354. };
  3355. var EngineCapabilities = (function () {
  3356. function EngineCapabilities() {
  3357. }
  3358. return EngineCapabilities;
  3359. })();
  3360. BABYLON.EngineCapabilities = EngineCapabilities;
  3361. var Engine = (function () {
  3362. function Engine(canvas, antialias, options) {
  3363. var _this = this;
  3364. // Public members
  3365. this.isFullscreen = false;
  3366. this.isPointerLock = false;
  3367. this.cullBackFaces = true;
  3368. this.renderEvenInBackground = true;
  3369. this.scenes = new Array();
  3370. this._windowIsBackground = false;
  3371. this._loadingDivBackgroundColor = "black";
  3372. this._drawCalls = 0;
  3373. this._renderingQueueLaunched = false;
  3374. this._activeRenderLoops = [];
  3375. // FPS
  3376. this.fpsRange = 60;
  3377. this.previousFramesDuration = [];
  3378. this.fps = 60;
  3379. this.deltaTime = 0;
  3380. // States
  3381. this._depthCullingState = new _DepthCullingState();
  3382. this._alphaState = new _AlphaState();
  3383. this._alphaMode = Engine.ALPHA_DISABLE;
  3384. // Cache
  3385. this._loadedTexturesCache = new Array();
  3386. this._activeTexturesCache = new Array();
  3387. this._compiledEffects = {};
  3388. this._uintIndicesCurrentlySet = false;
  3389. this._renderingCanvas = canvas;
  3390. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3391. options = options || {};
  3392. options.antialias = antialias;
  3393. try {
  3394. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3395. } catch (e) {
  3396. throw new Error("WebGL not supported");
  3397. }
  3398. if (!this._gl) {
  3399. throw new Error("WebGL not supported");
  3400. }
  3401. this._onBlur = function () {
  3402. _this._windowIsBackground = true;
  3403. };
  3404. this._onFocus = function () {
  3405. _this._windowIsBackground = false;
  3406. };
  3407. window.addEventListener("blur", this._onBlur);
  3408. window.addEventListener("focus", this._onFocus);
  3409. // Textures
  3410. this._workingCanvas = document.createElement("canvas");
  3411. this._workingContext = this._workingCanvas.getContext("2d");
  3412. // Viewport
  3413. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3414. this.resize();
  3415. // Caps
  3416. this._caps = new EngineCapabilities();
  3417. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3418. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3419. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3420. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3421. // Infos
  3422. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3423. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3424. if (rendererInfo != null) {
  3425. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3426. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3427. }
  3428. if (!this._glVendor) {
  3429. this._glVendor = "Unknown vendor";
  3430. }
  3431. if (!this._glRenderer) {
  3432. this._glRenderer = "Unknown renderer";
  3433. }
  3434. // Extensions
  3435. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3436. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3437. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3438. 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');
  3439. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3440. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3441. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3442. // Depth buffer
  3443. this.setDepthBuffer(true);
  3444. this.setDepthFunctionToLessOrEqual();
  3445. this.setDepthWrite(true);
  3446. // Fullscreen
  3447. this._onFullscreenChange = function () {
  3448. if (document.fullscreen !== undefined) {
  3449. _this.isFullscreen = document.fullscreen;
  3450. } else if (document.mozFullScreen !== undefined) {
  3451. _this.isFullscreen = document.mozFullScreen;
  3452. } else if (document.webkitIsFullScreen !== undefined) {
  3453. _this.isFullscreen = document.webkitIsFullScreen;
  3454. } else if (document.msIsFullScreen !== undefined) {
  3455. _this.isFullscreen = document.msIsFullScreen;
  3456. }
  3457. // Pointer lock
  3458. if (_this.isFullscreen && _this._pointerLockRequested) {
  3459. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3460. if (canvas.requestPointerLock) {
  3461. canvas.requestPointerLock();
  3462. }
  3463. }
  3464. };
  3465. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3466. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3467. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3468. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3469. // Pointer lock
  3470. this._onPointerLockChange = function () {
  3471. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3472. };
  3473. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3474. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3475. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3476. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3477. this._audioEngine = new BABYLON.AudioEngine();
  3478. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3479. }
  3480. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3481. get: function () {
  3482. return Engine._ALPHA_DISABLE;
  3483. },
  3484. enumerable: true,
  3485. configurable: true
  3486. });
  3487. Object.defineProperty(Engine, "ALPHA_ADD", {
  3488. get: function () {
  3489. return Engine._ALPHA_ADD;
  3490. },
  3491. enumerable: true,
  3492. configurable: true
  3493. });
  3494. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3495. get: function () {
  3496. return Engine._ALPHA_COMBINE;
  3497. },
  3498. enumerable: true,
  3499. configurable: true
  3500. });
  3501. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3502. get: function () {
  3503. return Engine._DELAYLOADSTATE_NONE;
  3504. },
  3505. enumerable: true,
  3506. configurable: true
  3507. });
  3508. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3509. get: function () {
  3510. return Engine._DELAYLOADSTATE_LOADED;
  3511. },
  3512. enumerable: true,
  3513. configurable: true
  3514. });
  3515. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3516. get: function () {
  3517. return Engine._DELAYLOADSTATE_LOADING;
  3518. },
  3519. enumerable: true,
  3520. configurable: true
  3521. });
  3522. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3523. get: function () {
  3524. return Engine._DELAYLOADSTATE_NOTLOADED;
  3525. },
  3526. enumerable: true,
  3527. configurable: true
  3528. });
  3529. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3530. get: function () {
  3531. return Engine._TEXTUREFORMAT_ALPHA;
  3532. },
  3533. enumerable: true,
  3534. configurable: true
  3535. });
  3536. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3537. get: function () {
  3538. return Engine._TEXTUREFORMAT_LUMINANCE;
  3539. },
  3540. enumerable: true,
  3541. configurable: true
  3542. });
  3543. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3544. get: function () {
  3545. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3546. },
  3547. enumerable: true,
  3548. configurable: true
  3549. });
  3550. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3551. get: function () {
  3552. return Engine._TEXTUREFORMAT_RGB;
  3553. },
  3554. enumerable: true,
  3555. configurable: true
  3556. });
  3557. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3558. get: function () {
  3559. return Engine._TEXTUREFORMAT_RGBA;
  3560. },
  3561. enumerable: true,
  3562. configurable: true
  3563. });
  3564. Object.defineProperty(Engine, "Version", {
  3565. get: function () {
  3566. return "2.0.0";
  3567. },
  3568. enumerable: true,
  3569. configurable: true
  3570. });
  3571. Engine.prototype.getGlInfo = function () {
  3572. return {
  3573. vendor: this._glVendor,
  3574. renderer: this._glRenderer,
  3575. version: this._glVersion
  3576. };
  3577. };
  3578. Engine.prototype.getAudioEngine = function () {
  3579. return this._audioEngine;
  3580. };
  3581. Engine.prototype.getAspectRatio = function (camera) {
  3582. var viewport = camera.viewport;
  3583. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3584. };
  3585. Engine.prototype.getRenderWidth = function () {
  3586. if (this._currentRenderTarget) {
  3587. return this._currentRenderTarget._width;
  3588. }
  3589. return this._renderingCanvas.width;
  3590. };
  3591. Engine.prototype.getRenderHeight = function () {
  3592. if (this._currentRenderTarget) {
  3593. return this._currentRenderTarget._height;
  3594. }
  3595. return this._renderingCanvas.height;
  3596. };
  3597. Engine.prototype.getRenderingCanvas = function () {
  3598. return this._renderingCanvas;
  3599. };
  3600. Engine.prototype.getRenderingCanvasClientRect = function () {
  3601. return this._renderingCanvas.getBoundingClientRect();
  3602. };
  3603. Engine.prototype.setHardwareScalingLevel = function (level) {
  3604. this._hardwareScalingLevel = level;
  3605. this.resize();
  3606. };
  3607. Engine.prototype.getHardwareScalingLevel = function () {
  3608. return this._hardwareScalingLevel;
  3609. };
  3610. Engine.prototype.getLoadedTexturesCache = function () {
  3611. return this._loadedTexturesCache;
  3612. };
  3613. Engine.prototype.getCaps = function () {
  3614. return this._caps;
  3615. };
  3616. Object.defineProperty(Engine.prototype, "drawCalls", {
  3617. get: function () {
  3618. return this._drawCalls;
  3619. },
  3620. enumerable: true,
  3621. configurable: true
  3622. });
  3623. // Methods
  3624. Engine.prototype.resetDrawCalls = function () {
  3625. this._drawCalls = 0;
  3626. };
  3627. Engine.prototype.setDepthFunctionToGreater = function () {
  3628. this._depthCullingState.depthFunc = this._gl.GREATER;
  3629. };
  3630. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3631. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3632. };
  3633. Engine.prototype.setDepthFunctionToLess = function () {
  3634. this._depthCullingState.depthFunc = this._gl.LESS;
  3635. };
  3636. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3637. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3638. };
  3639. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3640. if (!renderFunction) {
  3641. this._activeRenderLoops = [];
  3642. return;
  3643. }
  3644. var index = this._activeRenderLoops.indexOf(renderFunction);
  3645. if (index >= 0) {
  3646. this._activeRenderLoops.splice(index, 1);
  3647. }
  3648. };
  3649. Engine.prototype._renderLoop = function () {
  3650. var _this = this;
  3651. var shouldRender = true;
  3652. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3653. shouldRender = false;
  3654. }
  3655. if (shouldRender) {
  3656. // Start new frame
  3657. this.beginFrame();
  3658. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3659. var renderFunction = this._activeRenderLoops[index];
  3660. renderFunction();
  3661. }
  3662. // Present
  3663. this.endFrame();
  3664. }
  3665. if (this._activeRenderLoops.length > 0) {
  3666. // Register new frame
  3667. BABYLON.Tools.QueueNewFrame(function () {
  3668. _this._renderLoop();
  3669. });
  3670. } else {
  3671. this._renderingQueueLaunched = false;
  3672. }
  3673. };
  3674. Engine.prototype.runRenderLoop = function (renderFunction) {
  3675. var _this = this;
  3676. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3677. return;
  3678. }
  3679. this._activeRenderLoops.push(renderFunction);
  3680. if (!this._renderingQueueLaunched) {
  3681. this._renderingQueueLaunched = true;
  3682. BABYLON.Tools.QueueNewFrame(function () {
  3683. _this._renderLoop();
  3684. });
  3685. }
  3686. };
  3687. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3688. if (this.isFullscreen) {
  3689. BABYLON.Tools.ExitFullscreen();
  3690. } else {
  3691. this._pointerLockRequested = requestPointerLock;
  3692. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3693. }
  3694. };
  3695. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3696. this.applyStates();
  3697. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3698. if (this._depthCullingState.depthMask) {
  3699. this._gl.clearDepth(1.0);
  3700. }
  3701. var mode = 0;
  3702. if (backBuffer)
  3703. mode |= this._gl.COLOR_BUFFER_BIT;
  3704. if (depthStencil && this._depthCullingState.depthMask)
  3705. mode |= this._gl.DEPTH_BUFFER_BIT;
  3706. this._gl.clear(mode);
  3707. };
  3708. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3709. var width = requiredWidth || this._renderingCanvas.width;
  3710. var height = requiredHeight || this._renderingCanvas.height;
  3711. var x = viewport.x || 0;
  3712. var y = viewport.y || 0;
  3713. this._cachedViewport = viewport;
  3714. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3715. };
  3716. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3717. this._cachedViewport = null;
  3718. this._gl.viewport(x, y, width, height);
  3719. };
  3720. Engine.prototype.beginFrame = function () {
  3721. this._measureFps();
  3722. };
  3723. Engine.prototype.endFrame = function () {
  3724. this.flushFramebuffer();
  3725. };
  3726. Engine.prototype.resize = function () {
  3727. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3728. };
  3729. Engine.prototype.setSize = function (width, height) {
  3730. this._renderingCanvas.width = width;
  3731. this._renderingCanvas.height = height;
  3732. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3733. };
  3734. Engine.prototype.bindFramebuffer = function (texture) {
  3735. this._currentRenderTarget = texture;
  3736. var gl = this._gl;
  3737. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3738. this._gl.viewport(0, 0, texture._width, texture._height);
  3739. this.wipeCaches();
  3740. };
  3741. Engine.prototype.unBindFramebuffer = function (texture) {
  3742. this._currentRenderTarget = null;
  3743. if (texture.generateMipMaps) {
  3744. var gl = this._gl;
  3745. gl.bindTexture(gl.TEXTURE_2D, texture);
  3746. gl.generateMipmap(gl.TEXTURE_2D);
  3747. gl.bindTexture(gl.TEXTURE_2D, null);
  3748. }
  3749. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3750. };
  3751. Engine.prototype.flushFramebuffer = function () {
  3752. // this._gl.flush();
  3753. };
  3754. Engine.prototype.restoreDefaultFramebuffer = function () {
  3755. this._currentRenderTarget = null;
  3756. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3757. this.setViewport(this._cachedViewport);
  3758. this.wipeCaches();
  3759. };
  3760. // VBOs
  3761. Engine.prototype._resetVertexBufferBinding = function () {
  3762. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3763. this._cachedVertexBuffers = null;
  3764. };
  3765. Engine.prototype.createVertexBuffer = function (vertices) {
  3766. var vbo = this._gl.createBuffer();
  3767. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3768. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3769. this._resetVertexBufferBinding();
  3770. vbo.references = 1;
  3771. return vbo;
  3772. };
  3773. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3774. var vbo = this._gl.createBuffer();
  3775. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3776. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3777. this._resetVertexBufferBinding();
  3778. vbo.references = 1;
  3779. return vbo;
  3780. };
  3781. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3782. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3783. if (offset === undefined) {
  3784. offset = 0;
  3785. }
  3786. if (vertices instanceof Float32Array) {
  3787. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3788. } else {
  3789. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3790. }
  3791. this._resetVertexBufferBinding();
  3792. };
  3793. Engine.prototype._resetIndexBufferBinding = function () {
  3794. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3795. this._cachedIndexBuffer = null;
  3796. };
  3797. Engine.prototype.createIndexBuffer = function (indices) {
  3798. var vbo = this._gl.createBuffer();
  3799. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3800. // Check for 32 bits indices
  3801. var arrayBuffer;
  3802. var need32Bits = false;
  3803. if (this._caps.uintIndices) {
  3804. for (var index = 0; index < indices.length; index++) {
  3805. if (indices[index] > 65535) {
  3806. need32Bits = true;
  3807. break;
  3808. }
  3809. }
  3810. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3811. } else {
  3812. arrayBuffer = new Uint16Array(indices);
  3813. }
  3814. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3815. this._resetIndexBufferBinding();
  3816. vbo.references = 1;
  3817. vbo.is32Bits = need32Bits;
  3818. return vbo;
  3819. };
  3820. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3821. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3822. this._cachedVertexBuffers = vertexBuffer;
  3823. this._cachedEffectForVertexBuffers = effect;
  3824. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3825. var offset = 0;
  3826. for (var index = 0; index < vertexDeclaration.length; index++) {
  3827. var order = effect.getAttributeLocation(index);
  3828. if (order >= 0) {
  3829. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3830. }
  3831. offset += vertexDeclaration[index] * 4;
  3832. }
  3833. }
  3834. if (this._cachedIndexBuffer !== indexBuffer) {
  3835. this._cachedIndexBuffer = indexBuffer;
  3836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3837. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3838. }
  3839. };
  3840. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3841. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3842. this._cachedVertexBuffers = vertexBuffers;
  3843. this._cachedEffectForVertexBuffers = effect;
  3844. var attributes = effect.getAttributesNames();
  3845. for (var index = 0; index < attributes.length; index++) {
  3846. var order = effect.getAttributeLocation(index);
  3847. if (order >= 0) {
  3848. var vertexBuffer = vertexBuffers[attributes[index]];
  3849. if (!vertexBuffer) {
  3850. continue;
  3851. }
  3852. var stride = vertexBuffer.getStrideSize();
  3853. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3854. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3855. }
  3856. }
  3857. }
  3858. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3859. this._cachedIndexBuffer = indexBuffer;
  3860. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3861. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3862. }
  3863. };
  3864. Engine.prototype._releaseBuffer = function (buffer) {
  3865. buffer.references--;
  3866. if (buffer.references === 0) {
  3867. this._gl.deleteBuffer(buffer);
  3868. return true;
  3869. }
  3870. return false;
  3871. };
  3872. Engine.prototype.createInstancesBuffer = function (capacity) {
  3873. var buffer = this._gl.createBuffer();
  3874. buffer.capacity = capacity;
  3875. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3876. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3877. return buffer;
  3878. };
  3879. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3880. this._gl.deleteBuffer(buffer);
  3881. };
  3882. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3883. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3884. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3885. for (var index = 0; index < 4; index++) {
  3886. var offsetLocation = offsetLocations[index];
  3887. this._gl.enableVertexAttribArray(offsetLocation);
  3888. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3889. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3890. }
  3891. };
  3892. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3893. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3894. for (var index = 0; index < 4; index++) {
  3895. var offsetLocation = offsetLocations[index];
  3896. this._gl.disableVertexAttribArray(offsetLocation);
  3897. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3898. }
  3899. };
  3900. Engine.prototype.applyStates = function () {
  3901. this._depthCullingState.apply(this._gl);
  3902. this._alphaState.apply(this._gl);
  3903. };
  3904. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3905. // Apply states
  3906. this.applyStates();
  3907. this._drawCalls++;
  3908. // Render
  3909. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3910. if (instancesCount) {
  3911. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3912. return;
  3913. }
  3914. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3915. };
  3916. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3917. // Apply states
  3918. this.applyStates();
  3919. this._drawCalls++;
  3920. if (instancesCount) {
  3921. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3922. return;
  3923. }
  3924. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3925. };
  3926. // Shaders
  3927. Engine.prototype._releaseEffect = function (effect) {
  3928. if (this._compiledEffects[effect._key]) {
  3929. delete this._compiledEffects[effect._key];
  3930. if (effect.getProgram()) {
  3931. this._gl.deleteProgram(effect.getProgram());
  3932. }
  3933. }
  3934. };
  3935. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3936. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3937. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3938. var name = vertex + "+" + fragment + "@" + defines;
  3939. if (this._compiledEffects[name]) {
  3940. return this._compiledEffects[name];
  3941. }
  3942. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3943. effect._key = name;
  3944. this._compiledEffects[name] = effect;
  3945. return effect;
  3946. };
  3947. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3948. if (typeof uniformsNames === "undefined") { uniformsNames = []; }
  3949. if (typeof samplers === "undefined") { samplers = []; }
  3950. if (typeof defines === "undefined") { defines = ""; }
  3951. return this.createEffect({
  3952. vertex: "particles",
  3953. fragmentElement: fragmentName
  3954. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3955. };
  3956. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  3957. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  3958. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  3959. var shaderProgram = this._gl.createProgram();
  3960. this._gl.attachShader(shaderProgram, vertexShader);
  3961. this._gl.attachShader(shaderProgram, fragmentShader);
  3962. this._gl.linkProgram(shaderProgram);
  3963. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  3964. if (!linked) {
  3965. var error = this._gl.getProgramInfoLog(shaderProgram);
  3966. if (error) {
  3967. throw new Error(error);
  3968. }
  3969. }
  3970. this._gl.deleteShader(vertexShader);
  3971. this._gl.deleteShader(fragmentShader);
  3972. return shaderProgram;
  3973. };
  3974. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  3975. var results = [];
  3976. for (var index = 0; index < uniformsNames.length; index++) {
  3977. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  3978. }
  3979. return results;
  3980. };
  3981. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  3982. var results = [];
  3983. for (var index = 0; index < attributesNames.length; index++) {
  3984. try {
  3985. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  3986. } catch (e) {
  3987. results.push(-1);
  3988. }
  3989. }
  3990. return results;
  3991. };
  3992. Engine.prototype.enableEffect = function (effect) {
  3993. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  3994. if (effect && effect.onBind) {
  3995. effect.onBind(effect);
  3996. }
  3997. return;
  3998. }
  3999. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4000. // Use program
  4001. this._gl.useProgram(effect.getProgram());
  4002. for (var i in this._vertexAttribArrays) {
  4003. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4004. continue;
  4005. }
  4006. this._vertexAttribArrays[i] = false;
  4007. this._gl.disableVertexAttribArray(i);
  4008. }
  4009. var attributesCount = effect.getAttributesCount();
  4010. for (var index = 0; index < attributesCount; index++) {
  4011. // Attributes
  4012. var order = effect.getAttributeLocation(index);
  4013. if (order >= 0) {
  4014. this._vertexAttribArrays[order] = true;
  4015. this._gl.enableVertexAttribArray(order);
  4016. }
  4017. }
  4018. this._currentEffect = effect;
  4019. if (effect.onBind) {
  4020. effect.onBind(effect);
  4021. }
  4022. };
  4023. Engine.prototype.setArray = function (uniform, array) {
  4024. if (!uniform)
  4025. return;
  4026. this._gl.uniform1fv(uniform, array);
  4027. };
  4028. Engine.prototype.setMatrices = function (uniform, matrices) {
  4029. if (!uniform)
  4030. return;
  4031. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4032. };
  4033. Engine.prototype.setMatrix = function (uniform, matrix) {
  4034. if (!uniform)
  4035. return;
  4036. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4037. };
  4038. Engine.prototype.setFloat = function (uniform, value) {
  4039. if (!uniform)
  4040. return;
  4041. this._gl.uniform1f(uniform, value);
  4042. };
  4043. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4044. if (!uniform)
  4045. return;
  4046. this._gl.uniform2f(uniform, x, y);
  4047. };
  4048. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4049. if (!uniform)
  4050. return;
  4051. this._gl.uniform3f(uniform, x, y, z);
  4052. };
  4053. Engine.prototype.setBool = function (uniform, bool) {
  4054. if (!uniform)
  4055. return;
  4056. this._gl.uniform1i(uniform, bool);
  4057. };
  4058. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4059. if (!uniform)
  4060. return;
  4061. this._gl.uniform4f(uniform, x, y, z, w);
  4062. };
  4063. Engine.prototype.setColor3 = function (uniform, color3) {
  4064. if (!uniform)
  4065. return;
  4066. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4067. };
  4068. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4069. if (!uniform)
  4070. return;
  4071. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4072. };
  4073. // States
  4074. Engine.prototype.setState = function (culling, force) {
  4075. // Culling
  4076. if (this._depthCullingState.cull !== culling || force) {
  4077. if (culling) {
  4078. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4079. this._depthCullingState.cull = true;
  4080. } else {
  4081. this._depthCullingState.cull = false;
  4082. }
  4083. }
  4084. };
  4085. Engine.prototype.setDepthBuffer = function (enable) {
  4086. this._depthCullingState.depthTest = enable;
  4087. };
  4088. Engine.prototype.getDepthWrite = function () {
  4089. return this._depthCullingState.depthMask;
  4090. };
  4091. Engine.prototype.setDepthWrite = function (enable) {
  4092. this._depthCullingState.depthMask = enable;
  4093. };
  4094. Engine.prototype.setColorWrite = function (enable) {
  4095. this._gl.colorMask(enable, enable, enable, enable);
  4096. };
  4097. Engine.prototype.setAlphaMode = function (mode) {
  4098. switch (mode) {
  4099. case Engine.ALPHA_DISABLE:
  4100. this.setDepthWrite(true);
  4101. this._alphaState.alphaBlend = false;
  4102. break;
  4103. case Engine.ALPHA_COMBINE:
  4104. this.setDepthWrite(false);
  4105. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4106. this._alphaState.alphaBlend = true;
  4107. break;
  4108. case Engine.ALPHA_ADD:
  4109. this.setDepthWrite(false);
  4110. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4111. this._alphaState.alphaBlend = true;
  4112. break;
  4113. }
  4114. this._alphaMode = mode;
  4115. };
  4116. Engine.prototype.getAlphaMode = function () {
  4117. return this._alphaMode;
  4118. };
  4119. Engine.prototype.setAlphaTesting = function (enable) {
  4120. this._alphaTest = enable;
  4121. };
  4122. Engine.prototype.getAlphaTesting = function () {
  4123. return this._alphaTest;
  4124. };
  4125. // Textures
  4126. Engine.prototype.wipeCaches = function () {
  4127. this._activeTexturesCache = [];
  4128. this._currentEffect = null;
  4129. this._depthCullingState.reset();
  4130. this._alphaState.reset();
  4131. this._cachedVertexBuffers = null;
  4132. this._cachedIndexBuffer = null;
  4133. this._cachedEffectForVertexBuffers = null;
  4134. };
  4135. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4136. var gl = this._gl;
  4137. gl.bindTexture(gl.TEXTURE_2D, texture);
  4138. var magFilter = gl.NEAREST;
  4139. var minFilter = gl.NEAREST;
  4140. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4141. magFilter = gl.LINEAR;
  4142. minFilter = gl.LINEAR;
  4143. } else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4144. magFilter = gl.LINEAR;
  4145. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4146. }
  4147. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4148. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4149. gl.bindTexture(gl.TEXTURE_2D, null);
  4150. texture.samplingMode = samplingMode;
  4151. };
  4152. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4153. var _this = this;
  4154. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4155. if (typeof onLoad === "undefined") { onLoad = null; }
  4156. if (typeof onError === "undefined") { onError = null; }
  4157. if (typeof buffer === "undefined") { buffer = null; }
  4158. var texture = this._gl.createTexture();
  4159. var extension;
  4160. var fromData = false;
  4161. if (url.substr(0, 5) === "data:") {
  4162. fromData = true;
  4163. }
  4164. if (!fromData)
  4165. extension = url.substr(url.length - 4, 4).toLowerCase();
  4166. else {
  4167. var oldUrl = url;
  4168. fromData = oldUrl.split(':');
  4169. url = oldUrl;
  4170. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4171. }
  4172. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4173. var isTGA = (extension === ".tga");
  4174. scene._addPendingData(texture);
  4175. texture.url = url;
  4176. texture.noMipmap = noMipmap;
  4177. texture.references = 1;
  4178. this._loadedTexturesCache.push(texture);
  4179. var onerror = function () {
  4180. scene._removePendingData(texture);
  4181. if (onError) {
  4182. onError();
  4183. }
  4184. };
  4185. if (isTGA) {
  4186. var callback = function (arrayBuffer) {
  4187. var data = new Uint8Array(arrayBuffer);
  4188. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4189. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4190. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4191. if (onLoad) {
  4192. onLoad();
  4193. }
  4194. }, samplingMode);
  4195. };
  4196. if (!(fromData instanceof Array))
  4197. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4198. callback(arrayBuffer);
  4199. }, onerror, scene.database, true);
  4200. else
  4201. callback(buffer);
  4202. } else if (isDDS) {
  4203. callback = function (data) {
  4204. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4205. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4206. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4207. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4208. if (onLoad) {
  4209. onLoad();
  4210. }
  4211. }, samplingMode);
  4212. };
  4213. if (!(fromData instanceof Array))
  4214. BABYLON.Tools.LoadFile(url, function (data) {
  4215. callback(data);
  4216. }, onerror, scene.database, true);
  4217. else
  4218. callback(buffer);
  4219. } else {
  4220. var onload = function (img) {
  4221. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4222. var isPot = (img.width === potWidth && img.height === potHeight);
  4223. if (!isPot) {
  4224. _this._workingCanvas.width = potWidth;
  4225. _this._workingCanvas.height = potHeight;
  4226. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4227. _this._workingContext.imageSmoothingEnabled = false;
  4228. _this._workingContext.mozImageSmoothingEnabled = false;
  4229. _this._workingContext.oImageSmoothingEnabled = false;
  4230. _this._workingContext.webkitImageSmoothingEnabled = false;
  4231. _this._workingContext.msImageSmoothingEnabled = false;
  4232. }
  4233. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4234. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4235. _this._workingContext.imageSmoothingEnabled = true;
  4236. _this._workingContext.mozImageSmoothingEnabled = true;
  4237. _this._workingContext.oImageSmoothingEnabled = true;
  4238. _this._workingContext.webkitImageSmoothingEnabled = true;
  4239. _this._workingContext.msImageSmoothingEnabled = true;
  4240. }
  4241. }
  4242. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4243. if (onLoad) {
  4244. onLoad();
  4245. }
  4246. }, samplingMode);
  4247. };
  4248. if (!(fromData instanceof Array))
  4249. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4250. else
  4251. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4252. }
  4253. return texture;
  4254. };
  4255. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4256. var texture = this._gl.createTexture();
  4257. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4258. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4259. // Format
  4260. var internalFormat = this._gl.RGBA;
  4261. switch (format) {
  4262. case Engine.TEXTUREFORMAT_ALPHA:
  4263. internalFormat = this._gl.ALPHA;
  4264. break;
  4265. case Engine.TEXTUREFORMAT_LUMINANCE:
  4266. internalFormat = this._gl.LUMINANCE;
  4267. break;
  4268. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4269. internalFormat = this._gl.LUMINANCE_ALPHA;
  4270. break;
  4271. case Engine.TEXTUREFORMAT_RGB:
  4272. internalFormat = this._gl.RGB;
  4273. break;
  4274. case Engine.TEXTUREFORMAT_RGBA:
  4275. internalFormat = this._gl.RGBA;
  4276. break;
  4277. }
  4278. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4279. if (generateMipMaps) {
  4280. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4281. }
  4282. // Filters
  4283. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4284. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4285. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4286. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4287. this._activeTexturesCache = [];
  4288. texture._baseWidth = width;
  4289. texture._baseHeight = height;
  4290. texture._width = width;
  4291. texture._height = height;
  4292. texture.isReady = true;
  4293. texture.references = 1;
  4294. texture.samplingMode = samplingMode;
  4295. this._loadedTexturesCache.push(texture);
  4296. return texture;
  4297. };
  4298. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4299. var texture = this._gl.createTexture();
  4300. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4301. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4302. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4303. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4304. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4305. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4306. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4307. this._activeTexturesCache = [];
  4308. texture._baseWidth = width;
  4309. texture._baseHeight = height;
  4310. texture._width = width;
  4311. texture._height = height;
  4312. texture.isReady = false;
  4313. texture.generateMipMaps = generateMipMaps;
  4314. texture.references = 1;
  4315. texture.samplingMode = samplingMode;
  4316. this._loadedTexturesCache.push(texture);
  4317. return texture;
  4318. };
  4319. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4320. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4321. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4322. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4323. if (texture.generateMipMaps) {
  4324. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4325. }
  4326. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4327. this._activeTexturesCache = [];
  4328. texture.isReady = true;
  4329. };
  4330. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4331. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4332. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4333. // Scale the video if it is a NPOT using the current working canvas
  4334. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4335. if (!texture._workingCanvas) {
  4336. texture._workingCanvas = document.createElement("canvas");
  4337. texture._workingContext = texture._workingCanvas.getContext("2d");
  4338. texture._workingCanvas.width = texture._width;
  4339. texture._workingCanvas.height = texture._height;
  4340. }
  4341. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4342. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4343. } else {
  4344. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4345. }
  4346. if (texture.generateMipMaps) {
  4347. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4348. }
  4349. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4350. this._activeTexturesCache = [];
  4351. texture.isReady = true;
  4352. };
  4353. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4354. // old version had a "generateMipMaps" arg instead of options.
  4355. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4356. // in the same way, generateDepthBuffer is defaulted to true
  4357. var generateMipMaps = false;
  4358. var generateDepthBuffer = true;
  4359. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4360. if (options !== undefined) {
  4361. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4362. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4363. if (options.samplingMode !== undefined) {
  4364. samplingMode = options.samplingMode;
  4365. }
  4366. }
  4367. var gl = this._gl;
  4368. var texture = gl.createTexture();
  4369. gl.bindTexture(gl.TEXTURE_2D, texture);
  4370. var width = size.width || size;
  4371. var height = size.height || size;
  4372. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4373. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4374. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4375. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4376. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4377. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4378. var depthBuffer;
  4379. // Create the depth buffer
  4380. if (generateDepthBuffer) {
  4381. depthBuffer = gl.createRenderbuffer();
  4382. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4383. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4384. }
  4385. // Create the framebuffer
  4386. var framebuffer = gl.createFramebuffer();
  4387. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4388. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4389. if (generateDepthBuffer) {
  4390. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4391. }
  4392. // Unbind
  4393. gl.bindTexture(gl.TEXTURE_2D, null);
  4394. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4395. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4396. texture._framebuffer = framebuffer;
  4397. if (generateDepthBuffer) {
  4398. texture._depthBuffer = depthBuffer;
  4399. }
  4400. texture._width = width;
  4401. texture._height = height;
  4402. texture.isReady = true;
  4403. texture.generateMipMaps = generateMipMaps;
  4404. texture.references = 1;
  4405. texture.samplingMode = samplingMode;
  4406. this._activeTexturesCache = [];
  4407. this._loadedTexturesCache.push(texture);
  4408. return texture;
  4409. };
  4410. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4411. var _this = this;
  4412. var gl = this._gl;
  4413. var texture = gl.createTexture();
  4414. texture.isCube = true;
  4415. texture.url = rootUrl;
  4416. texture.references = 1;
  4417. this._loadedTexturesCache.push(texture);
  4418. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4419. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4420. if (isDDS) {
  4421. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4422. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4423. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4424. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4425. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4426. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4427. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4428. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4429. }
  4430. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4431. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4432. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4433. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4434. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4435. _this._activeTexturesCache = [];
  4436. texture._width = info.width;
  4437. texture._height = info.height;
  4438. texture.isReady = true;
  4439. }, null, null, true);
  4440. } else {
  4441. cascadeLoad(rootUrl, scene, function (imgs) {
  4442. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4443. var height = width;
  4444. _this._workingCanvas.width = width;
  4445. _this._workingCanvas.height = height;
  4446. var faces = [
  4447. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4448. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4449. ];
  4450. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4451. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4452. for (var index = 0; index < faces.length; index++) {
  4453. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4454. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4455. }
  4456. if (!noMipmap) {
  4457. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4458. }
  4459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4461. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4462. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4463. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4464. _this._activeTexturesCache = [];
  4465. texture._width = width;
  4466. texture._height = height;
  4467. texture.isReady = true;
  4468. }, extensions);
  4469. }
  4470. return texture;
  4471. };
  4472. Engine.prototype._releaseTexture = function (texture) {
  4473. var gl = this._gl;
  4474. if (texture._framebuffer) {
  4475. gl.deleteFramebuffer(texture._framebuffer);
  4476. }
  4477. if (texture._depthBuffer) {
  4478. gl.deleteRenderbuffer(texture._depthBuffer);
  4479. }
  4480. gl.deleteTexture(texture);
  4481. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4482. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4483. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4484. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4485. this._activeTexturesCache[channel] = null;
  4486. }
  4487. var index = this._loadedTexturesCache.indexOf(texture);
  4488. if (index !== -1) {
  4489. this._loadedTexturesCache.splice(index, 1);
  4490. }
  4491. };
  4492. Engine.prototype.bindSamplers = function (effect) {
  4493. this._gl.useProgram(effect.getProgram());
  4494. var samplers = effect.getSamplers();
  4495. for (var index = 0; index < samplers.length; index++) {
  4496. var uniform = effect.getUniform(samplers[index]);
  4497. this._gl.uniform1i(uniform, index);
  4498. }
  4499. this._currentEffect = null;
  4500. };
  4501. Engine.prototype._bindTexture = function (channel, texture) {
  4502. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4503. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4504. this._activeTexturesCache[channel] = null;
  4505. };
  4506. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4507. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4508. };
  4509. Engine.prototype.setTexture = function (channel, texture) {
  4510. if (channel < 0) {
  4511. return;
  4512. }
  4513. // Not ready?
  4514. if (!texture || !texture.isReady()) {
  4515. if (this._activeTexturesCache[channel] != null) {
  4516. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4517. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4518. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4519. this._activeTexturesCache[channel] = null;
  4520. }
  4521. return;
  4522. }
  4523. // Video
  4524. if (texture instanceof BABYLON.VideoTexture) {
  4525. if (texture.update()) {
  4526. this._activeTexturesCache[channel] = null;
  4527. }
  4528. } else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4529. texture.delayLoad();
  4530. return;
  4531. }
  4532. if (this._activeTexturesCache[channel] === texture) {
  4533. return;
  4534. }
  4535. this._activeTexturesCache[channel] = texture;
  4536. var internalTexture = texture.getInternalTexture();
  4537. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4538. if (internalTexture.isCube) {
  4539. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4540. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4541. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4542. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4543. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4544. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4545. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4546. }
  4547. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4548. } else {
  4549. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4550. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4551. internalTexture._cachedWrapU = texture.wrapU;
  4552. switch (texture.wrapU) {
  4553. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4554. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4555. break;
  4556. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4557. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4558. break;
  4559. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4560. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4561. break;
  4562. }
  4563. }
  4564. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4565. internalTexture._cachedWrapV = texture.wrapV;
  4566. switch (texture.wrapV) {
  4567. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4568. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4569. break;
  4570. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4571. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4572. break;
  4573. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4574. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4575. break;
  4576. }
  4577. }
  4578. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4579. }
  4580. };
  4581. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4582. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4583. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4584. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4585. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4586. }
  4587. };
  4588. Engine.prototype.readPixels = function (x, y, width, height) {
  4589. var data = new Uint8Array(height * width * 4);
  4590. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4591. return data;
  4592. };
  4593. // Dispose
  4594. Engine.prototype.dispose = function () {
  4595. this.hideLoadingUI();
  4596. this.stopRenderLoop();
  4597. while (this.scenes.length) {
  4598. this.scenes[0].dispose();
  4599. }
  4600. for (var name in this._compiledEffects) {
  4601. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4602. }
  4603. for (var i in this._vertexAttribArrays) {
  4604. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4605. continue;
  4606. }
  4607. this._gl.disableVertexAttribArray(i);
  4608. }
  4609. // Events
  4610. window.removeEventListener("blur", this._onBlur);
  4611. window.removeEventListener("focus", this._onFocus);
  4612. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4613. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4614. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4615. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4616. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4617. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4618. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4619. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4620. };
  4621. // Loading screen
  4622. Engine.prototype.displayLoadingUI = function () {
  4623. var _this = this;
  4624. this._loadingDiv = document.createElement("div");
  4625. this._loadingDiv.style.opacity = "0";
  4626. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4627. // Loading text
  4628. this._loadingTextDiv = document.createElement("div");
  4629. this._loadingTextDiv.style.position = "absolute";
  4630. this._loadingTextDiv.style.left = "0";
  4631. this._loadingTextDiv.style.top = "50%";
  4632. this._loadingTextDiv.style.marginTop = "80px";
  4633. this._loadingTextDiv.style.width = "100%";
  4634. this._loadingTextDiv.style.height = "20px";
  4635. this._loadingTextDiv.style.fontFamily = "Arial";
  4636. this._loadingTextDiv.style.fontSize = "14px";
  4637. this._loadingTextDiv.style.color = "white";
  4638. this._loadingTextDiv.style.textAlign = "center";
  4639. this._loadingTextDiv.innerHTML = "Loading";
  4640. this._loadingDiv.appendChild(this._loadingTextDiv);
  4641. // Loading img
  4642. var imgBack = new Image();
  4643. 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==";
  4644. imgBack.style.position = "absolute";
  4645. imgBack.style.left = "50%";
  4646. imgBack.style.top = "50%";
  4647. imgBack.style.marginLeft = "-50px";
  4648. imgBack.style.marginTop = "-50px";
  4649. imgBack.style.transition = "transform 1.0s ease";
  4650. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4651. var deg = 360;
  4652. var onTransitionEnd = function () {
  4653. deg += 360;
  4654. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4655. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4656. };
  4657. imgBack.addEventListener("transitionend", onTransitionEnd);
  4658. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4659. this._loadingDiv.appendChild(imgBack);
  4660. // front image
  4661. var imgFront = new Image();
  4662. 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=";
  4663. imgFront.style.position = "absolute";
  4664. imgFront.style.left = "50%";
  4665. imgFront.style.top = "50%";
  4666. imgFront.style.marginLeft = "-50px";
  4667. imgFront.style.marginTop = "-50px";
  4668. this._loadingDiv.appendChild(imgFront);
  4669. // Resize
  4670. this._resizeLoadingUI = function () {
  4671. var canvasRect = _this.getRenderingCanvasClientRect();
  4672. _this._loadingDiv.style.position = "absolute";
  4673. _this._loadingDiv.style.left = canvasRect.left + "px";
  4674. _this._loadingDiv.style.top = canvasRect.top + "px";
  4675. _this._loadingDiv.style.width = canvasRect.width + "px";
  4676. _this._loadingDiv.style.height = canvasRect.height + "px";
  4677. };
  4678. this._resizeLoadingUI();
  4679. window.addEventListener("resize", this._resizeLoadingUI);
  4680. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4681. document.body.appendChild(this._loadingDiv);
  4682. setTimeout(function () {
  4683. _this._loadingDiv.style.opacity = "1";
  4684. imgBack.style.transform = "rotateZ(360deg)";
  4685. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4686. }, 0);
  4687. };
  4688. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4689. set: function (text) {
  4690. if (!this._loadingDiv) {
  4691. return;
  4692. }
  4693. this._loadingTextDiv.innerHTML = text;
  4694. },
  4695. enumerable: true,
  4696. configurable: true
  4697. });
  4698. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4699. get: function () {
  4700. return this._loadingDivBackgroundColor;
  4701. },
  4702. set: function (color) {
  4703. this._loadingDivBackgroundColor = color;
  4704. if (!this._loadingDiv) {
  4705. return;
  4706. }
  4707. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4708. },
  4709. enumerable: true,
  4710. configurable: true
  4711. });
  4712. Engine.prototype.hideLoadingUI = function () {
  4713. var _this = this;
  4714. if (!this._loadingDiv) {
  4715. return;
  4716. }
  4717. var onTransitionEnd = function () {
  4718. if (!_this._loadingDiv) {
  4719. return;
  4720. }
  4721. document.body.removeChild(_this._loadingDiv);
  4722. window.removeEventListener("resize", _this._resizeLoadingUI);
  4723. _this._loadingDiv = null;
  4724. };
  4725. this._loadingDiv.style.opacity = "0";
  4726. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4727. };
  4728. // FPS
  4729. Engine.prototype.getFps = function () {
  4730. return this.fps;
  4731. };
  4732. Engine.prototype.getDeltaTime = function () {
  4733. return this.deltaTime;
  4734. };
  4735. Engine.prototype._measureFps = function () {
  4736. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4737. var length = this.previousFramesDuration.length;
  4738. if (length >= 2) {
  4739. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4740. }
  4741. if (length >= this.fpsRange) {
  4742. if (length > this.fpsRange) {
  4743. this.previousFramesDuration.splice(0, 1);
  4744. length = this.previousFramesDuration.length;
  4745. }
  4746. var sum = 0;
  4747. for (var id = 0; id < length - 1; id++) {
  4748. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4749. }
  4750. this.fps = 1000.0 / (sum / (length - 1));
  4751. }
  4752. };
  4753. // Statics
  4754. Engine.isSupported = function () {
  4755. try {
  4756. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4757. if (navigator.isCocoonJS) {
  4758. return true;
  4759. }
  4760. var tempcanvas = document.createElement("canvas");
  4761. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4762. return gl != null && !!window.WebGLRenderingContext;
  4763. } catch (e) {
  4764. return false;
  4765. }
  4766. };
  4767. Engine._ALPHA_DISABLE = 0;
  4768. Engine._ALPHA_ADD = 1;
  4769. Engine._ALPHA_COMBINE = 2;
  4770. Engine._DELAYLOADSTATE_NONE = 0;
  4771. Engine._DELAYLOADSTATE_LOADED = 1;
  4772. Engine._DELAYLOADSTATE_LOADING = 2;
  4773. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4774. Engine._TEXTUREFORMAT_ALPHA = 0;
  4775. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4776. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4777. Engine._TEXTUREFORMAT_RGB = 4;
  4778. Engine._TEXTUREFORMAT_RGBA = 4;
  4779. Engine.Epsilon = 0.001;
  4780. Engine.CollisionsEpsilon = 0.001;
  4781. Engine.ShadersRepository = "Babylon/Shaders/";
  4782. return Engine;
  4783. })();
  4784. BABYLON.Engine = Engine;
  4785. })(BABYLON || (BABYLON = {}));
  4786. //# sourceMappingURL=babylon.engine.js.map
  4787. var BABYLON;
  4788. (function (BABYLON) {
  4789. var Node = (function () {
  4790. function Node(name, scene) {
  4791. this.state = "";
  4792. this.animations = new Array();
  4793. this._childrenFlag = -1;
  4794. this._isEnabled = true;
  4795. this._isReady = true;
  4796. this._currentRenderId = -1;
  4797. this.name = name;
  4798. this.id = name;
  4799. this._scene = scene;
  4800. this._initCache();
  4801. }
  4802. Node.prototype.getScene = function () {
  4803. return this._scene;
  4804. };
  4805. Node.prototype.getEngine = function () {
  4806. return this._scene.getEngine();
  4807. };
  4808. // override it in derived class
  4809. Node.prototype.getWorldMatrix = function () {
  4810. return BABYLON.Matrix.Identity();
  4811. };
  4812. // override it in derived class if you add new variables to the cache
  4813. // and call the parent class method
  4814. Node.prototype._initCache = function () {
  4815. this._cache = {};
  4816. this._cache.parent = undefined;
  4817. };
  4818. Node.prototype.updateCache = function (force) {
  4819. if (!force && this.isSynchronized())
  4820. return;
  4821. this._cache.parent = this.parent;
  4822. this._updateCache();
  4823. };
  4824. // override it in derived class if you add new variables to the cache
  4825. // and call the parent class method if !ignoreParentClass
  4826. Node.prototype._updateCache = function (ignoreParentClass) {
  4827. };
  4828. // override it in derived class if you add new variables to the cache
  4829. Node.prototype._isSynchronized = function () {
  4830. return true;
  4831. };
  4832. Node.prototype.isSynchronizedWithParent = function () {
  4833. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4834. };
  4835. Node.prototype.isSynchronized = function (updateCache) {
  4836. var check = this.hasNewParent();
  4837. check = check || !this.isSynchronizedWithParent();
  4838. check = check || !this._isSynchronized();
  4839. if (updateCache)
  4840. this.updateCache(true);
  4841. return !check;
  4842. };
  4843. Node.prototype.hasNewParent = function (update) {
  4844. if (this._cache.parent === this.parent)
  4845. return false;
  4846. if (update)
  4847. this._cache.parent = this.parent;
  4848. return true;
  4849. };
  4850. Node.prototype.isReady = function () {
  4851. return this._isReady;
  4852. };
  4853. Node.prototype.isEnabled = function () {
  4854. if (!this._isEnabled) {
  4855. return false;
  4856. }
  4857. if (this.parent) {
  4858. return this.parent.isEnabled();
  4859. }
  4860. return true;
  4861. };
  4862. Node.prototype.setEnabled = function (value) {
  4863. this._isEnabled = value;
  4864. };
  4865. Node.prototype.isDescendantOf = function (ancestor) {
  4866. if (this.parent) {
  4867. if (this.parent === ancestor) {
  4868. return true;
  4869. }
  4870. return this.parent.isDescendantOf(ancestor);
  4871. }
  4872. return false;
  4873. };
  4874. Node.prototype._getDescendants = function (list, results) {
  4875. for (var index = 0; index < list.length; index++) {
  4876. var item = list[index];
  4877. if (item.isDescendantOf(this)) {
  4878. results.push(item);
  4879. }
  4880. }
  4881. };
  4882. Node.prototype.getDescendants = function () {
  4883. var results = [];
  4884. this._getDescendants(this._scene.meshes, results);
  4885. this._getDescendants(this._scene.lights, results);
  4886. this._getDescendants(this._scene.cameras, results);
  4887. return results;
  4888. };
  4889. Node.prototype._setReady = function (state) {
  4890. if (state == this._isReady) {
  4891. return;
  4892. }
  4893. if (!state) {
  4894. this._isReady = false;
  4895. return;
  4896. }
  4897. this._isReady = true;
  4898. if (this.onReady) {
  4899. this.onReady(this);
  4900. }
  4901. };
  4902. return Node;
  4903. })();
  4904. BABYLON.Node = Node;
  4905. })(BABYLON || (BABYLON = {}));
  4906. //# sourceMappingURL=babylon.node.js.map
  4907. var BABYLON;
  4908. (function (BABYLON) {
  4909. var BoundingSphere = (function () {
  4910. function BoundingSphere(minimum, maximum) {
  4911. this.minimum = minimum;
  4912. this.maximum = maximum;
  4913. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4914. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4915. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4916. this.radius = distance * 0.5;
  4917. this.centerWorld = BABYLON.Vector3.Zero();
  4918. this._update(BABYLON.Matrix.Identity());
  4919. }
  4920. // Methods
  4921. BoundingSphere.prototype._update = function (world) {
  4922. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4923. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4924. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4925. };
  4926. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4927. for (var i = 0; i < 6; i++) {
  4928. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4929. return false;
  4930. }
  4931. return true;
  4932. };
  4933. BoundingSphere.prototype.intersectsPoint = function (point) {
  4934. var x = this.centerWorld.x - point.x;
  4935. var y = this.centerWorld.y - point.y;
  4936. var z = this.centerWorld.z - point.z;
  4937. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4938. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4939. return false;
  4940. return true;
  4941. };
  4942. // Statics
  4943. BoundingSphere.Intersects = function (sphere0, sphere1) {
  4944. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  4945. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  4946. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  4947. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4948. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  4949. return false;
  4950. return true;
  4951. };
  4952. return BoundingSphere;
  4953. })();
  4954. BABYLON.BoundingSphere = BoundingSphere;
  4955. })(BABYLON || (BABYLON = {}));
  4956. //# sourceMappingURL=babylon.boundingSphere.js.map
  4957. var BABYLON;
  4958. (function (BABYLON) {
  4959. var BoundingBox = (function () {
  4960. function BoundingBox(minimum, maximum) {
  4961. this.minimum = minimum;
  4962. this.maximum = maximum;
  4963. this.vectors = new Array();
  4964. this.vectorsWorld = new Array();
  4965. // Bounding vectors
  4966. this.vectors.push(this.minimum.clone());
  4967. this.vectors.push(this.maximum.clone());
  4968. this.vectors.push(this.minimum.clone());
  4969. this.vectors[2].x = this.maximum.x;
  4970. this.vectors.push(this.minimum.clone());
  4971. this.vectors[3].y = this.maximum.y;
  4972. this.vectors.push(this.minimum.clone());
  4973. this.vectors[4].z = this.maximum.z;
  4974. this.vectors.push(this.maximum.clone());
  4975. this.vectors[5].z = this.minimum.z;
  4976. this.vectors.push(this.maximum.clone());
  4977. this.vectors[6].x = this.minimum.x;
  4978. this.vectors.push(this.maximum.clone());
  4979. this.vectors[7].y = this.minimum.y;
  4980. // OBB
  4981. this.center = this.maximum.add(this.minimum).scale(0.5);
  4982. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  4983. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  4984. for (var index = 0; index < this.vectors.length; index++) {
  4985. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  4986. }
  4987. this.minimumWorld = BABYLON.Vector3.Zero();
  4988. this.maximumWorld = BABYLON.Vector3.Zero();
  4989. this._update(BABYLON.Matrix.Identity());
  4990. }
  4991. // Methods
  4992. BoundingBox.prototype.getWorldMatrix = function () {
  4993. return this._worldMatrix;
  4994. };
  4995. BoundingBox.prototype._update = function (world) {
  4996. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  4997. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  4998. for (var index = 0; index < this.vectors.length; index++) {
  4999. var v = this.vectorsWorld[index];
  5000. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5001. if (v.x < this.minimumWorld.x)
  5002. this.minimumWorld.x = v.x;
  5003. if (v.y < this.minimumWorld.y)
  5004. this.minimumWorld.y = v.y;
  5005. if (v.z < this.minimumWorld.z)
  5006. this.minimumWorld.z = v.z;
  5007. if (v.x > this.maximumWorld.x)
  5008. this.maximumWorld.x = v.x;
  5009. if (v.y > this.maximumWorld.y)
  5010. this.maximumWorld.y = v.y;
  5011. if (v.z > this.maximumWorld.z)
  5012. this.maximumWorld.z = v.z;
  5013. }
  5014. // OBB
  5015. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5016. this.center.scaleInPlace(0.5);
  5017. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5018. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5019. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5020. this._worldMatrix = world;
  5021. };
  5022. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5023. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5024. };
  5025. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5026. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5027. };
  5028. BoundingBox.prototype.intersectsPoint = function (point) {
  5029. var delta = BABYLON.Engine.Epsilon;
  5030. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5031. return false;
  5032. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5033. return false;
  5034. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5035. return false;
  5036. return true;
  5037. };
  5038. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5039. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5040. };
  5041. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5042. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5043. return false;
  5044. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5045. return false;
  5046. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5047. return false;
  5048. return true;
  5049. };
  5050. // Statics
  5051. BoundingBox.Intersects = function (box0, box1) {
  5052. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5053. return false;
  5054. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5055. return false;
  5056. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5057. return false;
  5058. return true;
  5059. };
  5060. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5061. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5062. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5063. return (num <= (sphereRadius * sphereRadius));
  5064. };
  5065. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5066. for (var p = 0; p < 6; p++) {
  5067. for (var i = 0; i < 8; i++) {
  5068. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5069. return false;
  5070. }
  5071. }
  5072. }
  5073. return true;
  5074. };
  5075. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5076. for (var p = 0; p < 6; p++) {
  5077. var inCount = 8;
  5078. for (var i = 0; i < 8; i++) {
  5079. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5080. --inCount;
  5081. } else {
  5082. break;
  5083. }
  5084. }
  5085. if (inCount == 0)
  5086. return false;
  5087. }
  5088. return true;
  5089. };
  5090. return BoundingBox;
  5091. })();
  5092. BABYLON.BoundingBox = BoundingBox;
  5093. })(BABYLON || (BABYLON = {}));
  5094. //# sourceMappingURL=babylon.boundingBox.js.map
  5095. var BABYLON;
  5096. (function (BABYLON) {
  5097. var computeBoxExtents = function (axis, box) {
  5098. var p = BABYLON.Vector3.Dot(box.center, axis);
  5099. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5100. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5101. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5102. var r = r0 + r1 + r2;
  5103. return {
  5104. min: p - r,
  5105. max: p + r
  5106. };
  5107. };
  5108. var extentsOverlap = function (min0, max0, min1, max1) {
  5109. return !(min0 > max1 || min1 > max0);
  5110. };
  5111. var axisOverlap = function (axis, box0, box1) {
  5112. var result0 = computeBoxExtents(axis, box0);
  5113. var result1 = computeBoxExtents(axis, box1);
  5114. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5115. };
  5116. var BoundingInfo = (function () {
  5117. function BoundingInfo(minimum, maximum) {
  5118. this.minimum = minimum;
  5119. this.maximum = maximum;
  5120. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5121. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5122. }
  5123. // Methods
  5124. BoundingInfo.prototype._update = function (world) {
  5125. this.boundingBox._update(world);
  5126. this.boundingSphere._update(world);
  5127. };
  5128. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5129. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5130. return false;
  5131. return this.boundingBox.isInFrustum(frustumPlanes);
  5132. };
  5133. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5134. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5135. };
  5136. BoundingInfo.prototype._checkCollision = function (collider) {
  5137. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5138. };
  5139. BoundingInfo.prototype.intersectsPoint = function (point) {
  5140. if (!this.boundingSphere.centerWorld) {
  5141. return false;
  5142. }
  5143. if (!this.boundingSphere.intersectsPoint(point)) {
  5144. return false;
  5145. }
  5146. if (!this.boundingBox.intersectsPoint(point)) {
  5147. return false;
  5148. }
  5149. return true;
  5150. };
  5151. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5152. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5153. return false;
  5154. }
  5155. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5156. return false;
  5157. }
  5158. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5159. return false;
  5160. }
  5161. if (!precise) {
  5162. return true;
  5163. }
  5164. var box0 = this.boundingBox;
  5165. var box1 = boundingInfo.boundingBox;
  5166. if (!axisOverlap(box0.directions[0], box0, box1))
  5167. return false;
  5168. if (!axisOverlap(box0.directions[1], box0, box1))
  5169. return false;
  5170. if (!axisOverlap(box0.directions[2], box0, box1))
  5171. return false;
  5172. if (!axisOverlap(box1.directions[0], box0, box1))
  5173. return false;
  5174. if (!axisOverlap(box1.directions[1], box0, box1))
  5175. return false;
  5176. if (!axisOverlap(box1.directions[2], box0, box1))
  5177. return false;
  5178. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5179. return false;
  5180. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5181. return false;
  5182. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5183. return false;
  5184. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5185. return false;
  5186. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5187. return false;
  5188. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5189. return false;
  5190. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5191. return false;
  5192. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5193. return false;
  5194. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5195. return false;
  5196. return true;
  5197. };
  5198. return BoundingInfo;
  5199. })();
  5200. BABYLON.BoundingInfo = BoundingInfo;
  5201. })(BABYLON || (BABYLON = {}));
  5202. //# sourceMappingURL=babylon.boundingInfo.js.map
  5203. var BABYLON;
  5204. (function (BABYLON) {
  5205. var Light = (function (_super) {
  5206. __extends(Light, _super);
  5207. function Light(name, scene) {
  5208. _super.call(this, name, scene);
  5209. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5210. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5211. this.intensity = 1.0;
  5212. this.range = Number.MAX_VALUE;
  5213. this.includedOnlyMeshes = new Array();
  5214. this.excludedMeshes = new Array();
  5215. this._excludedMeshesIds = new Array();
  5216. this._includedOnlyMeshesIds = new Array();
  5217. scene.lights.push(this);
  5218. }
  5219. Light.prototype.getShadowGenerator = function () {
  5220. return this._shadowGenerator;
  5221. };
  5222. Light.prototype.getAbsolutePosition = function () {
  5223. return BABYLON.Vector3.Zero();
  5224. };
  5225. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5226. };
  5227. Light.prototype._getWorldMatrix = function () {
  5228. return BABYLON.Matrix.Identity();
  5229. };
  5230. Light.prototype.canAffectMesh = function (mesh) {
  5231. if (!mesh) {
  5232. return true;
  5233. }
  5234. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5235. return false;
  5236. }
  5237. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5238. return false;
  5239. }
  5240. return true;
  5241. };
  5242. Light.prototype.getWorldMatrix = function () {
  5243. this._currentRenderId = this.getScene().getRenderId();
  5244. var worldMatrix = this._getWorldMatrix();
  5245. if (this.parent && this.parent.getWorldMatrix) {
  5246. if (!this._parentedWorldMatrix) {
  5247. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5248. }
  5249. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5250. return this._parentedWorldMatrix;
  5251. }
  5252. return worldMatrix;
  5253. };
  5254. Light.prototype.dispose = function () {
  5255. if (this._shadowGenerator) {
  5256. this._shadowGenerator.dispose();
  5257. this._shadowGenerator = null;
  5258. }
  5259. // Remove from scene
  5260. var index = this.getScene().lights.indexOf(this);
  5261. this.getScene().lights.splice(index, 1);
  5262. };
  5263. return Light;
  5264. })(BABYLON.Node);
  5265. BABYLON.Light = Light;
  5266. })(BABYLON || (BABYLON = {}));
  5267. //# sourceMappingURL=babylon.light.js.map
  5268. var BABYLON;
  5269. (function (BABYLON) {
  5270. var PointLight = (function (_super) {
  5271. __extends(PointLight, _super);
  5272. function PointLight(name, position, scene) {
  5273. _super.call(this, name, scene);
  5274. this.position = position;
  5275. }
  5276. PointLight.prototype.getAbsolutePosition = function () {
  5277. return this._transformedPosition ? this._transformedPosition : this.position;
  5278. };
  5279. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5280. if (this.parent && this.parent.getWorldMatrix) {
  5281. if (!this._transformedPosition) {
  5282. this._transformedPosition = BABYLON.Vector3.Zero();
  5283. }
  5284. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5285. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5286. return;
  5287. }
  5288. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5289. };
  5290. PointLight.prototype.getShadowGenerator = function () {
  5291. return null;
  5292. };
  5293. PointLight.prototype._getWorldMatrix = function () {
  5294. if (!this._worldMatrix) {
  5295. this._worldMatrix = BABYLON.Matrix.Identity();
  5296. }
  5297. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5298. return this._worldMatrix;
  5299. };
  5300. return PointLight;
  5301. })(BABYLON.Light);
  5302. BABYLON.PointLight = PointLight;
  5303. })(BABYLON || (BABYLON = {}));
  5304. //# sourceMappingURL=babylon.pointLight.js.map
  5305. var BABYLON;
  5306. (function (BABYLON) {
  5307. var SpotLight = (function (_super) {
  5308. __extends(SpotLight, _super);
  5309. function SpotLight(name, position, direction, angle, exponent, scene) {
  5310. _super.call(this, name, scene);
  5311. this.position = position;
  5312. this.direction = direction;
  5313. this.angle = angle;
  5314. this.exponent = exponent;
  5315. }
  5316. SpotLight.prototype.getAbsolutePosition = function () {
  5317. return this.transformedPosition ? this.transformedPosition : this.position;
  5318. };
  5319. SpotLight.prototype.setDirectionToTarget = function (target) {
  5320. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5321. return this.direction;
  5322. };
  5323. SpotLight.prototype.computeTransformedPosition = function () {
  5324. if (this.parent && this.parent.getWorldMatrix) {
  5325. if (!this.transformedPosition) {
  5326. this.transformedPosition = BABYLON.Vector3.Zero();
  5327. }
  5328. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5329. return true;
  5330. }
  5331. return false;
  5332. };
  5333. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5334. var normalizeDirection;
  5335. if (this.parent && this.parent.getWorldMatrix) {
  5336. if (!this._transformedDirection) {
  5337. this._transformedDirection = BABYLON.Vector3.Zero();
  5338. }
  5339. this.computeTransformedPosition();
  5340. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5341. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5342. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5343. } else {
  5344. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5345. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5346. }
  5347. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5348. };
  5349. SpotLight.prototype._getWorldMatrix = function () {
  5350. if (!this._worldMatrix) {
  5351. this._worldMatrix = BABYLON.Matrix.Identity();
  5352. }
  5353. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5354. return this._worldMatrix;
  5355. };
  5356. return SpotLight;
  5357. })(BABYLON.Light);
  5358. BABYLON.SpotLight = SpotLight;
  5359. })(BABYLON || (BABYLON = {}));
  5360. //# sourceMappingURL=babylon.spotLight.js.map
  5361. var BABYLON;
  5362. (function (BABYLON) {
  5363. var DirectionalLight = (function (_super) {
  5364. __extends(DirectionalLight, _super);
  5365. function DirectionalLight(name, direction, scene) {
  5366. _super.call(this, name, scene);
  5367. this.direction = direction;
  5368. this.position = direction.scale(-1);
  5369. }
  5370. DirectionalLight.prototype.getAbsolutePosition = function () {
  5371. return this.transformedPosition ? this.transformedPosition : this.position;
  5372. };
  5373. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5374. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5375. return this.direction;
  5376. };
  5377. DirectionalLight.prototype.computeTransformedPosition = function () {
  5378. if (this.parent && this.parent.getWorldMatrix) {
  5379. if (!this.transformedPosition) {
  5380. this.transformedPosition = BABYLON.Vector3.Zero();
  5381. }
  5382. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5383. return true;
  5384. }
  5385. return false;
  5386. };
  5387. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5388. if (this.parent && this.parent.getWorldMatrix) {
  5389. if (!this._transformedDirection) {
  5390. this._transformedDirection = BABYLON.Vector3.Zero();
  5391. }
  5392. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5393. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5394. return;
  5395. }
  5396. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5397. };
  5398. DirectionalLight.prototype._getWorldMatrix = function () {
  5399. if (!this._worldMatrix) {
  5400. this._worldMatrix = BABYLON.Matrix.Identity();
  5401. }
  5402. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5403. return this._worldMatrix;
  5404. };
  5405. return DirectionalLight;
  5406. })(BABYLON.Light);
  5407. BABYLON.DirectionalLight = DirectionalLight;
  5408. })(BABYLON || (BABYLON = {}));
  5409. //# sourceMappingURL=babylon.directionalLight.js.map
  5410. var BABYLON;
  5411. (function (BABYLON) {
  5412. var ShadowGenerator = (function () {
  5413. function ShadowGenerator(mapSize, light) {
  5414. var _this = this;
  5415. // Members
  5416. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5417. this._darkness = 0;
  5418. this._transparencyShadow = false;
  5419. this._viewMatrix = BABYLON.Matrix.Zero();
  5420. this._projectionMatrix = BABYLON.Matrix.Zero();
  5421. this._transformMatrix = BABYLON.Matrix.Zero();
  5422. this._worldViewProjection = BABYLON.Matrix.Zero();
  5423. this._light = light;
  5424. this._scene = light.getScene();
  5425. light._shadowGenerator = this;
  5426. // Render target
  5427. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5428. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5429. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5430. this._shadowMap.renderParticles = false;
  5431. // Custom render function
  5432. var renderSubMesh = function (subMesh) {
  5433. var mesh = subMesh.getRenderingMesh();
  5434. var scene = _this._scene;
  5435. var engine = scene.getEngine();
  5436. // Culling
  5437. engine.setState(subMesh.getMaterial().backFaceCulling);
  5438. // Managing instances
  5439. var batch = mesh._getInstancesRenderList(subMesh._id);
  5440. if (batch.mustReturn) {
  5441. return;
  5442. }
  5443. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5444. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5445. engine.enableEffect(_this._effect);
  5446. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5447. var material = subMesh.getMaterial();
  5448. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5449. // Alpha test
  5450. if (material && material.needAlphaTesting()) {
  5451. var alphaTexture = material.getAlphaTestTexture();
  5452. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5453. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5454. }
  5455. // Bones
  5456. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5457. if (useBones) {
  5458. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5459. }
  5460. if (hardwareInstancedRendering) {
  5461. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5462. } else {
  5463. if (batch.renderSelf[subMesh._id]) {
  5464. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5465. // Draw
  5466. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5467. }
  5468. if (batch.visibleInstances[subMesh._id]) {
  5469. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5470. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5471. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5472. // Draw
  5473. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5474. }
  5475. }
  5476. }
  5477. } else {
  5478. // Need to reset refresh rate of the shadowMap
  5479. _this._shadowMap.resetRefreshCounter();
  5480. }
  5481. };
  5482. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5483. var index;
  5484. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5485. renderSubMesh(opaqueSubMeshes.data[index]);
  5486. }
  5487. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5488. renderSubMesh(alphaTestSubMeshes.data[index]);
  5489. }
  5490. if (_this._transparencyShadow) {
  5491. for (index = 0; index < transparentSubMeshes.length; index++) {
  5492. renderSubMesh(transparentSubMeshes.data[index]);
  5493. }
  5494. }
  5495. };
  5496. }
  5497. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5498. // Static
  5499. get: function () {
  5500. return ShadowGenerator._FILTER_NONE;
  5501. },
  5502. enumerable: true,
  5503. configurable: true
  5504. });
  5505. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5506. get: function () {
  5507. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5508. },
  5509. enumerable: true,
  5510. configurable: true
  5511. });
  5512. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5513. get: function () {
  5514. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5515. },
  5516. enumerable: true,
  5517. configurable: true
  5518. });
  5519. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5520. get: function () {
  5521. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5522. },
  5523. set: function (value) {
  5524. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5525. },
  5526. enumerable: true,
  5527. configurable: true
  5528. });
  5529. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5530. get: function () {
  5531. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5532. },
  5533. set: function (value) {
  5534. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5535. },
  5536. enumerable: true,
  5537. configurable: true
  5538. });
  5539. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5540. var defines = [];
  5541. if (this.useVarianceShadowMap) {
  5542. defines.push("#define VSM");
  5543. }
  5544. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5545. var mesh = subMesh.getMesh();
  5546. var scene = mesh.getScene();
  5547. var material = subMesh.getMaterial();
  5548. // Alpha test
  5549. if (material && material.needAlphaTesting()) {
  5550. defines.push("#define ALPHATEST");
  5551. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5552. attribs.push(BABYLON.VertexBuffer.UVKind);
  5553. defines.push("#define UV1");
  5554. }
  5555. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5556. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5557. defines.push("#define UV2");
  5558. }
  5559. }
  5560. // Bones
  5561. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5562. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5563. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5564. defines.push("#define BONES");
  5565. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5566. }
  5567. // Instances
  5568. if (useInstances) {
  5569. defines.push("#define INSTANCES");
  5570. attribs.push("world0");
  5571. attribs.push("world1");
  5572. attribs.push("world2");
  5573. attribs.push("world3");
  5574. }
  5575. // Get correct effect
  5576. var join = defines.join("\n");
  5577. if (this._cachedDefines !== join) {
  5578. this._cachedDefines = join;
  5579. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5580. }
  5581. return this._effect.isReady();
  5582. };
  5583. ShadowGenerator.prototype.getShadowMap = function () {
  5584. return this._shadowMap;
  5585. };
  5586. ShadowGenerator.prototype.getLight = function () {
  5587. return this._light;
  5588. };
  5589. // Methods
  5590. ShadowGenerator.prototype.getTransformMatrix = function () {
  5591. var lightPosition = this._light.position;
  5592. var lightDirection = this._light.direction;
  5593. if (this._light.computeTransformedPosition()) {
  5594. lightPosition = this._light.transformedPosition;
  5595. }
  5596. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5597. this._cachedPosition = lightPosition.clone();
  5598. this._cachedDirection = lightDirection.clone();
  5599. var activeCamera = this._scene.activeCamera;
  5600. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5601. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5602. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5603. }
  5604. return this._transformMatrix;
  5605. };
  5606. ShadowGenerator.prototype.getDarkness = function () {
  5607. return this._darkness;
  5608. };
  5609. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5610. if (darkness >= 1.0)
  5611. this._darkness = 1.0;
  5612. else if (darkness <= 0.0)
  5613. this._darkness = 0.0;
  5614. else
  5615. this._darkness = darkness;
  5616. };
  5617. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5618. this._transparencyShadow = hasShadow;
  5619. };
  5620. ShadowGenerator.prototype.dispose = function () {
  5621. this._shadowMap.dispose();
  5622. };
  5623. ShadowGenerator._FILTER_NONE = 0;
  5624. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5625. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5626. return ShadowGenerator;
  5627. })();
  5628. BABYLON.ShadowGenerator = ShadowGenerator;
  5629. })(BABYLON || (BABYLON = {}));
  5630. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5631. var BABYLON;
  5632. (function (BABYLON) {
  5633. var HemisphericLight = (function (_super) {
  5634. __extends(HemisphericLight, _super);
  5635. function HemisphericLight(name, direction, scene) {
  5636. _super.call(this, name, scene);
  5637. this.direction = direction;
  5638. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5639. }
  5640. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5641. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5642. return this.direction;
  5643. };
  5644. HemisphericLight.prototype.getShadowGenerator = function () {
  5645. return null;
  5646. };
  5647. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5648. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5649. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5650. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5651. };
  5652. HemisphericLight.prototype._getWorldMatrix = function () {
  5653. if (!this._worldMatrix) {
  5654. this._worldMatrix = BABYLON.Matrix.Identity();
  5655. }
  5656. return this._worldMatrix;
  5657. };
  5658. return HemisphericLight;
  5659. })(BABYLON.Light);
  5660. BABYLON.HemisphericLight = HemisphericLight;
  5661. })(BABYLON || (BABYLON = {}));
  5662. //# sourceMappingURL=babylon.hemisphericLight.js.map
  5663. var BABYLON;
  5664. (function (BABYLON) {
  5665. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5666. if (boxMin.x > sphereCenter.x + sphereRadius)
  5667. return false;
  5668. if (sphereCenter.x - sphereRadius > boxMax.x)
  5669. return false;
  5670. if (boxMin.y > sphereCenter.y + sphereRadius)
  5671. return false;
  5672. if (sphereCenter.y - sphereRadius > boxMax.y)
  5673. return false;
  5674. if (boxMin.z > sphereCenter.z + sphereRadius)
  5675. return false;
  5676. if (sphereCenter.z - sphereRadius > boxMax.z)
  5677. return false;
  5678. return true;
  5679. };
  5680. var getLowestRoot = function (a, b, c, maxR) {
  5681. var determinant = b * b - 4.0 * a * c;
  5682. var result = { root: 0, found: false };
  5683. if (determinant < 0)
  5684. return result;
  5685. var sqrtD = Math.sqrt(determinant);
  5686. var r1 = (-b - sqrtD) / (2.0 * a);
  5687. var r2 = (-b + sqrtD) / (2.0 * a);
  5688. if (r1 > r2) {
  5689. var temp = r2;
  5690. r2 = r1;
  5691. r1 = temp;
  5692. }
  5693. if (r1 > 0 && r1 < maxR) {
  5694. result.root = r1;
  5695. result.found = true;
  5696. return result;
  5697. }
  5698. if (r2 > 0 && r2 < maxR) {
  5699. result.root = r2;
  5700. result.found = true;
  5701. return result;
  5702. }
  5703. return result;
  5704. };
  5705. var Collider = (function () {
  5706. function Collider() {
  5707. this.radius = new BABYLON.Vector3(1, 1, 1);
  5708. this.retry = 0;
  5709. this.basePointWorld = BABYLON.Vector3.Zero();
  5710. this.velocityWorld = BABYLON.Vector3.Zero();
  5711. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5712. this._collisionPoint = BABYLON.Vector3.Zero();
  5713. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5714. this._tempVector = BABYLON.Vector3.Zero();
  5715. this._tempVector2 = BABYLON.Vector3.Zero();
  5716. this._tempVector3 = BABYLON.Vector3.Zero();
  5717. this._tempVector4 = BABYLON.Vector3.Zero();
  5718. this._edge = BABYLON.Vector3.Zero();
  5719. this._baseToVertex = BABYLON.Vector3.Zero();
  5720. this._destinationPoint = BABYLON.Vector3.Zero();
  5721. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5722. this._displacementVector = BABYLON.Vector3.Zero();
  5723. }
  5724. // Methods
  5725. Collider.prototype._initialize = function (source, dir, e) {
  5726. this.velocity = dir;
  5727. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5728. this.basePoint = source;
  5729. source.multiplyToRef(this.radius, this.basePointWorld);
  5730. dir.multiplyToRef(this.radius, this.velocityWorld);
  5731. this.velocityWorldLength = this.velocityWorld.length();
  5732. this.epsilon = e;
  5733. this.collisionFound = false;
  5734. };
  5735. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5736. pa.subtractToRef(point, this._tempVector);
  5737. pb.subtractToRef(point, this._tempVector2);
  5738. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5739. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5740. if (d < 0)
  5741. return false;
  5742. pc.subtractToRef(point, this._tempVector3);
  5743. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5744. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5745. if (d < 0)
  5746. return false;
  5747. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5748. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5749. return d >= 0;
  5750. };
  5751. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5752. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5753. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5754. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5755. return false;
  5756. }
  5757. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5758. return false;
  5759. return true;
  5760. };
  5761. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5762. var t0;
  5763. var embeddedInPlane = false;
  5764. if (!subMesh._trianglePlanes) {
  5765. subMesh._trianglePlanes = [];
  5766. }
  5767. if (!subMesh._trianglePlanes[faceIndex]) {
  5768. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5769. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5770. }
  5771. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5772. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5773. return;
  5774. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5775. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5776. if (normalDotVelocity == 0) {
  5777. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5778. return;
  5779. embeddedInPlane = true;
  5780. t0 = 0;
  5781. } else {
  5782. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5783. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5784. if (t0 > t1) {
  5785. var temp = t1;
  5786. t1 = t0;
  5787. t0 = temp;
  5788. }
  5789. if (t0 > 1.0 || t1 < 0.0)
  5790. return;
  5791. if (t0 < 0)
  5792. t0 = 0;
  5793. if (t0 > 1.0)
  5794. t0 = 1.0;
  5795. }
  5796. this._collisionPoint.copyFromFloats(0, 0, 0);
  5797. var found = false;
  5798. var t = 1.0;
  5799. if (!embeddedInPlane) {
  5800. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5801. this.velocity.scaleToRef(t0, this._tempVector);
  5802. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5803. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5804. found = true;
  5805. t = t0;
  5806. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5807. }
  5808. }
  5809. if (!found) {
  5810. var velocitySquaredLength = this.velocity.lengthSquared();
  5811. var a = velocitySquaredLength;
  5812. this.basePoint.subtractToRef(p1, this._tempVector);
  5813. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5814. var c = this._tempVector.lengthSquared() - 1.0;
  5815. var lowestRoot = getLowestRoot(a, b, c, t);
  5816. if (lowestRoot.found) {
  5817. t = lowestRoot.root;
  5818. found = true;
  5819. this._collisionPoint.copyFrom(p1);
  5820. }
  5821. this.basePoint.subtractToRef(p2, this._tempVector);
  5822. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5823. c = this._tempVector.lengthSquared() - 1.0;
  5824. lowestRoot = getLowestRoot(a, b, c, t);
  5825. if (lowestRoot.found) {
  5826. t = lowestRoot.root;
  5827. found = true;
  5828. this._collisionPoint.copyFrom(p2);
  5829. }
  5830. this.basePoint.subtractToRef(p3, this._tempVector);
  5831. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5832. c = this._tempVector.lengthSquared() - 1.0;
  5833. lowestRoot = getLowestRoot(a, b, c, t);
  5834. if (lowestRoot.found) {
  5835. t = lowestRoot.root;
  5836. found = true;
  5837. this._collisionPoint.copyFrom(p3);
  5838. }
  5839. p2.subtractToRef(p1, this._edge);
  5840. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5841. var edgeSquaredLength = this._edge.lengthSquared();
  5842. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5843. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5844. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5845. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5846. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5847. lowestRoot = getLowestRoot(a, b, c, t);
  5848. if (lowestRoot.found) {
  5849. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5850. if (f >= 0.0 && f <= 1.0) {
  5851. t = lowestRoot.root;
  5852. found = true;
  5853. this._edge.scaleInPlace(f);
  5854. p1.addToRef(this._edge, this._collisionPoint);
  5855. }
  5856. }
  5857. p3.subtractToRef(p2, this._edge);
  5858. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5859. edgeSquaredLength = this._edge.lengthSquared();
  5860. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5861. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5862. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5863. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5864. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5865. lowestRoot = getLowestRoot(a, b, c, t);
  5866. if (lowestRoot.found) {
  5867. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5868. if (f >= 0.0 && f <= 1.0) {
  5869. t = lowestRoot.root;
  5870. found = true;
  5871. this._edge.scaleInPlace(f);
  5872. p2.addToRef(this._edge, this._collisionPoint);
  5873. }
  5874. }
  5875. p1.subtractToRef(p3, this._edge);
  5876. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5877. edgeSquaredLength = this._edge.lengthSquared();
  5878. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5879. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5880. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5881. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5882. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5883. lowestRoot = getLowestRoot(a, b, c, t);
  5884. if (lowestRoot.found) {
  5885. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5886. if (f >= 0.0 && f <= 1.0) {
  5887. t = lowestRoot.root;
  5888. found = true;
  5889. this._edge.scaleInPlace(f);
  5890. p3.addToRef(this._edge, this._collisionPoint);
  5891. }
  5892. }
  5893. }
  5894. if (found) {
  5895. var distToCollision = t * this.velocity.length();
  5896. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5897. if (!this.intersectionPoint) {
  5898. this.intersectionPoint = this._collisionPoint.clone();
  5899. } else {
  5900. this.intersectionPoint.copyFrom(this._collisionPoint);
  5901. }
  5902. this.nearestDistance = distToCollision;
  5903. this.collisionFound = true;
  5904. this.collidedMesh = subMesh.getMesh();
  5905. }
  5906. }
  5907. };
  5908. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5909. for (var i = indexStart; i < indexEnd; i += 3) {
  5910. var p1 = pts[indices[i] - decal];
  5911. var p2 = pts[indices[i + 1] - decal];
  5912. var p3 = pts[indices[i + 2] - decal];
  5913. this._testTriangle(i, subMesh, p3, p2, p1);
  5914. }
  5915. };
  5916. Collider.prototype._getResponse = function (pos, vel) {
  5917. pos.addToRef(vel, this._destinationPoint);
  5918. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5919. this.basePoint.addToRef(vel, pos);
  5920. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5921. this._slidePlaneNormal.normalize();
  5922. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5923. pos.addInPlace(this._displacementVector);
  5924. this.intersectionPoint.addInPlace(this._displacementVector);
  5925. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5926. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5927. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5928. };
  5929. return Collider;
  5930. })();
  5931. BABYLON.Collider = Collider;
  5932. })(BABYLON || (BABYLON = {}));
  5933. //# sourceMappingURL=babylon.collider.js.map
  5934. var BABYLON;
  5935. (function (BABYLON) {
  5936. var Camera = (function (_super) {
  5937. __extends(Camera, _super);
  5938. function Camera(name, position, scene) {
  5939. _super.call(this, name, scene);
  5940. this.position = position;
  5941. // Members
  5942. this.upVector = BABYLON.Vector3.Up();
  5943. this.orthoLeft = null;
  5944. this.orthoRight = null;
  5945. this.orthoBottom = null;
  5946. this.orthoTop = null;
  5947. this.fov = 0.8;
  5948. this.minZ = 1.0;
  5949. this.maxZ = 10000.0;
  5950. this.inertia = 0.9;
  5951. this.mode = Camera.PERSPECTIVE_CAMERA;
  5952. this.isIntermediate = false;
  5953. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  5954. this.subCameras = [];
  5955. this.layerMask = 0xFFFFFFFF;
  5956. this._computedViewMatrix = BABYLON.Matrix.Identity();
  5957. this._projectionMatrix = new BABYLON.Matrix();
  5958. this._postProcesses = new Array();
  5959. this._postProcessesTakenIndices = [];
  5960. scene.cameras.push(this);
  5961. if (!scene.activeCamera) {
  5962. scene.activeCamera = this;
  5963. }
  5964. }
  5965. //Cache
  5966. Camera.prototype._initCache = function () {
  5967. _super.prototype._initCache.call(this);
  5968. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5969. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5970. this._cache.mode = undefined;
  5971. this._cache.minZ = undefined;
  5972. this._cache.maxZ = undefined;
  5973. this._cache.fov = undefined;
  5974. this._cache.aspectRatio = undefined;
  5975. this._cache.orthoLeft = undefined;
  5976. this._cache.orthoRight = undefined;
  5977. this._cache.orthoBottom = undefined;
  5978. this._cache.orthoTop = undefined;
  5979. this._cache.renderWidth = undefined;
  5980. this._cache.renderHeight = undefined;
  5981. };
  5982. Camera.prototype._updateCache = function (ignoreParentClass) {
  5983. if (!ignoreParentClass) {
  5984. _super.prototype._updateCache.call(this);
  5985. }
  5986. var engine = this.getEngine();
  5987. this._cache.position.copyFrom(this.position);
  5988. this._cache.upVector.copyFrom(this.upVector);
  5989. this._cache.mode = this.mode;
  5990. this._cache.minZ = this.minZ;
  5991. this._cache.maxZ = this.maxZ;
  5992. this._cache.fov = this.fov;
  5993. this._cache.aspectRatio = engine.getAspectRatio(this);
  5994. this._cache.orthoLeft = this.orthoLeft;
  5995. this._cache.orthoRight = this.orthoRight;
  5996. this._cache.orthoBottom = this.orthoBottom;
  5997. this._cache.orthoTop = this.orthoTop;
  5998. this._cache.renderWidth = engine.getRenderWidth();
  5999. this._cache.renderHeight = engine.getRenderHeight();
  6000. };
  6001. Camera.prototype._updateFromScene = function () {
  6002. this.updateCache();
  6003. this._update();
  6004. };
  6005. // Synchronized
  6006. Camera.prototype._isSynchronized = function () {
  6007. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6008. };
  6009. Camera.prototype._isSynchronizedViewMatrix = function () {
  6010. if (!_super.prototype._isSynchronized.call(this))
  6011. return false;
  6012. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6013. };
  6014. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6015. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6016. if (!check) {
  6017. return false;
  6018. }
  6019. var engine = this.getEngine();
  6020. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6021. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6022. } else {
  6023. 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();
  6024. }
  6025. return check;
  6026. };
  6027. // Controls
  6028. Camera.prototype.attachControl = function (element) {
  6029. };
  6030. Camera.prototype.detachControl = function (element) {
  6031. };
  6032. Camera.prototype._update = function () {
  6033. };
  6034. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6035. if (typeof insertAt === "undefined") { insertAt = null; }
  6036. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6037. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6038. return 0;
  6039. }
  6040. if (insertAt == null || insertAt < 0) {
  6041. this._postProcesses.push(postProcess);
  6042. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6043. return this._postProcesses.length - 1;
  6044. }
  6045. var add = 0;
  6046. if (this._postProcesses[insertAt]) {
  6047. var start = this._postProcesses.length - 1;
  6048. for (var i = start; i >= insertAt + 1; --i) {
  6049. this._postProcesses[i + 1] = this._postProcesses[i];
  6050. }
  6051. add = 1;
  6052. }
  6053. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6054. if (this._postProcessesTakenIndices[i] < insertAt) {
  6055. continue;
  6056. }
  6057. start = this._postProcessesTakenIndices.length - 1;
  6058. for (var j = start; j >= i; --j) {
  6059. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6060. }
  6061. this._postProcessesTakenIndices[i] = insertAt;
  6062. break;
  6063. }
  6064. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6065. this._postProcessesTakenIndices.push(insertAt);
  6066. }
  6067. var result = insertAt + add;
  6068. this._postProcesses[result] = postProcess;
  6069. return result;
  6070. };
  6071. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6072. if (typeof atIndices === "undefined") { atIndices = null; }
  6073. var result = [];
  6074. if (!atIndices) {
  6075. var length = this._postProcesses.length;
  6076. for (var i = 0; i < length; i++) {
  6077. if (this._postProcesses[i] !== postProcess) {
  6078. continue;
  6079. }
  6080. delete this._postProcesses[i];
  6081. var index = this._postProcessesTakenIndices.indexOf(i);
  6082. this._postProcessesTakenIndices.splice(index, 1);
  6083. }
  6084. } else {
  6085. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6086. for (i = 0; i < atIndices.length; i++) {
  6087. var foundPostProcess = this._postProcesses[atIndices[i]];
  6088. if (foundPostProcess !== postProcess) {
  6089. result.push(i);
  6090. continue;
  6091. }
  6092. delete this._postProcesses[atIndices[i]];
  6093. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6094. this._postProcessesTakenIndices.splice(index, 1);
  6095. }
  6096. }
  6097. return result;
  6098. };
  6099. Camera.prototype.getWorldMatrix = function () {
  6100. if (!this._worldMatrix) {
  6101. this._worldMatrix = BABYLON.Matrix.Identity();
  6102. }
  6103. var viewMatrix = this.getViewMatrix();
  6104. viewMatrix.invertToRef(this._worldMatrix);
  6105. return this._worldMatrix;
  6106. };
  6107. Camera.prototype._getViewMatrix = function () {
  6108. return BABYLON.Matrix.Identity();
  6109. };
  6110. Camera.prototype.getViewMatrix = function () {
  6111. this._computedViewMatrix = this._computeViewMatrix();
  6112. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6113. return this._computedViewMatrix;
  6114. }
  6115. if (!this._worldMatrix) {
  6116. this._worldMatrix = BABYLON.Matrix.Identity();
  6117. }
  6118. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6119. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6120. this._computedViewMatrix.invert();
  6121. this._currentRenderId = this.getScene().getRenderId();
  6122. return this._computedViewMatrix;
  6123. };
  6124. Camera.prototype._computeViewMatrix = function (force) {
  6125. if (!force && this._isSynchronizedViewMatrix()) {
  6126. return this._computedViewMatrix;
  6127. }
  6128. this._computedViewMatrix = this._getViewMatrix();
  6129. if (!this.parent || !this.parent.getWorldMatrix) {
  6130. this._currentRenderId = this.getScene().getRenderId();
  6131. }
  6132. return this._computedViewMatrix;
  6133. };
  6134. Camera.prototype.getProjectionMatrix = function (force) {
  6135. if (!force && this._isSynchronizedProjectionMatrix()) {
  6136. return this._projectionMatrix;
  6137. }
  6138. var engine = this.getEngine();
  6139. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6140. if (this.minZ <= 0) {
  6141. this.minZ = 0.1;
  6142. }
  6143. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6144. return this._projectionMatrix;
  6145. }
  6146. var halfWidth = engine.getRenderWidth() / 2.0;
  6147. var halfHeight = engine.getRenderHeight() / 2.0;
  6148. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6149. return this._projectionMatrix;
  6150. };
  6151. Camera.prototype.dispose = function () {
  6152. // Remove from scene
  6153. var index = this.getScene().cameras.indexOf(this);
  6154. this.getScene().cameras.splice(index, 1);
  6155. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6156. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6157. }
  6158. };
  6159. Camera.PERSPECTIVE_CAMERA = 0;
  6160. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6161. return Camera;
  6162. })(BABYLON.Node);
  6163. BABYLON.Camera = Camera;
  6164. })(BABYLON || (BABYLON = {}));
  6165. //# sourceMappingURL=babylon.camera.js.map
  6166. var BABYLON;
  6167. (function (BABYLON) {
  6168. var TargetCamera = (function (_super) {
  6169. __extends(TargetCamera, _super);
  6170. function TargetCamera(name, position, scene) {
  6171. _super.call(this, name, position, scene);
  6172. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6173. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6174. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6175. this.speed = 2.0;
  6176. this.noRotationConstraint = false;
  6177. this.lockedTarget = null;
  6178. this._currentTarget = BABYLON.Vector3.Zero();
  6179. this._viewMatrix = BABYLON.Matrix.Zero();
  6180. this._camMatrix = BABYLON.Matrix.Zero();
  6181. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6182. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6183. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6184. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6185. this._lookAtTemp = BABYLON.Matrix.Zero();
  6186. this._tempMatrix = BABYLON.Matrix.Zero();
  6187. }
  6188. TargetCamera.prototype._getLockedTargetPosition = function () {
  6189. if (!this.lockedTarget) {
  6190. return null;
  6191. }
  6192. return this.lockedTarget.position || this.lockedTarget;
  6193. };
  6194. // Cache
  6195. TargetCamera.prototype._initCache = function () {
  6196. _super.prototype._initCache.call(this);
  6197. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6198. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6199. };
  6200. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6201. if (!ignoreParentClass) {
  6202. _super.prototype._updateCache.call(this);
  6203. }
  6204. var lockedTargetPosition = this._getLockedTargetPosition();
  6205. if (!lockedTargetPosition) {
  6206. this._cache.lockedTarget = null;
  6207. } else {
  6208. if (!this._cache.lockedTarget) {
  6209. this._cache.lockedTarget = lockedTargetPosition.clone();
  6210. } else {
  6211. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6212. }
  6213. }
  6214. this._cache.rotation.copyFrom(this.rotation);
  6215. };
  6216. // Synchronized
  6217. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6218. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6219. return false;
  6220. }
  6221. var lockedTargetPosition = this._getLockedTargetPosition();
  6222. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6223. };
  6224. // Methods
  6225. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6226. var engine = this.getEngine();
  6227. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6228. };
  6229. // Target
  6230. TargetCamera.prototype.setTarget = function (target) {
  6231. this.upVector.normalize();
  6232. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6233. this._camMatrix.invert();
  6234. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6235. var vDir = target.subtract(this.position);
  6236. if (vDir.x >= 0.0) {
  6237. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6238. } else {
  6239. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6240. }
  6241. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6242. if (isNaN(this.rotation.x)) {
  6243. this.rotation.x = 0;
  6244. }
  6245. if (isNaN(this.rotation.y)) {
  6246. this.rotation.y = 0;
  6247. }
  6248. if (isNaN(this.rotation.z)) {
  6249. this.rotation.z = 0;
  6250. }
  6251. };
  6252. TargetCamera.prototype.getTarget = function () {
  6253. return this._currentTarget;
  6254. };
  6255. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6256. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6257. };
  6258. TargetCamera.prototype._updatePosition = function () {
  6259. this.position.addInPlace(this.cameraDirection);
  6260. };
  6261. TargetCamera.prototype._update = function () {
  6262. var needToMove = this._decideIfNeedsToMove();
  6263. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6264. // Move
  6265. if (needToMove) {
  6266. this._updatePosition();
  6267. }
  6268. // Rotate
  6269. if (needToRotate) {
  6270. this.rotation.x += this.cameraRotation.x;
  6271. this.rotation.y += this.cameraRotation.y;
  6272. if (!this.noRotationConstraint) {
  6273. var limit = (Math.PI / 2) * 0.95;
  6274. if (this.rotation.x > limit)
  6275. this.rotation.x = limit;
  6276. if (this.rotation.x < -limit)
  6277. this.rotation.x = -limit;
  6278. }
  6279. }
  6280. // Inertia
  6281. if (needToMove) {
  6282. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6283. this.cameraDirection.x = 0;
  6284. }
  6285. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6286. this.cameraDirection.y = 0;
  6287. }
  6288. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6289. this.cameraDirection.z = 0;
  6290. }
  6291. this.cameraDirection.scaleInPlace(this.inertia);
  6292. }
  6293. if (needToRotate) {
  6294. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6295. this.cameraRotation.x = 0;
  6296. }
  6297. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6298. this.cameraRotation.y = 0;
  6299. }
  6300. this.cameraRotation.scaleInPlace(this.inertia);
  6301. }
  6302. };
  6303. TargetCamera.prototype._getViewMatrix = function () {
  6304. if (!this.lockedTarget) {
  6305. // Compute
  6306. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6307. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6308. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6309. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6310. this._lookAtTemp.invert();
  6311. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6312. } else {
  6313. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6314. }
  6315. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6316. // Computing target and final matrix
  6317. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6318. } else {
  6319. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6320. }
  6321. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6322. return this._viewMatrix;
  6323. };
  6324. return TargetCamera;
  6325. })(BABYLON.Camera);
  6326. BABYLON.TargetCamera = TargetCamera;
  6327. })(BABYLON || (BABYLON = {}));
  6328. //# sourceMappingURL=babylon.targetCamera.js.map
  6329. var BABYLON;
  6330. (function (BABYLON) {
  6331. var FollowCamera = (function (_super) {
  6332. __extends(FollowCamera, _super);
  6333. function FollowCamera(name, position, scene) {
  6334. _super.call(this, name, position, scene);
  6335. this.radius = 12;
  6336. this.rotationOffset = 0;
  6337. this.heightOffset = 4;
  6338. this.cameraAcceleration = 0.05;
  6339. this.maxCameraSpeed = 20;
  6340. }
  6341. FollowCamera.prototype.getRadians = function (degrees) {
  6342. return degrees * Math.PI / 180;
  6343. };
  6344. FollowCamera.prototype.follow = function (cameraTarget) {
  6345. if (!cameraTarget)
  6346. return;
  6347. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6348. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6349. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6350. var dx = targetX - this.position.x;
  6351. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6352. var dz = (targetZ) - this.position.z;
  6353. var vx = dx * this.cameraAcceleration * 2;
  6354. var vy = dy * this.cameraAcceleration;
  6355. var vz = dz * this.cameraAcceleration * 2;
  6356. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6357. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6358. }
  6359. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6360. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6361. }
  6362. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6363. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6364. }
  6365. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6366. this.setTarget(cameraTarget.position);
  6367. };
  6368. FollowCamera.prototype._update = function () {
  6369. _super.prototype._update.call(this);
  6370. this.follow(this.target);
  6371. };
  6372. return FollowCamera;
  6373. })(BABYLON.TargetCamera);
  6374. BABYLON.FollowCamera = FollowCamera;
  6375. })(BABYLON || (BABYLON = {}));
  6376. //# sourceMappingURL=babylon.followCamera.js.map
  6377. var BABYLON;
  6378. (function (BABYLON) {
  6379. var FreeCamera = (function (_super) {
  6380. __extends(FreeCamera, _super);
  6381. function FreeCamera(name, position, scene) {
  6382. _super.call(this, name, position, scene);
  6383. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6384. this.keysUp = [38];
  6385. this.keysDown = [40];
  6386. this.keysLeft = [37];
  6387. this.keysRight = [39];
  6388. this.checkCollisions = false;
  6389. this.applyGravity = false;
  6390. this.angularSensibility = 2000.0;
  6391. this._keys = [];
  6392. this._collider = new BABYLON.Collider();
  6393. this._needMoveForGravity = true;
  6394. this._oldPosition = BABYLON.Vector3.Zero();
  6395. this._diffPosition = BABYLON.Vector3.Zero();
  6396. this._newPosition = BABYLON.Vector3.Zero();
  6397. }
  6398. // Controls
  6399. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6400. var _this = this;
  6401. var previousPosition;
  6402. var engine = this.getEngine();
  6403. if (this._attachedElement) {
  6404. return;
  6405. }
  6406. this._attachedElement = element;
  6407. if (this._onMouseDown === undefined) {
  6408. this._onMouseDown = function (evt) {
  6409. previousPosition = {
  6410. x: evt.clientX,
  6411. y: evt.clientY
  6412. };
  6413. if (!noPreventDefault) {
  6414. evt.preventDefault();
  6415. }
  6416. };
  6417. this._onMouseUp = function (evt) {
  6418. previousPosition = null;
  6419. if (!noPreventDefault) {
  6420. evt.preventDefault();
  6421. }
  6422. };
  6423. this._onMouseOut = function (evt) {
  6424. previousPosition = null;
  6425. _this._keys = [];
  6426. if (!noPreventDefault) {
  6427. evt.preventDefault();
  6428. }
  6429. };
  6430. this._onMouseMove = function (evt) {
  6431. if (!previousPosition && !engine.isPointerLock) {
  6432. return;
  6433. }
  6434. var offsetX;
  6435. var offsetY;
  6436. if (!engine.isPointerLock) {
  6437. offsetX = evt.clientX - previousPosition.x;
  6438. offsetY = evt.clientY - previousPosition.y;
  6439. } else {
  6440. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6441. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6442. }
  6443. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6444. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6445. previousPosition = {
  6446. x: evt.clientX,
  6447. y: evt.clientY
  6448. };
  6449. if (!noPreventDefault) {
  6450. evt.preventDefault();
  6451. }
  6452. };
  6453. this._onKeyDown = function (evt) {
  6454. 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) {
  6455. var index = _this._keys.indexOf(evt.keyCode);
  6456. if (index === -1) {
  6457. _this._keys.push(evt.keyCode);
  6458. }
  6459. if (!noPreventDefault) {
  6460. evt.preventDefault();
  6461. }
  6462. }
  6463. };
  6464. this._onKeyUp = function (evt) {
  6465. 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) {
  6466. var index = _this._keys.indexOf(evt.keyCode);
  6467. if (index >= 0) {
  6468. _this._keys.splice(index, 1);
  6469. }
  6470. if (!noPreventDefault) {
  6471. evt.preventDefault();
  6472. }
  6473. }
  6474. };
  6475. this._onLostFocus = function () {
  6476. _this._keys = [];
  6477. };
  6478. this._reset = function () {
  6479. _this._keys = [];
  6480. previousPosition = null;
  6481. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6482. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6483. };
  6484. }
  6485. element.addEventListener("mousedown", this._onMouseDown, false);
  6486. element.addEventListener("mouseup", this._onMouseUp, false);
  6487. element.addEventListener("mouseout", this._onMouseOut, false);
  6488. element.addEventListener("mousemove", this._onMouseMove, false);
  6489. BABYLON.Tools.RegisterTopRootEvents([
  6490. { name: "keydown", handler: this._onKeyDown },
  6491. { name: "keyup", handler: this._onKeyUp },
  6492. { name: "blur", handler: this._onLostFocus }
  6493. ]);
  6494. };
  6495. FreeCamera.prototype.detachControl = function (element) {
  6496. if (this._attachedElement != element) {
  6497. return;
  6498. }
  6499. element.removeEventListener("mousedown", this._onMouseDown);
  6500. element.removeEventListener("mouseup", this._onMouseUp);
  6501. element.removeEventListener("mouseout", this._onMouseOut);
  6502. element.removeEventListener("mousemove", this._onMouseMove);
  6503. BABYLON.Tools.UnregisterTopRootEvents([
  6504. { name: "keydown", handler: this._onKeyDown },
  6505. { name: "keyup", handler: this._onKeyUp },
  6506. { name: "blur", handler: this._onLostFocus }
  6507. ]);
  6508. this._attachedElement = null;
  6509. if (this._reset) {
  6510. this._reset();
  6511. }
  6512. };
  6513. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6514. var globalPosition;
  6515. if (this.parent) {
  6516. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6517. } else {
  6518. globalPosition = this.position;
  6519. }
  6520. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6521. this._collider.radius = this.ellipsoid;
  6522. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6523. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6524. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6525. this.position.addInPlace(this._diffPosition);
  6526. if (this.onCollide) {
  6527. this.onCollide(this._collider.collidedMesh);
  6528. }
  6529. }
  6530. };
  6531. FreeCamera.prototype._checkInputs = function () {
  6532. if (!this._localDirection) {
  6533. this._localDirection = BABYLON.Vector3.Zero();
  6534. this._transformedDirection = BABYLON.Vector3.Zero();
  6535. }
  6536. for (var index = 0; index < this._keys.length; index++) {
  6537. var keyCode = this._keys[index];
  6538. var speed = this._computeLocalCameraSpeed();
  6539. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6540. this._localDirection.copyFromFloats(-speed, 0, 0);
  6541. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  6542. this._localDirection.copyFromFloats(0, 0, speed);
  6543. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  6544. this._localDirection.copyFromFloats(speed, 0, 0);
  6545. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  6546. this._localDirection.copyFromFloats(0, 0, -speed);
  6547. }
  6548. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6549. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6550. this.cameraDirection.addInPlace(this._transformedDirection);
  6551. }
  6552. };
  6553. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6554. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6555. };
  6556. FreeCamera.prototype._updatePosition = function () {
  6557. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6558. this._collideWithWorld(this.cameraDirection);
  6559. if (this.applyGravity) {
  6560. var oldPosition = this.position;
  6561. this._collideWithWorld(this.getScene().gravity);
  6562. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6563. }
  6564. } else {
  6565. this.position.addInPlace(this.cameraDirection);
  6566. }
  6567. };
  6568. FreeCamera.prototype._update = function () {
  6569. this._checkInputs();
  6570. _super.prototype._update.call(this);
  6571. };
  6572. return FreeCamera;
  6573. })(BABYLON.TargetCamera);
  6574. BABYLON.FreeCamera = FreeCamera;
  6575. })(BABYLON || (BABYLON = {}));
  6576. //# sourceMappingURL=babylon.freeCamera.js.map
  6577. var BABYLON;
  6578. (function (BABYLON) {
  6579. // We're mainly based on the logic defined into the FreeCamera code
  6580. var TouchCamera = (function (_super) {
  6581. __extends(TouchCamera, _super);
  6582. function TouchCamera(name, position, scene) {
  6583. _super.call(this, name, position, scene);
  6584. this._offsetX = null;
  6585. this._offsetY = null;
  6586. this._pointerCount = 0;
  6587. this._pointerPressed = [];
  6588. this.angularSensibility = 200000.0;
  6589. this.moveSensibility = 500.0;
  6590. }
  6591. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6592. var _this = this;
  6593. var previousPosition;
  6594. if (this._attachedCanvas) {
  6595. return;
  6596. }
  6597. this._attachedCanvas = canvas;
  6598. if (this._onPointerDown === undefined) {
  6599. this._onPointerDown = function (evt) {
  6600. if (!noPreventDefault) {
  6601. evt.preventDefault();
  6602. }
  6603. _this._pointerPressed.push(evt.pointerId);
  6604. if (_this._pointerPressed.length !== 1) {
  6605. return;
  6606. }
  6607. previousPosition = {
  6608. x: evt.clientX,
  6609. y: evt.clientY
  6610. };
  6611. };
  6612. this._onPointerUp = function (evt) {
  6613. if (!noPreventDefault) {
  6614. evt.preventDefault();
  6615. }
  6616. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6617. if (index === -1) {
  6618. return;
  6619. }
  6620. _this._pointerPressed.splice(index, 1);
  6621. if (index != 0) {
  6622. return;
  6623. }
  6624. previousPosition = null;
  6625. _this._offsetX = null;
  6626. _this._offsetY = null;
  6627. };
  6628. this._onPointerMove = function (evt) {
  6629. if (!noPreventDefault) {
  6630. evt.preventDefault();
  6631. }
  6632. if (!previousPosition) {
  6633. return;
  6634. }
  6635. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6636. if (index != 0) {
  6637. return;
  6638. }
  6639. _this._offsetX = evt.clientX - previousPosition.x;
  6640. _this._offsetY = -(evt.clientY - previousPosition.y);
  6641. };
  6642. this._onLostFocus = function () {
  6643. _this._offsetX = null;
  6644. _this._offsetY = null;
  6645. };
  6646. }
  6647. canvas.addEventListener("pointerdown", this._onPointerDown);
  6648. canvas.addEventListener("pointerup", this._onPointerUp);
  6649. canvas.addEventListener("pointerout", this._onPointerUp);
  6650. canvas.addEventListener("pointermove", this._onPointerMove);
  6651. BABYLON.Tools.RegisterTopRootEvents([
  6652. { name: "blur", handler: this._onLostFocus }
  6653. ]);
  6654. };
  6655. TouchCamera.prototype.detachControl = function (canvas) {
  6656. if (this._attachedCanvas != canvas) {
  6657. return;
  6658. }
  6659. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6660. canvas.removeEventListener("pointerup", this._onPointerUp);
  6661. canvas.removeEventListener("pointerout", this._onPointerUp);
  6662. canvas.removeEventListener("pointermove", this._onPointerMove);
  6663. BABYLON.Tools.UnregisterTopRootEvents([
  6664. { name: "blur", handler: this._onLostFocus }
  6665. ]);
  6666. this._attachedCanvas = null;
  6667. };
  6668. TouchCamera.prototype._checkInputs = function () {
  6669. if (!this._offsetX) {
  6670. return;
  6671. }
  6672. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6673. if (this._pointerPressed.length > 1) {
  6674. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6675. } else {
  6676. var speed = this._computeLocalCameraSpeed();
  6677. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6678. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6679. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6680. }
  6681. };
  6682. return TouchCamera;
  6683. })(BABYLON.FreeCamera);
  6684. BABYLON.TouchCamera = TouchCamera;
  6685. })(BABYLON || (BABYLON = {}));
  6686. //# sourceMappingURL=babylon.touchCamera.js.map
  6687. var BABYLON;
  6688. (function (BABYLON) {
  6689. // We're mainly based on the logic defined into the FreeCamera code
  6690. var DeviceOrientationCamera = (function (_super) {
  6691. __extends(DeviceOrientationCamera, _super);
  6692. function DeviceOrientationCamera(name, position, scene) {
  6693. var _this = this;
  6694. _super.call(this, name, position, scene);
  6695. this._offsetX = null;
  6696. this._offsetY = null;
  6697. this._orientationGamma = 0;
  6698. this._orientationBeta = 0;
  6699. this._initialOrientationGamma = 0;
  6700. this._initialOrientationBeta = 0;
  6701. this.angularSensibility = 10000.0;
  6702. this.moveSensibility = 50.0;
  6703. window.addEventListener("resize", function () {
  6704. _this._initialOrientationGamma = null;
  6705. }, false);
  6706. }
  6707. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6708. var _this = this;
  6709. if (this._attachedCanvas) {
  6710. return;
  6711. }
  6712. this._attachedCanvas = canvas;
  6713. if (!this._orientationChanged) {
  6714. this._orientationChanged = function (evt) {
  6715. if (!_this._initialOrientationGamma) {
  6716. _this._initialOrientationGamma = evt.gamma;
  6717. _this._initialOrientationBeta = evt.beta;
  6718. }
  6719. _this._orientationGamma = evt.gamma;
  6720. _this._orientationBeta = evt.beta;
  6721. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6722. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6723. };
  6724. }
  6725. window.addEventListener("deviceorientation", this._orientationChanged);
  6726. };
  6727. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6728. if (this._attachedCanvas != canvas) {
  6729. return;
  6730. }
  6731. window.removeEventListener("deviceorientation", this._orientationChanged);
  6732. this._attachedCanvas = null;
  6733. this._orientationGamma = 0;
  6734. this._orientationBeta = 0;
  6735. this._initialOrientationGamma = 0;
  6736. this._initialOrientationBeta = 0;
  6737. };
  6738. DeviceOrientationCamera.prototype._checkInputs = function () {
  6739. if (!this._offsetX) {
  6740. return;
  6741. }
  6742. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6743. var speed = this._computeLocalCameraSpeed();
  6744. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6745. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6746. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6747. };
  6748. return DeviceOrientationCamera;
  6749. })(BABYLON.FreeCamera);
  6750. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6751. })(BABYLON || (BABYLON = {}));
  6752. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6753. var BABYLON;
  6754. (function (BABYLON) {
  6755. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6756. var ArcRotateCamera = (function (_super) {
  6757. __extends(ArcRotateCamera, _super);
  6758. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6759. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6760. this.alpha = alpha;
  6761. this.beta = beta;
  6762. this.radius = radius;
  6763. this.target = target;
  6764. this.inertialAlphaOffset = 0;
  6765. this.inertialBetaOffset = 0;
  6766. this.inertialRadiusOffset = 0;
  6767. this.lowerAlphaLimit = null;
  6768. this.upperAlphaLimit = null;
  6769. this.lowerBetaLimit = 0.01;
  6770. this.upperBetaLimit = Math.PI;
  6771. this.lowerRadiusLimit = null;
  6772. this.upperRadiusLimit = null;
  6773. this.angularSensibility = 1000.0;
  6774. this.wheelPrecision = 3.0;
  6775. this.keysUp = [38];
  6776. this.keysDown = [40];
  6777. this.keysLeft = [37];
  6778. this.keysRight = [39];
  6779. this.zoomOnFactor = 1;
  6780. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6781. this._keys = [];
  6782. this._viewMatrix = new BABYLON.Matrix();
  6783. this.checkCollisions = false;
  6784. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6785. this._collider = new BABYLON.Collider();
  6786. this._previousPosition = BABYLON.Vector3.Zero();
  6787. this._collisionVelocity = BABYLON.Vector3.Zero();
  6788. this._newPosition = BABYLON.Vector3.Zero();
  6789. // Pinch
  6790. // value for pinch step scaling
  6791. // set to 20 by default
  6792. this.pinchPrecision = 20;
  6793. this.getViewMatrix();
  6794. }
  6795. ArcRotateCamera.prototype._getTargetPosition = function () {
  6796. return this.target.position || this.target;
  6797. };
  6798. // Cache
  6799. ArcRotateCamera.prototype._initCache = function () {
  6800. _super.prototype._initCache.call(this);
  6801. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6802. this._cache.alpha = undefined;
  6803. this._cache.beta = undefined;
  6804. this._cache.radius = undefined;
  6805. this._cache.targetScreenOffset = undefined;
  6806. };
  6807. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6808. if (!ignoreParentClass) {
  6809. _super.prototype._updateCache.call(this);
  6810. }
  6811. this._cache.target.copyFrom(this._getTargetPosition());
  6812. this._cache.alpha = this.alpha;
  6813. this._cache.beta = this.beta;
  6814. this._cache.radius = this.radius;
  6815. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6816. };
  6817. // Synchronized
  6818. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6819. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6820. return false;
  6821. 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);
  6822. };
  6823. // Methods
  6824. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6825. var _this = this;
  6826. var previousPosition;
  6827. var pointerId;
  6828. // to know if pinch started
  6829. var pinchStarted = false;
  6830. // two pinch point on X
  6831. // that will use for find if user action is pinch open or pinch close
  6832. var pinchPointX1, pinchPointX2;
  6833. if (this._attachedElement) {
  6834. return;
  6835. }
  6836. this._attachedElement = element;
  6837. var engine = this.getEngine();
  6838. if (this._onPointerDown === undefined) {
  6839. this._onPointerDown = function (evt) {
  6840. if (pointerId) {
  6841. return;
  6842. }
  6843. pointerId = evt.pointerId;
  6844. previousPosition = {
  6845. x: evt.clientX,
  6846. y: evt.clientY
  6847. };
  6848. if (!noPreventDefault) {
  6849. evt.preventDefault();
  6850. }
  6851. };
  6852. this._onPointerUp = function (evt) {
  6853. previousPosition = null;
  6854. pointerId = null;
  6855. if (!noPreventDefault) {
  6856. evt.preventDefault();
  6857. }
  6858. };
  6859. this._onPointerMove = function (evt) {
  6860. if (!previousPosition) {
  6861. return;
  6862. }
  6863. if (pointerId !== evt.pointerId) {
  6864. return;
  6865. }
  6866. // return pinch is started
  6867. if (pinchStarted) {
  6868. return;
  6869. }
  6870. var offsetX = evt.clientX - previousPosition.x;
  6871. var offsetY = evt.clientY - previousPosition.y;
  6872. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6873. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6874. previousPosition = {
  6875. x: evt.clientX,
  6876. y: evt.clientY
  6877. };
  6878. if (!noPreventDefault) {
  6879. evt.preventDefault();
  6880. }
  6881. };
  6882. this._onMouseMove = function (evt) {
  6883. if (!engine.isPointerLock) {
  6884. return;
  6885. }
  6886. // return pinch is started
  6887. if (pinchStarted) {
  6888. return;
  6889. }
  6890. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6891. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6892. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6893. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6894. if (!noPreventDefault) {
  6895. evt.preventDefault();
  6896. }
  6897. };
  6898. this._wheel = function (event) {
  6899. var delta = 0;
  6900. if (event.wheelDelta) {
  6901. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6902. } else if (event.detail) {
  6903. delta = -event.detail / _this.wheelPrecision;
  6904. }
  6905. if (delta)
  6906. _this.inertialRadiusOffset += delta;
  6907. if (event.preventDefault) {
  6908. if (!noPreventDefault) {
  6909. event.preventDefault();
  6910. }
  6911. }
  6912. };
  6913. this._onKeyDown = function (evt) {
  6914. 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) {
  6915. var index = _this._keys.indexOf(evt.keyCode);
  6916. if (index === -1) {
  6917. _this._keys.push(evt.keyCode);
  6918. }
  6919. if (evt.preventDefault) {
  6920. if (!noPreventDefault) {
  6921. evt.preventDefault();
  6922. }
  6923. }
  6924. }
  6925. };
  6926. this._onKeyUp = function (evt) {
  6927. 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) {
  6928. var index = _this._keys.indexOf(evt.keyCode);
  6929. if (index >= 0) {
  6930. _this._keys.splice(index, 1);
  6931. }
  6932. if (evt.preventDefault) {
  6933. if (!noPreventDefault) {
  6934. evt.preventDefault();
  6935. }
  6936. }
  6937. }
  6938. };
  6939. this._onLostFocus = function () {
  6940. _this._keys = [];
  6941. pointerId = null;
  6942. };
  6943. this._onGestureStart = function (e) {
  6944. if (window.MSGesture === undefined) {
  6945. return;
  6946. }
  6947. if (!_this._MSGestureHandler) {
  6948. _this._MSGestureHandler = new MSGesture();
  6949. _this._MSGestureHandler.target = element;
  6950. }
  6951. _this._MSGestureHandler.addPointer(e.pointerId);
  6952. };
  6953. this._onGesture = function (e) {
  6954. _this.radius *= e.scale;
  6955. if (e.preventDefault) {
  6956. if (!noPreventDefault) {
  6957. e.stopPropagation();
  6958. e.preventDefault();
  6959. }
  6960. }
  6961. };
  6962. this._reset = function () {
  6963. _this._keys = [];
  6964. _this.inertialAlphaOffset = 0;
  6965. _this.inertialBetaOffset = 0;
  6966. _this.inertialRadiusOffset = 0;
  6967. previousPosition = null;
  6968. pointerId = null;
  6969. };
  6970. this._touchStart = function (event) {
  6971. if (event.touches.length === 2) {
  6972. //-- start pinch if two fingers on the screen
  6973. pinchStarted = true;
  6974. _this._pinchStart(event);
  6975. }
  6976. };
  6977. this._touchMove = function (event) {
  6978. if (pinchStarted) {
  6979. //-- make scaling
  6980. _this._pinchMove(event);
  6981. }
  6982. };
  6983. this._touchEnd = function (event) {
  6984. if (pinchStarted) {
  6985. //-- end of pinch
  6986. _this._pinchEnd(event);
  6987. }
  6988. };
  6989. this._pinchStart = function (event) {
  6990. // save origin touch point
  6991. pinchPointX1 = event.touches[0].clientX;
  6992. pinchPointX2 = event.touches[1].clientX;
  6993. // block the camera
  6994. // if not it rotate around target during pinch
  6995. pinchStarted = true;
  6996. };
  6997. this._pinchMove = function (event) {
  6998. // variable for new camera's radius
  6999. var delta = 0;
  7000. // variables to know if pinch open or pinch close
  7001. var direction = 1;
  7002. var distanceXOrigine, distanceXNow;
  7003. if (event.touches.length !== 2)
  7004. return;
  7005. // calculate absolute distances of the two fingers
  7006. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7007. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7008. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7009. if (distanceXNow < distanceXOrigine) {
  7010. direction = -1;
  7011. }
  7012. // calculate new radius
  7013. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7014. // set new radius
  7015. _this.inertialRadiusOffset -= delta;
  7016. // save origin touch point
  7017. pinchPointX1 = event.touches[0].clientX;
  7018. pinchPointX2 = event.touches[1].clientX;
  7019. };
  7020. this._pinchEnd = function (event) {
  7021. // cancel pinch and deblock camera rotation
  7022. pinchStarted = false;
  7023. };
  7024. }
  7025. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7026. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7027. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7028. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7029. element.addEventListener("mousemove", this._onMouseMove, false);
  7030. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7031. element.addEventListener("MSGestureChange", this._onGesture, false);
  7032. element.addEventListener('mousewheel', this._wheel, false);
  7033. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7034. // pinch
  7035. element.addEventListener('touchstart', this._touchStart, false);
  7036. element.addEventListener('touchmove', this._touchMove, false);
  7037. element.addEventListener('touchend', this._touchEnd, false);
  7038. BABYLON.Tools.RegisterTopRootEvents([
  7039. { name: "keydown", handler: this._onKeyDown },
  7040. { name: "keyup", handler: this._onKeyUp },
  7041. { name: "blur", handler: this._onLostFocus }
  7042. ]);
  7043. };
  7044. ArcRotateCamera.prototype.detachControl = function (element) {
  7045. if (this._attachedElement != element) {
  7046. return;
  7047. }
  7048. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7049. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7050. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7051. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7052. element.removeEventListener("mousemove", this._onMouseMove);
  7053. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7054. element.removeEventListener("MSGestureChange", this._onGesture);
  7055. element.removeEventListener('mousewheel', this._wheel);
  7056. element.removeEventListener('DOMMouseScroll', this._wheel);
  7057. // pinch
  7058. element.removeEventListener('touchstart', this._touchStart);
  7059. element.removeEventListener('touchmove', this._touchMove);
  7060. element.removeEventListener('touchend', this._touchEnd);
  7061. BABYLON.Tools.UnregisterTopRootEvents([
  7062. { name: "keydown", handler: this._onKeyDown },
  7063. { name: "keyup", handler: this._onKeyUp },
  7064. { name: "blur", handler: this._onLostFocus }
  7065. ]);
  7066. this._MSGestureHandler = null;
  7067. this._attachedElement = null;
  7068. if (this._reset) {
  7069. this._reset();
  7070. }
  7071. };
  7072. ArcRotateCamera.prototype._update = function () {
  7073. for (var index = 0; index < this._keys.length; index++) {
  7074. var keyCode = this._keys[index];
  7075. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7076. this.inertialAlphaOffset -= 0.01;
  7077. } else if (this.keysUp.indexOf(keyCode) !== -1) {
  7078. this.inertialBetaOffset -= 0.01;
  7079. } else if (this.keysRight.indexOf(keyCode) !== -1) {
  7080. this.inertialAlphaOffset += 0.01;
  7081. } else if (this.keysDown.indexOf(keyCode) !== -1) {
  7082. this.inertialBetaOffset += 0.01;
  7083. }
  7084. }
  7085. // Inertia
  7086. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7087. this.alpha += this.inertialAlphaOffset;
  7088. this.beta += this.inertialBetaOffset;
  7089. this.radius -= this.inertialRadiusOffset;
  7090. this.inertialAlphaOffset *= this.inertia;
  7091. this.inertialBetaOffset *= this.inertia;
  7092. this.inertialRadiusOffset *= this.inertia;
  7093. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7094. this.inertialAlphaOffset = 0;
  7095. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7096. this.inertialBetaOffset = 0;
  7097. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7098. this.inertialRadiusOffset = 0;
  7099. }
  7100. // Limits
  7101. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7102. this.alpha = this.lowerAlphaLimit;
  7103. }
  7104. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7105. this.alpha = this.upperAlphaLimit;
  7106. }
  7107. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7108. this.beta = this.lowerBetaLimit;
  7109. }
  7110. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7111. this.beta = this.upperBetaLimit;
  7112. }
  7113. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7114. this.radius = this.lowerRadiusLimit;
  7115. }
  7116. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7117. this.radius = this.upperRadiusLimit;
  7118. }
  7119. };
  7120. ArcRotateCamera.prototype.setPosition = function (position) {
  7121. var radiusv3 = position.subtract(this._getTargetPosition());
  7122. this.radius = radiusv3.length();
  7123. // Alpha
  7124. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7125. if (radiusv3.z < 0) {
  7126. this.alpha = 2 * Math.PI - this.alpha;
  7127. }
  7128. // Beta
  7129. this.beta = Math.acos(radiusv3.y / this.radius);
  7130. };
  7131. ArcRotateCamera.prototype._getViewMatrix = function () {
  7132. // Compute
  7133. var cosa = Math.cos(this.alpha);
  7134. var sina = Math.sin(this.alpha);
  7135. var cosb = Math.cos(this.beta);
  7136. var sinb = Math.sin(this.beta);
  7137. var target = this._getTargetPosition();
  7138. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7139. if (this.checkCollisions) {
  7140. this._collider.radius = this.collisionRadius;
  7141. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7142. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7143. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7144. this.position.copyFrom(this._previousPosition);
  7145. this.alpha = this._previousAlpha;
  7146. this.beta = this._previousBeta;
  7147. this.radius = this._previousRadius;
  7148. if (this.onCollide) {
  7149. this.onCollide(this._collider.collidedMesh);
  7150. }
  7151. }
  7152. }
  7153. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7154. this._previousAlpha = this.alpha;
  7155. this._previousBeta = this.beta;
  7156. this._previousRadius = this.radius;
  7157. this._previousPosition.copyFrom(this.position);
  7158. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7159. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7160. return this._viewMatrix;
  7161. };
  7162. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7163. meshes = meshes || this.getScene().meshes;
  7164. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7165. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7166. this.radius = distance * this.zoomOnFactor;
  7167. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7168. };
  7169. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7170. var meshesOrMinMaxVector;
  7171. var distance;
  7172. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7173. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7174. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7175. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7176. } else {
  7177. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7178. distance = meshesOrMinMaxVectorAndDistance.distance;
  7179. }
  7180. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7181. this.maxZ = distance * 2;
  7182. };
  7183. return ArcRotateCamera;
  7184. })(BABYLON.Camera);
  7185. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7186. })(BABYLON || (BABYLON = {}));
  7187. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  7188. var BABYLON;
  7189. (function (BABYLON) {
  7190. var Scene = (function () {
  7191. // Constructor
  7192. function Scene(engine) {
  7193. // Members
  7194. this.autoClear = true;
  7195. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7196. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7197. this.forceWireframe = false;
  7198. this.forcePointsCloud = false;
  7199. this.forceShowBoundingBoxes = false;
  7200. this.animationsEnabled = true;
  7201. this.cameraToUseForPointers = null;
  7202. // Fog
  7203. this.fogEnabled = true;
  7204. this.fogMode = Scene.FOGMODE_NONE;
  7205. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7206. this.fogDensity = 0.1;
  7207. this.fogStart = 0;
  7208. this.fogEnd = 1000.0;
  7209. // Lights
  7210. this.shadowsEnabled = true;
  7211. this.lightsEnabled = true;
  7212. this.lights = new Array();
  7213. // Cameras
  7214. this.cameras = new Array();
  7215. this.activeCameras = new Array();
  7216. // Meshes
  7217. this.meshes = new Array();
  7218. // Geometries
  7219. this._geometries = new Array();
  7220. this.materials = new Array();
  7221. this.multiMaterials = new Array();
  7222. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7223. // Textures
  7224. this.texturesEnabled = true;
  7225. this.textures = new Array();
  7226. // Particles
  7227. this.particlesEnabled = true;
  7228. this.particleSystems = new Array();
  7229. // Sprites
  7230. this.spriteManagers = new Array();
  7231. // Layers
  7232. this.layers = new Array();
  7233. // Skeletons
  7234. this.skeletonsEnabled = true;
  7235. this.skeletons = new Array();
  7236. // Lens flares
  7237. this.lensFlaresEnabled = true;
  7238. this.lensFlareSystems = new Array();
  7239. // Collisions
  7240. this.collisionsEnabled = true;
  7241. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7242. // Postprocesses
  7243. this.postProcessesEnabled = true;
  7244. // Customs render targets
  7245. this.renderTargetsEnabled = true;
  7246. this.customRenderTargets = new Array();
  7247. // Imported meshes
  7248. this.importedMeshesFiles = new Array();
  7249. this._actionManagers = new Array();
  7250. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7251. // Procedural textures
  7252. this.proceduralTexturesEnabled = true;
  7253. this._proceduralTextures = new Array();
  7254. this.soundTracks = new Array();
  7255. this._totalVertices = 0;
  7256. this._activeVertices = 0;
  7257. this._activeParticles = 0;
  7258. this._lastFrameDuration = 0;
  7259. this._evaluateActiveMeshesDuration = 0;
  7260. this._renderTargetsDuration = 0;
  7261. this._particlesDuration = 0;
  7262. this._renderDuration = 0;
  7263. this._spritesDuration = 0;
  7264. this._animationRatio = 0;
  7265. this._renderId = 0;
  7266. this._executeWhenReadyTimeoutId = -1;
  7267. this._toBeDisposed = new BABYLON.SmartArray(256);
  7268. this._onReadyCallbacks = new Array();
  7269. this._pendingData = [];
  7270. this._onBeforeRenderCallbacks = new Array();
  7271. this._onAfterRenderCallbacks = new Array();
  7272. this._activeMeshes = new BABYLON.SmartArray(256);
  7273. this._processedMaterials = new BABYLON.SmartArray(256);
  7274. this._renderTargets = new BABYLON.SmartArray(256);
  7275. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7276. this._activeSkeletons = new BABYLON.SmartArray(32);
  7277. this._activeBones = 0;
  7278. this._activeAnimatables = new Array();
  7279. this._transformMatrix = BABYLON.Matrix.Zero();
  7280. this._scaledPosition = BABYLON.Vector3.Zero();
  7281. this._scaledVelocity = BABYLON.Vector3.Zero();
  7282. this._engine = engine;
  7283. engine.scenes.push(this);
  7284. this._renderingManager = new BABYLON.RenderingManager(this);
  7285. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7286. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7287. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7288. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7289. this.attachControl();
  7290. this._debugLayer = new BABYLON.DebugLayer(this);
  7291. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7292. }
  7293. Object.defineProperty(Scene.prototype, "debugLayer", {
  7294. // Properties
  7295. get: function () {
  7296. return this._debugLayer;
  7297. },
  7298. enumerable: true,
  7299. configurable: true
  7300. });
  7301. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7302. get: function () {
  7303. return this._meshUnderPointer;
  7304. },
  7305. enumerable: true,
  7306. configurable: true
  7307. });
  7308. Object.defineProperty(Scene.prototype, "pointerX", {
  7309. get: function () {
  7310. return this._pointerX;
  7311. },
  7312. enumerable: true,
  7313. configurable: true
  7314. });
  7315. Object.defineProperty(Scene.prototype, "pointerY", {
  7316. get: function () {
  7317. return this._pointerY;
  7318. },
  7319. enumerable: true,
  7320. configurable: true
  7321. });
  7322. Scene.prototype.getCachedMaterial = function () {
  7323. return this._cachedMaterial;
  7324. };
  7325. Scene.prototype.getBoundingBoxRenderer = function () {
  7326. return this._boundingBoxRenderer;
  7327. };
  7328. Scene.prototype.getOutlineRenderer = function () {
  7329. return this._outlineRenderer;
  7330. };
  7331. Scene.prototype.getEngine = function () {
  7332. return this._engine;
  7333. };
  7334. Scene.prototype.getTotalVertices = function () {
  7335. return this._totalVertices;
  7336. };
  7337. Scene.prototype.getActiveVertices = function () {
  7338. return this._activeVertices;
  7339. };
  7340. Scene.prototype.getActiveParticles = function () {
  7341. return this._activeParticles;
  7342. };
  7343. Scene.prototype.getActiveBones = function () {
  7344. return this._activeBones;
  7345. };
  7346. // Stats
  7347. Scene.prototype.getLastFrameDuration = function () {
  7348. return this._lastFrameDuration;
  7349. };
  7350. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7351. return this._evaluateActiveMeshesDuration;
  7352. };
  7353. Scene.prototype.getActiveMeshes = function () {
  7354. return this._activeMeshes;
  7355. };
  7356. Scene.prototype.getRenderTargetsDuration = function () {
  7357. return this._renderTargetsDuration;
  7358. };
  7359. Scene.prototype.getRenderDuration = function () {
  7360. return this._renderDuration;
  7361. };
  7362. Scene.prototype.getParticlesDuration = function () {
  7363. return this._particlesDuration;
  7364. };
  7365. Scene.prototype.getSpritesDuration = function () {
  7366. return this._spritesDuration;
  7367. };
  7368. Scene.prototype.getAnimationRatio = function () {
  7369. return this._animationRatio;
  7370. };
  7371. Scene.prototype.getRenderId = function () {
  7372. return this._renderId;
  7373. };
  7374. Scene.prototype._updatePointerPosition = function (evt) {
  7375. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7376. this._pointerX = evt.clientX - canvasRect.left;
  7377. this._pointerY = evt.clientY - canvasRect.top;
  7378. if (this.cameraToUseForPointers) {
  7379. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7380. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7381. }
  7382. };
  7383. // Pointers handling
  7384. Scene.prototype.attachControl = function () {
  7385. var _this = this;
  7386. this._onPointerMove = function (evt) {
  7387. var canvas = _this._engine.getRenderingCanvas();
  7388. _this._updatePointerPosition(evt);
  7389. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) {
  7390. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers;
  7391. }, false, _this.cameraToUseForPointers);
  7392. if (pickResult.hit) {
  7393. _this._meshUnderPointer = pickResult.pickedMesh;
  7394. _this.setPointerOverMesh(pickResult.pickedMesh);
  7395. canvas.style.cursor = "pointer";
  7396. } else {
  7397. _this.setPointerOverMesh(null);
  7398. canvas.style.cursor = "";
  7399. _this._meshUnderPointer = null;
  7400. }
  7401. };
  7402. this._onPointerDown = function (evt) {
  7403. var predicate = null;
  7404. if (!_this.onPointerDown) {
  7405. predicate = function (mesh) {
  7406. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7407. };
  7408. }
  7409. _this._updatePointerPosition(evt);
  7410. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7411. if (pickResult.hit) {
  7412. if (pickResult.pickedMesh.actionManager) {
  7413. switch (evt.button) {
  7414. case 0:
  7415. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7416. break;
  7417. case 1:
  7418. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7419. break;
  7420. case 2:
  7421. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7422. break;
  7423. }
  7424. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7425. }
  7426. }
  7427. if (_this.onPointerDown) {
  7428. _this.onPointerDown(evt, pickResult);
  7429. }
  7430. };
  7431. this._onKeyDown = function (evt) {
  7432. if (_this.actionManager) {
  7433. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7434. }
  7435. };
  7436. this._onKeyUp = function (evt) {
  7437. if (_this.actionManager) {
  7438. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7439. }
  7440. };
  7441. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7442. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7443. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7444. window.addEventListener("keydown", this._onKeyDown, false);
  7445. window.addEventListener("keyup", this._onKeyUp, false);
  7446. };
  7447. Scene.prototype.detachControl = function () {
  7448. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7449. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7450. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7451. window.removeEventListener("keydown", this._onKeyDown);
  7452. window.removeEventListener("keyup", this._onKeyUp);
  7453. };
  7454. // Ready
  7455. Scene.prototype.isReady = function () {
  7456. if (this._pendingData.length > 0) {
  7457. return false;
  7458. }
  7459. for (var index = 0; index < this._geometries.length; index++) {
  7460. var geometry = this._geometries[index];
  7461. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7462. return false;
  7463. }
  7464. }
  7465. for (index = 0; index < this.meshes.length; index++) {
  7466. var mesh = this.meshes[index];
  7467. if (!mesh.isReady()) {
  7468. return false;
  7469. }
  7470. var mat = mesh.material;
  7471. if (mat) {
  7472. if (!mat.isReady(mesh)) {
  7473. return false;
  7474. }
  7475. }
  7476. }
  7477. return true;
  7478. };
  7479. Scene.prototype.resetCachedMaterial = function () {
  7480. this._cachedMaterial = null;
  7481. };
  7482. Scene.prototype.registerBeforeRender = function (func) {
  7483. this._onBeforeRenderCallbacks.push(func);
  7484. };
  7485. Scene.prototype.unregisterBeforeRender = function (func) {
  7486. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7487. if (index > -1) {
  7488. this._onBeforeRenderCallbacks.splice(index, 1);
  7489. }
  7490. };
  7491. Scene.prototype.registerAfterRender = function (func) {
  7492. this._onAfterRenderCallbacks.push(func);
  7493. };
  7494. Scene.prototype.unregisterAfterRender = function (func) {
  7495. var index = this._onAfterRenderCallbacks.indexOf(func);
  7496. if (index > -1) {
  7497. this._onAfterRenderCallbacks.splice(index, 1);
  7498. }
  7499. };
  7500. Scene.prototype._addPendingData = function (data) {
  7501. this._pendingData.push(data);
  7502. };
  7503. Scene.prototype._removePendingData = function (data) {
  7504. var index = this._pendingData.indexOf(data);
  7505. if (index !== -1) {
  7506. this._pendingData.splice(index, 1);
  7507. }
  7508. };
  7509. Scene.prototype.getWaitingItemsCount = function () {
  7510. return this._pendingData.length;
  7511. };
  7512. Scene.prototype.executeWhenReady = function (func) {
  7513. var _this = this;
  7514. this._onReadyCallbacks.push(func);
  7515. if (this._executeWhenReadyTimeoutId !== -1) {
  7516. return;
  7517. }
  7518. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7519. _this._checkIsReady();
  7520. }, 150);
  7521. };
  7522. Scene.prototype._checkIsReady = function () {
  7523. var _this = this;
  7524. if (this.isReady()) {
  7525. this._onReadyCallbacks.forEach(function (func) {
  7526. func();
  7527. });
  7528. this._onReadyCallbacks = [];
  7529. this._executeWhenReadyTimeoutId = -1;
  7530. return;
  7531. }
  7532. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7533. _this._checkIsReady();
  7534. }, 150);
  7535. };
  7536. // Animations
  7537. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7538. if (speedRatio === undefined) {
  7539. speedRatio = 1.0;
  7540. }
  7541. this.stopAnimation(target);
  7542. if (!animatable) {
  7543. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7544. }
  7545. // Local animations
  7546. if (target.animations) {
  7547. animatable.appendAnimations(target, target.animations);
  7548. }
  7549. // Children animations
  7550. if (target.getAnimatables) {
  7551. var animatables = target.getAnimatables();
  7552. for (var index = 0; index < animatables.length; index++) {
  7553. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7554. }
  7555. }
  7556. return animatable;
  7557. };
  7558. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7559. if (speedRatio === undefined) {
  7560. speedRatio = 1.0;
  7561. }
  7562. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7563. return animatable;
  7564. };
  7565. Scene.prototype.getAnimatableByTarget = function (target) {
  7566. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7567. if (this._activeAnimatables[index].target === target) {
  7568. return this._activeAnimatables[index];
  7569. }
  7570. }
  7571. return null;
  7572. };
  7573. Scene.prototype.stopAnimation = function (target) {
  7574. var animatable = this.getAnimatableByTarget(target);
  7575. if (animatable) {
  7576. animatable.stop();
  7577. }
  7578. };
  7579. Scene.prototype._animate = function () {
  7580. if (!this.animationsEnabled) {
  7581. return;
  7582. }
  7583. if (!this._animationStartDate) {
  7584. this._animationStartDate = BABYLON.Tools.Now;
  7585. }
  7586. // Getting time
  7587. var now = BABYLON.Tools.Now;
  7588. var delay = now - this._animationStartDate;
  7589. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7590. if (!this._activeAnimatables[index]._animate(delay)) {
  7591. this._activeAnimatables.splice(index, 1);
  7592. index--;
  7593. }
  7594. }
  7595. };
  7596. // Matrix
  7597. Scene.prototype.getViewMatrix = function () {
  7598. return this._viewMatrix;
  7599. };
  7600. Scene.prototype.getProjectionMatrix = function () {
  7601. return this._projectionMatrix;
  7602. };
  7603. Scene.prototype.getTransformMatrix = function () {
  7604. return this._transformMatrix;
  7605. };
  7606. Scene.prototype.setTransformMatrix = function (view, projection) {
  7607. this._viewMatrix = view;
  7608. this._projectionMatrix = projection;
  7609. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7610. };
  7611. // Methods
  7612. Scene.prototype.setActiveCameraByID = function (id) {
  7613. var camera = this.getCameraByID(id);
  7614. if (camera) {
  7615. this.activeCamera = camera;
  7616. return camera;
  7617. }
  7618. return null;
  7619. };
  7620. Scene.prototype.setActiveCameraByName = function (name) {
  7621. var camera = this.getCameraByName(name);
  7622. if (camera) {
  7623. this.activeCamera = camera;
  7624. return camera;
  7625. }
  7626. return null;
  7627. };
  7628. Scene.prototype.getMaterialByID = function (id) {
  7629. for (var index = 0; index < this.materials.length; index++) {
  7630. if (this.materials[index].id === id) {
  7631. return this.materials[index];
  7632. }
  7633. }
  7634. return null;
  7635. };
  7636. Scene.prototype.getMaterialByName = function (name) {
  7637. for (var index = 0; index < this.materials.length; index++) {
  7638. if (this.materials[index].name === name) {
  7639. return this.materials[index];
  7640. }
  7641. }
  7642. return null;
  7643. };
  7644. Scene.prototype.getCameraByID = function (id) {
  7645. for (var index = 0; index < this.cameras.length; index++) {
  7646. if (this.cameras[index].id === id) {
  7647. return this.cameras[index];
  7648. }
  7649. }
  7650. return null;
  7651. };
  7652. Scene.prototype.getCameraByName = function (name) {
  7653. for (var index = 0; index < this.cameras.length; index++) {
  7654. if (this.cameras[index].name === name) {
  7655. return this.cameras[index];
  7656. }
  7657. }
  7658. return null;
  7659. };
  7660. Scene.prototype.getLightByName = function (name) {
  7661. for (var index = 0; index < this.lights.length; index++) {
  7662. if (this.lights[index].name === name) {
  7663. return this.lights[index];
  7664. }
  7665. }
  7666. return null;
  7667. };
  7668. Scene.prototype.getLightByID = function (id) {
  7669. for (var index = 0; index < this.lights.length; index++) {
  7670. if (this.lights[index].id === id) {
  7671. return this.lights[index];
  7672. }
  7673. }
  7674. return null;
  7675. };
  7676. Scene.prototype.getGeometryByID = function (id) {
  7677. for (var index = 0; index < this._geometries.length; index++) {
  7678. if (this._geometries[index].id === id) {
  7679. return this._geometries[index];
  7680. }
  7681. }
  7682. return null;
  7683. };
  7684. Scene.prototype.pushGeometry = function (geometry, force) {
  7685. if (!force && this.getGeometryByID(geometry.id)) {
  7686. return false;
  7687. }
  7688. this._geometries.push(geometry);
  7689. return true;
  7690. };
  7691. Scene.prototype.getGeometries = function () {
  7692. return this._geometries;
  7693. };
  7694. Scene.prototype.getMeshByID = function (id) {
  7695. for (var index = 0; index < this.meshes.length; index++) {
  7696. if (this.meshes[index].id === id) {
  7697. return this.meshes[index];
  7698. }
  7699. }
  7700. return null;
  7701. };
  7702. Scene.prototype.getLastMeshByID = function (id) {
  7703. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7704. if (this.meshes[index].id === id) {
  7705. return this.meshes[index];
  7706. }
  7707. }
  7708. return null;
  7709. };
  7710. Scene.prototype.getLastEntryByID = function (id) {
  7711. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7712. if (this.meshes[index].id === id) {
  7713. return this.meshes[index];
  7714. }
  7715. }
  7716. for (index = this.cameras.length - 1; index >= 0; index--) {
  7717. if (this.cameras[index].id === id) {
  7718. return this.cameras[index];
  7719. }
  7720. }
  7721. for (index = this.lights.length - 1; index >= 0; index--) {
  7722. if (this.lights[index].id === id) {
  7723. return this.lights[index];
  7724. }
  7725. }
  7726. return null;
  7727. };
  7728. Scene.prototype.getNodeByName = function (name) {
  7729. var mesh = this.getMeshByName(name);
  7730. if (mesh) {
  7731. return mesh;
  7732. }
  7733. var light = this.getLightByName(name);
  7734. if (light) {
  7735. return light;
  7736. }
  7737. return this.getCameraByName(name);
  7738. };
  7739. Scene.prototype.getMeshByName = function (name) {
  7740. for (var index = 0; index < this.meshes.length; index++) {
  7741. if (this.meshes[index].name === name) {
  7742. return this.meshes[index];
  7743. }
  7744. }
  7745. return null;
  7746. };
  7747. Scene.prototype.getLastSkeletonByID = function (id) {
  7748. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7749. if (this.skeletons[index].id === id) {
  7750. return this.skeletons[index];
  7751. }
  7752. }
  7753. return null;
  7754. };
  7755. Scene.prototype.getSkeletonById = function (id) {
  7756. for (var index = 0; index < this.skeletons.length; index++) {
  7757. if (this.skeletons[index].id === id) {
  7758. return this.skeletons[index];
  7759. }
  7760. }
  7761. return null;
  7762. };
  7763. Scene.prototype.getSkeletonByName = function (name) {
  7764. for (var index = 0; index < this.skeletons.length; index++) {
  7765. if (this.skeletons[index].name === name) {
  7766. return this.skeletons[index];
  7767. }
  7768. }
  7769. return null;
  7770. };
  7771. Scene.prototype.isActiveMesh = function (mesh) {
  7772. return (this._activeMeshes.indexOf(mesh) !== -1);
  7773. };
  7774. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7775. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7776. var material = subMesh.getMaterial();
  7777. if (mesh.showSubMeshesBoundingBox) {
  7778. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7779. }
  7780. if (material) {
  7781. // Render targets
  7782. if (material.getRenderTargetTextures) {
  7783. if (this._processedMaterials.indexOf(material) === -1) {
  7784. this._processedMaterials.push(material);
  7785. this._renderTargets.concat(material.getRenderTargetTextures());
  7786. }
  7787. }
  7788. // Dispatch
  7789. this._activeVertices += subMesh.indexCount;
  7790. this._renderingManager.dispatch(subMesh);
  7791. }
  7792. }
  7793. };
  7794. Scene.prototype._evaluateActiveMeshes = function () {
  7795. this._activeMeshes.reset();
  7796. this._renderingManager.reset();
  7797. this._processedMaterials.reset();
  7798. this._activeParticleSystems.reset();
  7799. this._activeSkeletons.reset();
  7800. this._boundingBoxRenderer.reset();
  7801. if (!this._frustumPlanes) {
  7802. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7803. } else {
  7804. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7805. }
  7806. // Meshes
  7807. var meshes;
  7808. var len;
  7809. if (this._selectionOctree) {
  7810. var selection = this._selectionOctree.select(this._frustumPlanes);
  7811. meshes = selection.data;
  7812. len = selection.length;
  7813. } else {
  7814. len = this.meshes.length;
  7815. meshes = this.meshes;
  7816. }
  7817. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7818. var mesh = meshes[meshIndex];
  7819. if (mesh.isBlocked) {
  7820. continue;
  7821. }
  7822. this._totalVertices += mesh.getTotalVertices();
  7823. if (!mesh.isReady()) {
  7824. continue;
  7825. }
  7826. mesh.computeWorldMatrix();
  7827. // Intersections
  7828. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7829. this._meshesForIntersections.pushNoDuplicate(mesh);
  7830. }
  7831. // Switch to current LOD
  7832. var meshLOD = mesh.getLOD(this.activeCamera);
  7833. if (!meshLOD) {
  7834. continue;
  7835. }
  7836. mesh._preActivate();
  7837. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7838. this._activeMeshes.push(mesh);
  7839. mesh._activate(this._renderId);
  7840. this._activeMesh(meshLOD);
  7841. }
  7842. }
  7843. // Particle systems
  7844. var beforeParticlesDate = BABYLON.Tools.Now;
  7845. if (this.particlesEnabled) {
  7846. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7847. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7848. var particleSystem = this.particleSystems[particleIndex];
  7849. if (!particleSystem.isStarted()) {
  7850. continue;
  7851. }
  7852. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7853. this._activeParticleSystems.push(particleSystem);
  7854. particleSystem.animate();
  7855. }
  7856. }
  7857. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7858. }
  7859. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7860. };
  7861. Scene.prototype._activeMesh = function (mesh) {
  7862. if (mesh.skeleton && this.skeletonsEnabled) {
  7863. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7864. }
  7865. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7866. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7867. }
  7868. if (mesh && mesh.subMeshes) {
  7869. // Submeshes Octrees
  7870. var len;
  7871. var subMeshes;
  7872. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7873. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7874. len = intersections.length;
  7875. subMeshes = intersections.data;
  7876. } else {
  7877. subMeshes = mesh.subMeshes;
  7878. len = subMeshes.length;
  7879. }
  7880. for (var subIndex = 0; subIndex < len; subIndex++) {
  7881. var subMesh = subMeshes[subIndex];
  7882. this._evaluateSubMesh(subMesh, mesh);
  7883. }
  7884. }
  7885. };
  7886. Scene.prototype.updateTransformMatrix = function (force) {
  7887. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7888. };
  7889. Scene.prototype._renderForCamera = function (camera) {
  7890. var engine = this._engine;
  7891. this.activeCamera = camera;
  7892. if (!this.activeCamera)
  7893. throw new Error("Active camera not set");
  7894. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7895. // Viewport
  7896. engine.setViewport(this.activeCamera.viewport);
  7897. // Camera
  7898. this._renderId++;
  7899. this.updateTransformMatrix();
  7900. if (this.beforeCameraRender) {
  7901. this.beforeCameraRender(this.activeCamera);
  7902. }
  7903. // Meshes
  7904. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7905. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7906. this._evaluateActiveMeshes();
  7907. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7908. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7909. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7910. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7911. skeleton.prepare();
  7912. this._activeBones += skeleton.bones.length;
  7913. }
  7914. // Render targets
  7915. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7916. if (this.renderTargetsEnabled) {
  7917. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7918. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7919. var renderTarget = this._renderTargets.data[renderIndex];
  7920. if (renderTarget._shouldRender()) {
  7921. this._renderId++;
  7922. renderTarget.render();
  7923. }
  7924. }
  7925. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7926. this._renderId++;
  7927. }
  7928. if (this._renderTargets.length > 0) {
  7929. engine.restoreDefaultFramebuffer();
  7930. }
  7931. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  7932. // Prepare Frame
  7933. this.postProcessManager._prepareFrame();
  7934. var beforeRenderDate = BABYLON.Tools.Now;
  7935. // Backgrounds
  7936. if (this.layers.length) {
  7937. engine.setDepthBuffer(false);
  7938. var layerIndex;
  7939. var layer;
  7940. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7941. layer = this.layers[layerIndex];
  7942. if (layer.isBackground) {
  7943. layer.render();
  7944. }
  7945. }
  7946. engine.setDepthBuffer(true);
  7947. }
  7948. // Render
  7949. BABYLON.Tools.StartPerformanceCounter("Main render");
  7950. this._renderingManager.render(null, null, true, true);
  7951. BABYLON.Tools.EndPerformanceCounter("Main render");
  7952. // Bounding boxes
  7953. this._boundingBoxRenderer.render();
  7954. // Lens flares
  7955. if (this.lensFlaresEnabled) {
  7956. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7957. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  7958. this.lensFlareSystems[lensFlareSystemIndex].render();
  7959. }
  7960. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  7961. }
  7962. // Foregrounds
  7963. if (this.layers.length) {
  7964. engine.setDepthBuffer(false);
  7965. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  7966. layer = this.layers[layerIndex];
  7967. if (!layer.isBackground) {
  7968. layer.render();
  7969. }
  7970. }
  7971. engine.setDepthBuffer(true);
  7972. }
  7973. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  7974. // Finalize frame
  7975. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  7976. // Update camera
  7977. this.activeCamera._updateFromScene();
  7978. // Reset some special arrays
  7979. this._renderTargets.reset();
  7980. if (this.afterCameraRender) {
  7981. this.afterCameraRender(this.activeCamera);
  7982. }
  7983. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7984. };
  7985. Scene.prototype._processSubCameras = function (camera) {
  7986. if (camera.subCameras.length === 0) {
  7987. this._renderForCamera(camera);
  7988. return;
  7989. }
  7990. for (var index = 0; index < camera.subCameras.length; index++) {
  7991. this._renderForCamera(camera.subCameras[index]);
  7992. }
  7993. this.activeCamera = camera;
  7994. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  7995. // Update camera
  7996. this.activeCamera._updateFromScene();
  7997. };
  7998. Scene.prototype._checkIntersections = function () {
  7999. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8000. var sourceMesh = this._meshesForIntersections.data[index];
  8001. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8002. var action = sourceMesh.actionManager.actions[actionIndex];
  8003. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8004. var otherMesh = action.getTriggerParameter();
  8005. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8006. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8007. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8008. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8009. sourceMesh._intersectionsInProgress.push(otherMesh);
  8010. } else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8011. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8012. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8013. if (indexOfOther > -1) {
  8014. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8015. }
  8016. }
  8017. }
  8018. }
  8019. }
  8020. };
  8021. Scene.prototype.render = function () {
  8022. var startDate = BABYLON.Tools.Now;
  8023. this._particlesDuration = 0;
  8024. this._spritesDuration = 0;
  8025. this._activeParticles = 0;
  8026. this._renderDuration = 0;
  8027. this._renderTargetsDuration = 0;
  8028. this._evaluateActiveMeshesDuration = 0;
  8029. this._totalVertices = 0;
  8030. this._activeVertices = 0;
  8031. this._activeBones = 0;
  8032. this.getEngine().resetDrawCalls();
  8033. this._meshesForIntersections.reset();
  8034. this.resetCachedMaterial();
  8035. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8036. // Actions
  8037. if (this.actionManager) {
  8038. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8039. }
  8040. // Before render
  8041. if (this.beforeRender) {
  8042. this.beforeRender();
  8043. }
  8044. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8045. this._onBeforeRenderCallbacks[callbackIndex]();
  8046. }
  8047. // Animations
  8048. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8049. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8050. this._animate();
  8051. // Physics
  8052. if (this._physicsEngine) {
  8053. BABYLON.Tools.StartPerformanceCounter("Physics");
  8054. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8055. BABYLON.Tools.EndPerformanceCounter("Physics");
  8056. }
  8057. // Customs render targets
  8058. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8059. var engine = this.getEngine();
  8060. if (this.renderTargetsEnabled) {
  8061. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8062. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8063. var renderTarget = this.customRenderTargets[customIndex];
  8064. if (renderTarget._shouldRender()) {
  8065. this._renderId++;
  8066. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8067. if (!this.activeCamera)
  8068. throw new Error("Active camera not set");
  8069. // Viewport
  8070. engine.setViewport(this.activeCamera.viewport);
  8071. // Camera
  8072. this.updateTransformMatrix();
  8073. renderTarget.render();
  8074. }
  8075. }
  8076. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8077. this._renderId++;
  8078. }
  8079. if (this.customRenderTargets.length > 0) {
  8080. engine.restoreDefaultFramebuffer();
  8081. }
  8082. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8083. // Procedural textures
  8084. if (this.proceduralTexturesEnabled) {
  8085. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8086. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8087. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8088. if (proceduralTexture._shouldRender()) {
  8089. proceduralTexture.render();
  8090. }
  8091. }
  8092. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8093. }
  8094. // Clear
  8095. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8096. // Shadows
  8097. if (this.shadowsEnabled) {
  8098. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8099. var light = this.lights[lightIndex];
  8100. var shadowGenerator = light.getShadowGenerator();
  8101. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8102. this._renderTargets.push(shadowGenerator.getShadowMap());
  8103. }
  8104. }
  8105. }
  8106. // RenderPipeline
  8107. this.postProcessRenderPipelineManager.update();
  8108. // Multi-cameras?
  8109. if (this.activeCameras.length > 0) {
  8110. var currentRenderId = this._renderId;
  8111. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8112. this._renderId = currentRenderId;
  8113. this._processSubCameras(this.activeCameras[cameraIndex]);
  8114. }
  8115. } else {
  8116. if (!this.activeCamera) {
  8117. throw new Error("No camera defined");
  8118. }
  8119. this._processSubCameras(this.activeCamera);
  8120. }
  8121. // Intersection checks
  8122. this._checkIntersections();
  8123. // Update the audio listener attached to the camera
  8124. this._updateAudioParameters();
  8125. // After render
  8126. if (this.afterRender) {
  8127. this.afterRender();
  8128. }
  8129. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8130. this._onAfterRenderCallbacks[callbackIndex]();
  8131. }
  8132. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8133. this._toBeDisposed.data[index].dispose();
  8134. this._toBeDisposed[index] = null;
  8135. }
  8136. this._toBeDisposed.reset();
  8137. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8138. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8139. };
  8140. Scene.prototype._updateAudioParameters = function () {
  8141. var listeningCamera;
  8142. var audioEngine = this._engine.getAudioEngine();
  8143. if (this.activeCameras.length > 0) {
  8144. listeningCamera = this.activeCameras[0];
  8145. } else {
  8146. listeningCamera = this.activeCamera;
  8147. }
  8148. if (listeningCamera && audioEngine.canUseWebAudio) {
  8149. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8150. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8151. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8152. cameraDirection.normalize();
  8153. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8154. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8155. var sound = this.mainSoundTrack.soundCollection[i];
  8156. if (sound.useCustomAttenuation) {
  8157. sound.updateDistanceFromListener();
  8158. }
  8159. }
  8160. for (var i = 0; i < this.soundTracks.length; i++) {
  8161. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8162. var sound = this.soundTracks[i].soundCollection[j];
  8163. if (sound.useCustomAttenuation) {
  8164. sound.updateDistanceFromListener();
  8165. }
  8166. }
  8167. }
  8168. }
  8169. };
  8170. Scene.prototype.dispose = function () {
  8171. this.beforeRender = null;
  8172. this.afterRender = null;
  8173. this.skeletons = [];
  8174. this._boundingBoxRenderer.dispose();
  8175. // Debug layer
  8176. this.debugLayer.hide();
  8177. // Events
  8178. if (this.onDispose) {
  8179. this.onDispose();
  8180. }
  8181. this._onBeforeRenderCallbacks = [];
  8182. this._onAfterRenderCallbacks = [];
  8183. this.detachControl();
  8184. // Detach cameras
  8185. var canvas = this._engine.getRenderingCanvas();
  8186. var index;
  8187. for (index = 0; index < this.cameras.length; index++) {
  8188. this.cameras[index].detachControl(canvas);
  8189. }
  8190. while (this.lights.length) {
  8191. this.lights[0].dispose();
  8192. }
  8193. while (this.meshes.length) {
  8194. this.meshes[0].dispose(true);
  8195. }
  8196. while (this.cameras.length) {
  8197. this.cameras[0].dispose();
  8198. }
  8199. while (this.materials.length) {
  8200. this.materials[0].dispose();
  8201. }
  8202. while (this.particleSystems.length) {
  8203. this.particleSystems[0].dispose();
  8204. }
  8205. while (this.spriteManagers.length) {
  8206. this.spriteManagers[0].dispose();
  8207. }
  8208. while (this.layers.length) {
  8209. this.layers[0].dispose();
  8210. }
  8211. while (this.textures.length) {
  8212. this.textures[0].dispose();
  8213. }
  8214. // Post-processes
  8215. this.postProcessManager.dispose();
  8216. // Physics
  8217. if (this._physicsEngine) {
  8218. this.disablePhysicsEngine();
  8219. }
  8220. // Remove from engine
  8221. index = this._engine.scenes.indexOf(this);
  8222. if (index > -1) {
  8223. this._engine.scenes.splice(index, 1);
  8224. }
  8225. this._engine.wipeCaches();
  8226. };
  8227. // Collisions
  8228. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8229. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8230. position.divideToRef(collider.radius, this._scaledPosition);
  8231. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8232. collider.retry = 0;
  8233. collider.initialVelocity = this._scaledVelocity;
  8234. collider.initialPosition = this._scaledPosition;
  8235. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8236. finalPosition.multiplyInPlace(collider.radius);
  8237. };
  8238. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8239. if (typeof excludedMesh === "undefined") { excludedMesh = null; }
  8240. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8241. if (collider.retry >= maximumRetry) {
  8242. finalPosition.copyFrom(position);
  8243. return;
  8244. }
  8245. collider._initialize(position, velocity, closeDistance);
  8246. for (var index = 0; index < this.meshes.length; index++) {
  8247. var mesh = this.meshes[index];
  8248. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8249. mesh._checkCollision(collider);
  8250. }
  8251. }
  8252. if (!collider.collisionFound) {
  8253. position.addToRef(velocity, finalPosition);
  8254. return;
  8255. }
  8256. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8257. collider._getResponse(position, velocity);
  8258. }
  8259. if (velocity.length() <= closeDistance) {
  8260. finalPosition.copyFrom(position);
  8261. return;
  8262. }
  8263. collider.retry++;
  8264. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8265. };
  8266. // Octrees
  8267. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8268. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  8269. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  8270. if (!this._selectionOctree) {
  8271. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8272. }
  8273. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8274. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8275. for (var index = 0; index < this.meshes.length; index++) {
  8276. var mesh = this.meshes[index];
  8277. mesh.computeWorldMatrix(true);
  8278. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8279. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8280. BABYLON.Tools.CheckExtends(minBox, min, max);
  8281. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8282. }
  8283. // Update octree
  8284. this._selectionOctree.update(min, max, this.meshes);
  8285. return this._selectionOctree;
  8286. };
  8287. // Picking
  8288. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8289. var engine = this._engine;
  8290. if (!camera) {
  8291. if (!this.activeCamera)
  8292. throw new Error("Active camera not set");
  8293. camera = this.activeCamera;
  8294. }
  8295. var cameraViewport = camera.viewport;
  8296. var viewport = cameraViewport.toGlobal(engine);
  8297. // Moving coordinates to local viewport world
  8298. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8299. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8300. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8301. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8302. };
  8303. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8304. var pickingInfo = null;
  8305. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8306. var mesh = this.meshes[meshIndex];
  8307. if (predicate) {
  8308. if (!predicate(mesh)) {
  8309. continue;
  8310. }
  8311. } else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8312. continue;
  8313. }
  8314. var world = mesh.getWorldMatrix();
  8315. var ray = rayFunction(world);
  8316. var result = mesh.intersects(ray, fastCheck);
  8317. if (!result || !result.hit)
  8318. continue;
  8319. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8320. continue;
  8321. pickingInfo = result;
  8322. if (fastCheck) {
  8323. break;
  8324. }
  8325. }
  8326. return pickingInfo || new BABYLON.PickingInfo();
  8327. };
  8328. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8329. var _this = this;
  8330. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8331. /// <param name="x">X position on screen</param>
  8332. /// <param name="y">Y position on screen</param>
  8333. /// <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>
  8334. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8335. /// <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>
  8336. return this._internalPick(function (world) {
  8337. return _this.createPickingRay(x, y, world, camera);
  8338. }, predicate, fastCheck);
  8339. };
  8340. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8341. var _this = this;
  8342. return this._internalPick(function (world) {
  8343. if (!_this._pickWithRayInverseMatrix) {
  8344. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8345. }
  8346. world.invertToRef(_this._pickWithRayInverseMatrix);
  8347. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8348. }, predicate, fastCheck);
  8349. };
  8350. Scene.prototype.setPointerOverMesh = function (mesh) {
  8351. if (this._pointerOverMesh === mesh) {
  8352. return;
  8353. }
  8354. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8355. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8356. }
  8357. this._pointerOverMesh = mesh;
  8358. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8359. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8360. }
  8361. };
  8362. Scene.prototype.getPointerOverMesh = function () {
  8363. return this._pointerOverMesh;
  8364. };
  8365. // Physics
  8366. Scene.prototype.getPhysicsEngine = function () {
  8367. return this._physicsEngine;
  8368. };
  8369. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8370. if (this._physicsEngine) {
  8371. return true;
  8372. }
  8373. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8374. if (!this._physicsEngine.isSupported()) {
  8375. this._physicsEngine = null;
  8376. return false;
  8377. }
  8378. this._physicsEngine._initialize(gravity);
  8379. return true;
  8380. };
  8381. Scene.prototype.disablePhysicsEngine = function () {
  8382. if (!this._physicsEngine) {
  8383. return;
  8384. }
  8385. this._physicsEngine.dispose();
  8386. this._physicsEngine = undefined;
  8387. };
  8388. Scene.prototype.isPhysicsEnabled = function () {
  8389. return this._physicsEngine !== undefined;
  8390. };
  8391. Scene.prototype.setGravity = function (gravity) {
  8392. if (!this._physicsEngine) {
  8393. return;
  8394. }
  8395. this._physicsEngine._setGravity(gravity);
  8396. };
  8397. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8398. if (parts.parts) {
  8399. options = parts;
  8400. parts = parts.parts;
  8401. }
  8402. if (!this._physicsEngine) {
  8403. return null;
  8404. }
  8405. for (var index = 0; index < parts.length; index++) {
  8406. var mesh = parts[index].mesh;
  8407. mesh._physicImpostor = parts[index].impostor;
  8408. mesh._physicsMass = options.mass / parts.length;
  8409. mesh._physicsFriction = options.friction;
  8410. mesh._physicRestitution = options.restitution;
  8411. }
  8412. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8413. };
  8414. //ANY
  8415. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8416. for (var index = 0; index < compound.parts.length; index++) {
  8417. var mesh = compound.parts[index].mesh;
  8418. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8419. this._physicsEngine._unregisterMesh(mesh);
  8420. }
  8421. };
  8422. // Tags
  8423. Scene.prototype._getByTags = function (list, tagsQuery) {
  8424. if (tagsQuery === undefined) {
  8425. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8426. return list;
  8427. }
  8428. var listByTags = [];
  8429. for (var i in list) {
  8430. var item = list[i];
  8431. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8432. listByTags.push(item);
  8433. }
  8434. }
  8435. return listByTags;
  8436. };
  8437. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8438. return this._getByTags(this.meshes, tagsQuery);
  8439. };
  8440. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8441. return this._getByTags(this.cameras, tagsQuery);
  8442. };
  8443. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8444. return this._getByTags(this.lights, tagsQuery);
  8445. };
  8446. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8447. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8448. };
  8449. Scene.FOGMODE_NONE = 0;
  8450. Scene.FOGMODE_EXP = 1;
  8451. Scene.FOGMODE_EXP2 = 2;
  8452. Scene.FOGMODE_LINEAR = 3;
  8453. Scene.MinDeltaTime = 1.0;
  8454. Scene.MaxDeltaTime = 1000.0;
  8455. return Scene;
  8456. })();
  8457. BABYLON.Scene = Scene;
  8458. })(BABYLON || (BABYLON = {}));
  8459. //# sourceMappingURL=babylon.scene.js.map
  8460. var BABYLON;
  8461. (function (BABYLON) {
  8462. var VertexBuffer = (function () {
  8463. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8464. if (engine instanceof BABYLON.Mesh) {
  8465. this._engine = engine.getScene().getEngine();
  8466. } else {
  8467. this._engine = engine;
  8468. }
  8469. this._updatable = updatable;
  8470. this._data = data;
  8471. if (!postponeInternalCreation) {
  8472. this.create();
  8473. }
  8474. this._kind = kind;
  8475. if (stride) {
  8476. this._strideSize = stride;
  8477. return;
  8478. }
  8479. switch (kind) {
  8480. case VertexBuffer.PositionKind:
  8481. this._strideSize = 3;
  8482. break;
  8483. case VertexBuffer.NormalKind:
  8484. this._strideSize = 3;
  8485. break;
  8486. case VertexBuffer.UVKind:
  8487. this._strideSize = 2;
  8488. break;
  8489. case VertexBuffer.UV2Kind:
  8490. this._strideSize = 2;
  8491. break;
  8492. case VertexBuffer.ColorKind:
  8493. this._strideSize = 4;
  8494. break;
  8495. case VertexBuffer.MatricesIndicesKind:
  8496. this._strideSize = 4;
  8497. break;
  8498. case VertexBuffer.MatricesWeightsKind:
  8499. this._strideSize = 4;
  8500. break;
  8501. }
  8502. }
  8503. // Properties
  8504. VertexBuffer.prototype.isUpdatable = function () {
  8505. return this._updatable;
  8506. };
  8507. VertexBuffer.prototype.getData = function () {
  8508. return this._data;
  8509. };
  8510. VertexBuffer.prototype.getBuffer = function () {
  8511. return this._buffer;
  8512. };
  8513. VertexBuffer.prototype.getStrideSize = function () {
  8514. return this._strideSize;
  8515. };
  8516. // Methods
  8517. VertexBuffer.prototype.create = function (data) {
  8518. if (!data && this._buffer) {
  8519. return;
  8520. }
  8521. data = data || this._data;
  8522. if (!this._buffer) {
  8523. if (this._updatable) {
  8524. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8525. } else {
  8526. this._buffer = this._engine.createVertexBuffer(data);
  8527. }
  8528. }
  8529. if (this._updatable) {
  8530. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8531. this._data = data;
  8532. }
  8533. };
  8534. VertexBuffer.prototype.update = function (data) {
  8535. this.create(data);
  8536. };
  8537. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8538. if (!this._buffer) {
  8539. return;
  8540. }
  8541. if (this._updatable) {
  8542. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8543. this._data = null;
  8544. }
  8545. };
  8546. VertexBuffer.prototype.dispose = function () {
  8547. if (!this._buffer) {
  8548. return;
  8549. }
  8550. if (this._engine._releaseBuffer(this._buffer)) {
  8551. this._buffer = null;
  8552. }
  8553. };
  8554. Object.defineProperty(VertexBuffer, "PositionKind", {
  8555. get: function () {
  8556. return VertexBuffer._PositionKind;
  8557. },
  8558. enumerable: true,
  8559. configurable: true
  8560. });
  8561. Object.defineProperty(VertexBuffer, "NormalKind", {
  8562. get: function () {
  8563. return VertexBuffer._NormalKind;
  8564. },
  8565. enumerable: true,
  8566. configurable: true
  8567. });
  8568. Object.defineProperty(VertexBuffer, "UVKind", {
  8569. get: function () {
  8570. return VertexBuffer._UVKind;
  8571. },
  8572. enumerable: true,
  8573. configurable: true
  8574. });
  8575. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8576. get: function () {
  8577. return VertexBuffer._UV2Kind;
  8578. },
  8579. enumerable: true,
  8580. configurable: true
  8581. });
  8582. Object.defineProperty(VertexBuffer, "ColorKind", {
  8583. get: function () {
  8584. return VertexBuffer._ColorKind;
  8585. },
  8586. enumerable: true,
  8587. configurable: true
  8588. });
  8589. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8590. get: function () {
  8591. return VertexBuffer._MatricesIndicesKind;
  8592. },
  8593. enumerable: true,
  8594. configurable: true
  8595. });
  8596. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8597. get: function () {
  8598. return VertexBuffer._MatricesWeightsKind;
  8599. },
  8600. enumerable: true,
  8601. configurable: true
  8602. });
  8603. VertexBuffer._PositionKind = "position";
  8604. VertexBuffer._NormalKind = "normal";
  8605. VertexBuffer._UVKind = "uv";
  8606. VertexBuffer._UV2Kind = "uv2";
  8607. VertexBuffer._ColorKind = "color";
  8608. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8609. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8610. return VertexBuffer;
  8611. })();
  8612. BABYLON.VertexBuffer = VertexBuffer;
  8613. })(BABYLON || (BABYLON = {}));
  8614. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8615. var BABYLON;
  8616. (function (BABYLON) {
  8617. var AbstractMesh = (function (_super) {
  8618. __extends(AbstractMesh, _super);
  8619. function AbstractMesh(name, scene) {
  8620. _super.call(this, name, scene);
  8621. // Properties
  8622. this.position = new BABYLON.Vector3(0, 0, 0);
  8623. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8624. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8625. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8626. this.visibility = 1.0;
  8627. this.alphaIndex = Number.MAX_VALUE;
  8628. this.infiniteDistance = false;
  8629. this.isVisible = true;
  8630. this.isPickable = true;
  8631. this.showBoundingBox = false;
  8632. this.showSubMeshesBoundingBox = false;
  8633. this.onDispose = null;
  8634. this.checkCollisions = false;
  8635. this.isBlocker = false;
  8636. this.renderingGroupId = 0;
  8637. this.receiveShadows = false;
  8638. this.renderOutline = false;
  8639. this.outlineColor = BABYLON.Color3.Red();
  8640. this.outlineWidth = 0.02;
  8641. this.renderOverlay = false;
  8642. this.overlayColor = BABYLON.Color3.Red();
  8643. this.overlayAlpha = 0.5;
  8644. this.hasVertexAlpha = false;
  8645. this.useVertexColors = true;
  8646. this.applyFog = true;
  8647. this.useOctreeForRenderingSelection = true;
  8648. this.useOctreeForPicking = true;
  8649. this.useOctreeForCollisions = true;
  8650. this.layerMask = 0xFFFFFFFF;
  8651. // Physics
  8652. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8653. // Collisions
  8654. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8655. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8656. this._collider = new BABYLON.Collider();
  8657. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8658. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8659. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8660. // Cache
  8661. this._localScaling = BABYLON.Matrix.Zero();
  8662. this._localRotation = BABYLON.Matrix.Zero();
  8663. this._localTranslation = BABYLON.Matrix.Zero();
  8664. this._localBillboard = BABYLON.Matrix.Zero();
  8665. this._localPivotScaling = BABYLON.Matrix.Zero();
  8666. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8667. this._localWorld = BABYLON.Matrix.Zero();
  8668. this._worldMatrix = BABYLON.Matrix.Zero();
  8669. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8670. this._absolutePosition = BABYLON.Vector3.Zero();
  8671. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8672. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8673. this._isDirty = false;
  8674. this._pivotMatrix = BABYLON.Matrix.Identity();
  8675. this._isDisposed = false;
  8676. this._renderId = 0;
  8677. this._intersectionsInProgress = new Array();
  8678. this._onAfterWorldMatrixUpdate = new Array();
  8679. scene.meshes.push(this);
  8680. }
  8681. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8682. get: function () {
  8683. return AbstractMesh._BILLBOARDMODE_NONE;
  8684. },
  8685. enumerable: true,
  8686. configurable: true
  8687. });
  8688. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8689. get: function () {
  8690. return AbstractMesh._BILLBOARDMODE_X;
  8691. },
  8692. enumerable: true,
  8693. configurable: true
  8694. });
  8695. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8696. get: function () {
  8697. return AbstractMesh._BILLBOARDMODE_Y;
  8698. },
  8699. enumerable: true,
  8700. configurable: true
  8701. });
  8702. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8703. get: function () {
  8704. return AbstractMesh._BILLBOARDMODE_Z;
  8705. },
  8706. enumerable: true,
  8707. configurable: true
  8708. });
  8709. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8710. get: function () {
  8711. return AbstractMesh._BILLBOARDMODE_ALL;
  8712. },
  8713. enumerable: true,
  8714. configurable: true
  8715. });
  8716. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8717. // Methods
  8718. get: function () {
  8719. return false;
  8720. },
  8721. enumerable: true,
  8722. configurable: true
  8723. });
  8724. AbstractMesh.prototype.getLOD = function (camera) {
  8725. return this;
  8726. };
  8727. AbstractMesh.prototype.getTotalVertices = function () {
  8728. return 0;
  8729. };
  8730. AbstractMesh.prototype.getIndices = function () {
  8731. return null;
  8732. };
  8733. AbstractMesh.prototype.getVerticesData = function (kind) {
  8734. return null;
  8735. };
  8736. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8737. return false;
  8738. };
  8739. AbstractMesh.prototype.getBoundingInfo = function () {
  8740. if (this._masterMesh) {
  8741. return this._masterMesh.getBoundingInfo();
  8742. }
  8743. if (!this._boundingInfo) {
  8744. this._updateBoundingInfo();
  8745. }
  8746. return this._boundingInfo;
  8747. };
  8748. AbstractMesh.prototype._preActivate = function () {
  8749. };
  8750. AbstractMesh.prototype._activate = function (renderId) {
  8751. this._renderId = renderId;
  8752. };
  8753. AbstractMesh.prototype.getWorldMatrix = function () {
  8754. if (this._masterMesh) {
  8755. return this._masterMesh.getWorldMatrix();
  8756. }
  8757. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8758. this.computeWorldMatrix();
  8759. }
  8760. return this._worldMatrix;
  8761. };
  8762. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8763. get: function () {
  8764. return this._worldMatrix;
  8765. },
  8766. enumerable: true,
  8767. configurable: true
  8768. });
  8769. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8770. get: function () {
  8771. return this._absolutePosition;
  8772. },
  8773. enumerable: true,
  8774. configurable: true
  8775. });
  8776. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8777. if (!this.rotationQuaternion) {
  8778. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8779. this.rotation = BABYLON.Vector3.Zero();
  8780. }
  8781. if (!space || space == 0 /* LOCAL */) {
  8782. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8783. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8784. } else {
  8785. if (this.parent) {
  8786. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8787. invertParentWorldMatrix.invert();
  8788. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8789. }
  8790. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8791. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8792. }
  8793. };
  8794. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8795. var displacementVector = axis.scale(distance);
  8796. if (!space || space == 0 /* LOCAL */) {
  8797. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8798. this.setPositionWithLocalVector(tempV3);
  8799. } else {
  8800. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8801. }
  8802. };
  8803. AbstractMesh.prototype.getAbsolutePosition = function () {
  8804. this.computeWorldMatrix();
  8805. return this._absolutePosition;
  8806. };
  8807. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8808. if (!absolutePosition) {
  8809. return;
  8810. }
  8811. var absolutePositionX;
  8812. var absolutePositionY;
  8813. var absolutePositionZ;
  8814. if (absolutePosition.x === undefined) {
  8815. if (arguments.length < 3) {
  8816. return;
  8817. }
  8818. absolutePositionX = arguments[0];
  8819. absolutePositionY = arguments[1];
  8820. absolutePositionZ = arguments[2];
  8821. } else {
  8822. absolutePositionX = absolutePosition.x;
  8823. absolutePositionY = absolutePosition.y;
  8824. absolutePositionZ = absolutePosition.z;
  8825. }
  8826. if (this.parent) {
  8827. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8828. invertParentWorldMatrix.invert();
  8829. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8830. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8831. } else {
  8832. this.position.x = absolutePositionX;
  8833. this.position.y = absolutePositionY;
  8834. this.position.z = absolutePositionZ;
  8835. }
  8836. };
  8837. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8838. this._pivotMatrix = matrix;
  8839. this._cache.pivotMatrixUpdated = true;
  8840. };
  8841. AbstractMesh.prototype.getPivotMatrix = function () {
  8842. return this._pivotMatrix;
  8843. };
  8844. AbstractMesh.prototype._isSynchronized = function () {
  8845. if (this._isDirty) {
  8846. return false;
  8847. }
  8848. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8849. return false;
  8850. if (this._cache.pivotMatrixUpdated) {
  8851. return false;
  8852. }
  8853. if (this.infiniteDistance) {
  8854. return false;
  8855. }
  8856. if (!this._cache.position.equals(this.position))
  8857. return false;
  8858. if (this.rotationQuaternion) {
  8859. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8860. return false;
  8861. } else {
  8862. if (!this._cache.rotation.equals(this.rotation))
  8863. return false;
  8864. }
  8865. if (!this._cache.scaling.equals(this.scaling))
  8866. return false;
  8867. return true;
  8868. };
  8869. AbstractMesh.prototype._initCache = function () {
  8870. _super.prototype._initCache.call(this);
  8871. this._cache.localMatrixUpdated = false;
  8872. this._cache.position = BABYLON.Vector3.Zero();
  8873. this._cache.scaling = BABYLON.Vector3.Zero();
  8874. this._cache.rotation = BABYLON.Vector3.Zero();
  8875. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8876. };
  8877. AbstractMesh.prototype.markAsDirty = function (property) {
  8878. if (property === "rotation") {
  8879. this.rotationQuaternion = null;
  8880. }
  8881. this._currentRenderId = Number.MAX_VALUE;
  8882. this._isDirty = true;
  8883. };
  8884. AbstractMesh.prototype._updateBoundingInfo = function () {
  8885. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8886. this._boundingInfo._update(this.worldMatrixFromCache);
  8887. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8888. };
  8889. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8890. if (!this.subMeshes) {
  8891. return;
  8892. }
  8893. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8894. var subMesh = this.subMeshes[subIndex];
  8895. subMesh.updateBoundingInfo(matrix);
  8896. }
  8897. };
  8898. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8899. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8900. return this._worldMatrix;
  8901. }
  8902. this._cache.position.copyFrom(this.position);
  8903. this._cache.scaling.copyFrom(this.scaling);
  8904. this._cache.pivotMatrixUpdated = false;
  8905. this._currentRenderId = this.getScene().getRenderId();
  8906. this._isDirty = false;
  8907. // Scaling
  8908. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8909. // Rotation
  8910. if (this.rotationQuaternion) {
  8911. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  8912. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  8913. } else {
  8914. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  8915. this._cache.rotation.copyFrom(this.rotation);
  8916. }
  8917. // Translation
  8918. if (this.infiniteDistance && !this.parent) {
  8919. var camera = this.getScene().activeCamera;
  8920. var cameraWorldMatrix = camera.getWorldMatrix();
  8921. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  8922. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  8923. } else {
  8924. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  8925. }
  8926. // Composing transformations
  8927. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  8928. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  8929. // Billboarding
  8930. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  8931. var localPosition = this.position.clone();
  8932. var zero = this.getScene().activeCamera.position.clone();
  8933. if (this.parent && this.parent.position) {
  8934. localPosition.addInPlace(this.parent.position);
  8935. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  8936. }
  8937. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  8938. zero = this.getScene().activeCamera.position;
  8939. } else {
  8940. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  8941. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  8942. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  8943. zero.y = localPosition.y + 0.001;
  8944. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  8945. zero.z = localPosition.z + 0.001;
  8946. }
  8947. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  8948. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  8949. this._localBillboard.invert();
  8950. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  8951. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  8952. }
  8953. // Local world
  8954. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  8955. // Parent
  8956. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  8957. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  8958. } else {
  8959. this._worldMatrix.copyFrom(this._localWorld);
  8960. }
  8961. // Bounding info
  8962. this._updateBoundingInfo();
  8963. // Absolute position
  8964. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  8965. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  8966. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  8967. }
  8968. return this._worldMatrix;
  8969. };
  8970. /**
  8971. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  8972. * @param func: callback function to add
  8973. */
  8974. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  8975. this._onAfterWorldMatrixUpdate.push(func);
  8976. };
  8977. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  8978. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  8979. if (index > -1) {
  8980. this._onAfterWorldMatrixUpdate.splice(index, 1);
  8981. }
  8982. };
  8983. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  8984. this.computeWorldMatrix();
  8985. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  8986. };
  8987. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  8988. this.computeWorldMatrix();
  8989. var invLocalWorldMatrix = this._localWorld.clone();
  8990. invLocalWorldMatrix.invert();
  8991. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  8992. };
  8993. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  8994. this.computeWorldMatrix();
  8995. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  8996. };
  8997. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  8998. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  8999. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9000. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9001. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9002. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9003. /// <returns>Mesh oriented towards targetMesh</returns>
  9004. yawCor = yawCor || 0; // default to zero if undefined
  9005. pitchCor = pitchCor || 0;
  9006. rollCor = rollCor || 0;
  9007. var dv = targetPoint.subtract(this.position);
  9008. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9009. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9010. var pitch = Math.atan2(dv.y, len);
  9011. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9012. };
  9013. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9014. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9015. return false;
  9016. }
  9017. return true;
  9018. };
  9019. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9020. if (!camera) {
  9021. camera = this.getScene().activeCamera;
  9022. }
  9023. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9024. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9025. return false;
  9026. }
  9027. return true;
  9028. };
  9029. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9030. if (!this._boundingInfo || !mesh._boundingInfo) {
  9031. return false;
  9032. }
  9033. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9034. };
  9035. AbstractMesh.prototype.intersectsPoint = function (point) {
  9036. if (!this._boundingInfo) {
  9037. return false;
  9038. }
  9039. return this._boundingInfo.intersectsPoint(point);
  9040. };
  9041. // Physics
  9042. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9043. var physicsEngine = this.getScene().getPhysicsEngine();
  9044. if (!physicsEngine) {
  9045. return;
  9046. }
  9047. if (impostor.impostor) {
  9048. // Old API
  9049. options = impostor;
  9050. impostor = impostor.impostor;
  9051. }
  9052. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9053. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9054. physicsEngine._unregisterMesh(this);
  9055. return;
  9056. }
  9057. options.mass = options.mass || 0;
  9058. options.friction = options.friction || 0.2;
  9059. options.restitution = options.restitution || 0.2;
  9060. this._physicImpostor = impostor;
  9061. this._physicsMass = options.mass;
  9062. this._physicsFriction = options.friction;
  9063. this._physicRestitution = options.restitution;
  9064. return physicsEngine._registerMesh(this, impostor, options);
  9065. };
  9066. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9067. if (!this._physicImpostor) {
  9068. return BABYLON.PhysicsEngine.NoImpostor;
  9069. }
  9070. return this._physicImpostor;
  9071. };
  9072. AbstractMesh.prototype.getPhysicsMass = function () {
  9073. if (!this._physicsMass) {
  9074. return 0;
  9075. }
  9076. return this._physicsMass;
  9077. };
  9078. AbstractMesh.prototype.getPhysicsFriction = function () {
  9079. if (!this._physicsFriction) {
  9080. return 0;
  9081. }
  9082. return this._physicsFriction;
  9083. };
  9084. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9085. if (!this._physicRestitution) {
  9086. return 0;
  9087. }
  9088. return this._physicRestitution;
  9089. };
  9090. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9091. if (!camera) {
  9092. camera = this.getScene().activeCamera;
  9093. }
  9094. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9095. };
  9096. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9097. if (!camera) {
  9098. camera = this.getScene().activeCamera;
  9099. }
  9100. return this.absolutePosition.subtract(camera.position).length();
  9101. };
  9102. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9103. if (!this._physicImpostor) {
  9104. return;
  9105. }
  9106. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9107. };
  9108. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9109. if (!this._physicImpostor) {
  9110. return;
  9111. }
  9112. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9113. };
  9114. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9115. if (!this._physicImpostor) {
  9116. return;
  9117. }
  9118. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9119. };
  9120. // Collisions
  9121. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9122. var globalPosition = this.getAbsolutePosition();
  9123. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9124. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9125. this._collider.radius = this.ellipsoid;
  9126. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9127. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9128. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9129. this.position.addInPlace(this._diffPositionForCollisions);
  9130. }
  9131. };
  9132. // Submeshes octree
  9133. /**
  9134. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9135. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9136. */
  9137. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9138. if (typeof maxCapacity === "undefined") { maxCapacity = 64; }
  9139. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  9140. if (!this._submeshesOctree) {
  9141. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9142. }
  9143. this.computeWorldMatrix(true);
  9144. // Update octree
  9145. var bbox = this.getBoundingInfo().boundingBox;
  9146. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9147. return this._submeshesOctree;
  9148. };
  9149. // Collisions
  9150. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9151. this._generatePointsArray();
  9152. // Transformation
  9153. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9154. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9155. subMesh._lastColliderWorldVertices = [];
  9156. subMesh._trianglePlanes = [];
  9157. var start = subMesh.verticesStart;
  9158. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9159. for (var i = start; i < end; i++) {
  9160. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9161. }
  9162. }
  9163. // Collide
  9164. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9165. };
  9166. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9167. var subMeshes;
  9168. var len;
  9169. // Octrees
  9170. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9171. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9172. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9173. len = intersections.length;
  9174. subMeshes = intersections.data;
  9175. } else {
  9176. subMeshes = this.subMeshes;
  9177. len = subMeshes.length;
  9178. }
  9179. for (var index = 0; index < len; index++) {
  9180. var subMesh = subMeshes[index];
  9181. // Bounding test
  9182. if (len > 1 && !subMesh._checkCollision(collider))
  9183. continue;
  9184. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9185. }
  9186. };
  9187. AbstractMesh.prototype._checkCollision = function (collider) {
  9188. // Bounding box test
  9189. if (!this._boundingInfo._checkCollision(collider))
  9190. return;
  9191. // Transformation matrix
  9192. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9193. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9194. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9195. };
  9196. // Picking
  9197. AbstractMesh.prototype._generatePointsArray = function () {
  9198. return false;
  9199. };
  9200. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9201. var pickingInfo = new BABYLON.PickingInfo();
  9202. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9203. return pickingInfo;
  9204. }
  9205. if (!this._generatePointsArray()) {
  9206. return pickingInfo;
  9207. }
  9208. var intersectInfo = null;
  9209. // Octrees
  9210. var subMeshes;
  9211. var len;
  9212. if (this._submeshesOctree && this.useOctreeForPicking) {
  9213. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9214. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9215. len = intersections.length;
  9216. subMeshes = intersections.data;
  9217. } else {
  9218. subMeshes = this.subMeshes;
  9219. len = subMeshes.length;
  9220. }
  9221. for (var index = 0; index < len; index++) {
  9222. var subMesh = subMeshes[index];
  9223. // Bounding test
  9224. if (len > 1 && !subMesh.canIntersects(ray))
  9225. continue;
  9226. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9227. if (currentIntersectInfo) {
  9228. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9229. intersectInfo = currentIntersectInfo;
  9230. if (fastCheck) {
  9231. break;
  9232. }
  9233. }
  9234. }
  9235. }
  9236. if (intersectInfo) {
  9237. // Get picked point
  9238. var world = this.getWorldMatrix();
  9239. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9240. var direction = ray.direction.clone();
  9241. direction.normalize();
  9242. direction = direction.scale(intersectInfo.distance);
  9243. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9244. var pickedPoint = worldOrigin.add(worldDirection);
  9245. // Return result
  9246. pickingInfo.hit = true;
  9247. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9248. pickingInfo.pickedPoint = pickedPoint;
  9249. pickingInfo.pickedMesh = this;
  9250. pickingInfo.bu = intersectInfo.bu;
  9251. pickingInfo.bv = intersectInfo.bv;
  9252. pickingInfo.faceId = intersectInfo.faceId;
  9253. return pickingInfo;
  9254. }
  9255. return pickingInfo;
  9256. };
  9257. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9258. return null;
  9259. };
  9260. AbstractMesh.prototype.releaseSubMeshes = function () {
  9261. if (this.subMeshes) {
  9262. while (this.subMeshes.length) {
  9263. this.subMeshes[0].dispose();
  9264. }
  9265. } else {
  9266. this.subMeshes = new Array();
  9267. }
  9268. };
  9269. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9270. // Physics
  9271. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9272. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9273. }
  9274. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9275. var other = this._intersectionsInProgress[index];
  9276. var pos = other._intersectionsInProgress.indexOf(this);
  9277. other._intersectionsInProgress.splice(pos, 1);
  9278. }
  9279. this._intersectionsInProgress = [];
  9280. // SubMeshes
  9281. this.releaseSubMeshes();
  9282. // Remove from scene
  9283. var index = this.getScene().meshes.indexOf(this);
  9284. if (index != -1) {
  9285. // Remove from the scene if mesh found
  9286. this.getScene().meshes.splice(index, 1);
  9287. }
  9288. if (!doNotRecurse) {
  9289. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9290. if (this.getScene().particleSystems[index].emitter == this) {
  9291. this.getScene().particleSystems[index].dispose();
  9292. index--;
  9293. }
  9294. }
  9295. // Children
  9296. var objects = this.getScene().meshes.slice(0);
  9297. for (index = 0; index < objects.length; index++) {
  9298. if (objects[index].parent == this) {
  9299. objects[index].dispose();
  9300. }
  9301. }
  9302. } else {
  9303. for (index = 0; index < this.getScene().meshes.length; index++) {
  9304. var obj = this.getScene().meshes[index];
  9305. if (obj.parent === this) {
  9306. obj.parent = null;
  9307. obj.computeWorldMatrix(true);
  9308. }
  9309. }
  9310. }
  9311. this._onAfterWorldMatrixUpdate = [];
  9312. this._isDisposed = true;
  9313. // Callback
  9314. if (this.onDispose) {
  9315. this.onDispose();
  9316. }
  9317. };
  9318. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9319. AbstractMesh._BILLBOARDMODE_X = 1;
  9320. AbstractMesh._BILLBOARDMODE_Y = 2;
  9321. AbstractMesh._BILLBOARDMODE_Z = 4;
  9322. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9323. return AbstractMesh;
  9324. })(BABYLON.Node);
  9325. BABYLON.AbstractMesh = AbstractMesh;
  9326. })(BABYLON || (BABYLON = {}));
  9327. //# sourceMappingURL=babylon.abstractMesh.js.map
  9328. var BABYLON;
  9329. (function (BABYLON) {
  9330. var _InstancesBatch = (function () {
  9331. function _InstancesBatch() {
  9332. this.mustReturn = false;
  9333. this.visibleInstances = new Array();
  9334. this.renderSelf = new Array();
  9335. }
  9336. return _InstancesBatch;
  9337. })();
  9338. BABYLON._InstancesBatch = _InstancesBatch;
  9339. var Mesh = (function (_super) {
  9340. __extends(Mesh, _super);
  9341. /**
  9342. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9343. * @param {BABYLON.Scene} scene - The scene to add this mesh to.
  9344. * @param {BABYLON.Node} parent - The parent of this mesh, if it has one
  9345. * @param {BABYLON.Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9346. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9347. * When false, achieved by calling a clone(), also passing False.
  9348. * This will make creation of children, recursive.
  9349. */
  9350. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9351. if (typeof parent === "undefined") { parent = null; }
  9352. _super.call(this, name, scene);
  9353. // Members
  9354. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9355. this.instances = new Array();
  9356. this._LODLevels = new Array();
  9357. this._onBeforeRenderCallbacks = new Array();
  9358. this._onAfterRenderCallbacks = new Array();
  9359. this._visibleInstances = {};
  9360. this._renderIdForInstances = new Array();
  9361. this._batchCache = new _InstancesBatch();
  9362. this._instancesBufferSize = 32 * 16 * 4;
  9363. if (source) {
  9364. // Geometry
  9365. if (source._geometry) {
  9366. source._geometry.applyToMesh(this);
  9367. }
  9368. // Deep copy
  9369. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9370. // Material
  9371. this.material = source.material;
  9372. if (!doNotCloneChildren) {
  9373. for (var index = 0; index < scene.meshes.length; index++) {
  9374. var mesh = scene.meshes[index];
  9375. if (mesh.parent === source) {
  9376. // doNotCloneChildren is always going to be False
  9377. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9378. }
  9379. }
  9380. }
  9381. for (index = 0; index < scene.particleSystems.length; index++) {
  9382. var system = scene.particleSystems[index];
  9383. if (system.emitter === source) {
  9384. system.clone(system.name, this);
  9385. }
  9386. }
  9387. this.computeWorldMatrix(true);
  9388. }
  9389. // Parent
  9390. if (parent !== null) {
  9391. this.parent = parent;
  9392. }
  9393. }
  9394. Mesh.prototype._clone = function () {
  9395. };
  9396. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9397. // Methods
  9398. get: function () {
  9399. return this._LODLevels.length > 0;
  9400. },
  9401. enumerable: true,
  9402. configurable: true
  9403. });
  9404. Mesh.prototype._sortLODLevels = function () {
  9405. this._LODLevels.sort(function (a, b) {
  9406. if (a.distance < b.distance) {
  9407. return 1;
  9408. }
  9409. if (a.distance > b.distance) {
  9410. return -1;
  9411. }
  9412. return 0;
  9413. });
  9414. };
  9415. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9416. if (mesh && mesh._masterMesh) {
  9417. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9418. return this;
  9419. }
  9420. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9421. this._LODLevels.push(level);
  9422. if (mesh) {
  9423. mesh._masterMesh = this;
  9424. }
  9425. this._sortLODLevels();
  9426. return this;
  9427. };
  9428. Mesh.prototype.removeLODLevel = function (mesh) {
  9429. for (var index = 0; index < this._LODLevels.length; index++) {
  9430. if (this._LODLevels[index].mesh === mesh) {
  9431. this._LODLevels.splice(index, 1);
  9432. if (mesh) {
  9433. mesh._masterMesh = null;
  9434. }
  9435. }
  9436. }
  9437. this._sortLODLevels();
  9438. return this;
  9439. };
  9440. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9441. if (!this._LODLevels || this._LODLevels.length === 0) {
  9442. return this;
  9443. }
  9444. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9445. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9446. return this;
  9447. }
  9448. for (var index = 0; index < this._LODLevels.length; index++) {
  9449. var level = this._LODLevels[index];
  9450. if (level.distance < distanceToCamera) {
  9451. if (level.mesh) {
  9452. level.mesh._preActivate();
  9453. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9454. }
  9455. return level.mesh;
  9456. }
  9457. }
  9458. return this;
  9459. };
  9460. Object.defineProperty(Mesh.prototype, "geometry", {
  9461. get: function () {
  9462. return this._geometry;
  9463. },
  9464. enumerable: true,
  9465. configurable: true
  9466. });
  9467. Mesh.prototype.getTotalVertices = function () {
  9468. if (!this._geometry) {
  9469. return 0;
  9470. }
  9471. return this._geometry.getTotalVertices();
  9472. };
  9473. Mesh.prototype.getVerticesData = function (kind) {
  9474. if (!this._geometry) {
  9475. return null;
  9476. }
  9477. return this._geometry.getVerticesData(kind);
  9478. };
  9479. Mesh.prototype.getVertexBuffer = function (kind) {
  9480. if (!this._geometry) {
  9481. return undefined;
  9482. }
  9483. return this._geometry.getVertexBuffer(kind);
  9484. };
  9485. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9486. if (!this._geometry) {
  9487. if (this._delayInfo) {
  9488. return this._delayInfo.indexOf(kind) !== -1;
  9489. }
  9490. return false;
  9491. }
  9492. return this._geometry.isVerticesDataPresent(kind);
  9493. };
  9494. Mesh.prototype.getVerticesDataKinds = function () {
  9495. if (!this._geometry) {
  9496. var result = [];
  9497. if (this._delayInfo) {
  9498. for (var kind in this._delayInfo) {
  9499. result.push(kind);
  9500. }
  9501. }
  9502. return result;
  9503. }
  9504. return this._geometry.getVerticesDataKinds();
  9505. };
  9506. Mesh.prototype.getTotalIndices = function () {
  9507. if (!this._geometry) {
  9508. return 0;
  9509. }
  9510. return this._geometry.getTotalIndices();
  9511. };
  9512. Mesh.prototype.getIndices = function () {
  9513. if (!this._geometry) {
  9514. return [];
  9515. }
  9516. return this._geometry.getIndices();
  9517. };
  9518. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9519. get: function () {
  9520. return this._masterMesh !== null && this._masterMesh !== undefined;
  9521. },
  9522. enumerable: true,
  9523. configurable: true
  9524. });
  9525. Mesh.prototype.isReady = function () {
  9526. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9527. return false;
  9528. }
  9529. return _super.prototype.isReady.call(this);
  9530. };
  9531. Mesh.prototype.isDisposed = function () {
  9532. return this._isDisposed;
  9533. };
  9534. // Methods
  9535. Mesh.prototype._preActivate = function () {
  9536. var sceneRenderId = this.getScene().getRenderId();
  9537. if (this._preActivateId == sceneRenderId) {
  9538. return;
  9539. }
  9540. this._preActivateId = sceneRenderId;
  9541. this._visibleInstances = null;
  9542. };
  9543. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9544. if (!this._visibleInstances) {
  9545. this._visibleInstances = {};
  9546. this._visibleInstances.defaultRenderId = renderId;
  9547. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9548. }
  9549. if (!this._visibleInstances[renderId]) {
  9550. this._visibleInstances[renderId] = new Array();
  9551. }
  9552. this._visibleInstances[renderId].push(instance);
  9553. };
  9554. Mesh.prototype.refreshBoundingInfo = function () {
  9555. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9556. if (data) {
  9557. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9558. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9559. }
  9560. if (this.subMeshes) {
  9561. for (var index = 0; index < this.subMeshes.length; index++) {
  9562. this.subMeshes[index].refreshBoundingInfo();
  9563. }
  9564. }
  9565. this._updateBoundingInfo();
  9566. };
  9567. Mesh.prototype._createGlobalSubMesh = function () {
  9568. var totalVertices = this.getTotalVertices();
  9569. if (!totalVertices || !this.getIndices()) {
  9570. return null;
  9571. }
  9572. this.releaseSubMeshes();
  9573. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9574. };
  9575. Mesh.prototype.subdivide = function (count) {
  9576. if (count < 1) {
  9577. return;
  9578. }
  9579. var totalIndices = this.getTotalIndices();
  9580. var subdivisionSize = (totalIndices / count) | 0;
  9581. var offset = 0;
  9582. while (subdivisionSize % 3 != 0) {
  9583. subdivisionSize++;
  9584. }
  9585. this.releaseSubMeshes();
  9586. for (var index = 0; index < count; index++) {
  9587. if (offset >= totalIndices) {
  9588. break;
  9589. }
  9590. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9591. offset += subdivisionSize;
  9592. }
  9593. this.synchronizeInstances();
  9594. };
  9595. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9596. if (kind instanceof Array) {
  9597. var temp = data;
  9598. data = kind;
  9599. kind = temp;
  9600. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9601. }
  9602. if (!this._geometry) {
  9603. var vertexData = new BABYLON.VertexData();
  9604. vertexData.set(data, kind);
  9605. var scene = this.getScene();
  9606. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9607. } else {
  9608. this._geometry.setVerticesData(kind, data, updatable, stride);
  9609. }
  9610. };
  9611. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9612. if (!this._geometry) {
  9613. return;
  9614. }
  9615. if (!makeItUnique) {
  9616. this._geometry.updateVerticesData(kind, data, updateExtends);
  9617. } else {
  9618. this.makeGeometryUnique();
  9619. this.updateVerticesData(kind, data, updateExtends, false);
  9620. }
  9621. };
  9622. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9623. if (!this._geometry) {
  9624. return;
  9625. }
  9626. if (!makeItUnique) {
  9627. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9628. } else {
  9629. this.makeGeometryUnique();
  9630. this.updateVerticesDataDirectly(kind, data, offset, false);
  9631. }
  9632. };
  9633. Mesh.prototype.makeGeometryUnique = function () {
  9634. if (!this._geometry) {
  9635. return;
  9636. }
  9637. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9638. geometry.applyToMesh(this);
  9639. };
  9640. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9641. if (!this._geometry) {
  9642. var vertexData = new BABYLON.VertexData();
  9643. vertexData.indices = indices;
  9644. var scene = this.getScene();
  9645. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9646. } else {
  9647. this._geometry.setIndices(indices, totalVertices);
  9648. }
  9649. };
  9650. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9651. var engine = this.getScene().getEngine();
  9652. // Wireframe
  9653. var indexToBind;
  9654. switch (fillMode) {
  9655. case BABYLON.Material.PointFillMode:
  9656. indexToBind = null;
  9657. break;
  9658. case BABYLON.Material.WireFrameFillMode:
  9659. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9660. break;
  9661. default:
  9662. case BABYLON.Material.TriangleFillMode:
  9663. indexToBind = this._geometry.getIndexBuffer();
  9664. break;
  9665. }
  9666. // VBOs
  9667. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9668. };
  9669. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9670. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9671. return;
  9672. }
  9673. var engine = this.getScene().getEngine();
  9674. switch (fillMode) {
  9675. case BABYLON.Material.PointFillMode:
  9676. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9677. break;
  9678. case BABYLON.Material.WireFrameFillMode:
  9679. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9680. break;
  9681. default:
  9682. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9683. }
  9684. };
  9685. Mesh.prototype.registerBeforeRender = function (func) {
  9686. this._onBeforeRenderCallbacks.push(func);
  9687. };
  9688. Mesh.prototype.unregisterBeforeRender = function (func) {
  9689. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9690. if (index > -1) {
  9691. this._onBeforeRenderCallbacks.splice(index, 1);
  9692. }
  9693. };
  9694. Mesh.prototype.registerAfterRender = function (func) {
  9695. this._onAfterRenderCallbacks.push(func);
  9696. };
  9697. Mesh.prototype.unregisterAfterRender = function (func) {
  9698. var index = this._onAfterRenderCallbacks.indexOf(func);
  9699. if (index > -1) {
  9700. this._onAfterRenderCallbacks.splice(index, 1);
  9701. }
  9702. };
  9703. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9704. var scene = this.getScene();
  9705. this._batchCache.mustReturn = false;
  9706. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9707. this._batchCache.visibleInstances[subMeshId] = null;
  9708. if (this._visibleInstances) {
  9709. var currentRenderId = scene.getRenderId();
  9710. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9711. var selfRenderId = this._renderId;
  9712. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9713. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9714. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9715. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9716. }
  9717. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9718. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9719. this._batchCache.mustReturn = true;
  9720. return this._batchCache;
  9721. }
  9722. if (currentRenderId !== selfRenderId) {
  9723. this._batchCache.renderSelf[subMeshId] = false;
  9724. }
  9725. }
  9726. this._renderIdForInstances[subMeshId] = currentRenderId;
  9727. }
  9728. return this._batchCache;
  9729. };
  9730. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9731. var visibleInstances = batch.visibleInstances[subMesh._id];
  9732. var matricesCount = visibleInstances.length + 1;
  9733. var bufferSize = matricesCount * 16 * 4;
  9734. while (this._instancesBufferSize < bufferSize) {
  9735. this._instancesBufferSize *= 2;
  9736. }
  9737. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9738. if (this._worldMatricesInstancesBuffer) {
  9739. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9740. }
  9741. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9742. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9743. }
  9744. var offset = 0;
  9745. var instancesCount = 0;
  9746. var world = this.getWorldMatrix();
  9747. if (batch.renderSelf[subMesh._id]) {
  9748. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9749. offset += 16;
  9750. instancesCount++;
  9751. }
  9752. if (visibleInstances) {
  9753. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9754. var instance = visibleInstances[instanceIndex];
  9755. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9756. offset += 16;
  9757. instancesCount++;
  9758. }
  9759. }
  9760. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9761. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9762. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9763. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9764. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9765. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9766. this._draw(subMesh, fillMode, instancesCount);
  9767. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9768. };
  9769. Mesh.prototype.render = function (subMesh) {
  9770. var scene = this.getScene();
  9771. // Managing instances
  9772. var batch = this._getInstancesRenderList(subMesh._id);
  9773. if (batch.mustReturn) {
  9774. return;
  9775. }
  9776. // Checking geometry state
  9777. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9778. return;
  9779. }
  9780. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9781. this._onBeforeRenderCallbacks[callbackIndex]();
  9782. }
  9783. var engine = scene.getEngine();
  9784. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9785. // Material
  9786. var effectiveMaterial = subMesh.getMaterial();
  9787. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9788. return;
  9789. }
  9790. // Outline - step 1
  9791. var savedDepthWrite = engine.getDepthWrite();
  9792. if (this.renderOutline) {
  9793. engine.setDepthWrite(false);
  9794. scene.getOutlineRenderer().render(subMesh, batch);
  9795. engine.setDepthWrite(savedDepthWrite);
  9796. }
  9797. effectiveMaterial._preBind();
  9798. var effect = effectiveMaterial.getEffect();
  9799. // Bind
  9800. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9801. this._bind(subMesh, effect, fillMode);
  9802. var world = this.getWorldMatrix();
  9803. effectiveMaterial.bind(world, this);
  9804. // Instances rendering
  9805. if (hardwareInstancedRendering) {
  9806. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9807. } else {
  9808. if (batch.renderSelf[subMesh._id]) {
  9809. // Draw
  9810. this._draw(subMesh, fillMode);
  9811. }
  9812. if (batch.visibleInstances[subMesh._id]) {
  9813. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9814. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9815. // World
  9816. world = instance.getWorldMatrix();
  9817. effectiveMaterial.bindOnlyWorldMatrix(world);
  9818. // Draw
  9819. this._draw(subMesh, fillMode);
  9820. }
  9821. }
  9822. }
  9823. // Unbind
  9824. effectiveMaterial.unbind();
  9825. // Outline - step 2
  9826. if (this.renderOutline && savedDepthWrite) {
  9827. engine.setDepthWrite(true);
  9828. engine.setColorWrite(false);
  9829. scene.getOutlineRenderer().render(subMesh, batch);
  9830. engine.setColorWrite(true);
  9831. }
  9832. // Overlay
  9833. if (this.renderOverlay) {
  9834. var currentMode = engine.getAlphaMode();
  9835. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9836. scene.getOutlineRenderer().render(subMesh, batch, true);
  9837. engine.setAlphaMode(currentMode);
  9838. }
  9839. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9840. this._onAfterRenderCallbacks[callbackIndex]();
  9841. }
  9842. };
  9843. Mesh.prototype.getEmittedParticleSystems = function () {
  9844. var results = new Array();
  9845. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9846. var particleSystem = this.getScene().particleSystems[index];
  9847. if (particleSystem.emitter === this) {
  9848. results.push(particleSystem);
  9849. }
  9850. }
  9851. return results;
  9852. };
  9853. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9854. var results = new Array();
  9855. var descendants = this.getDescendants();
  9856. descendants.push(this);
  9857. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9858. var particleSystem = this.getScene().particleSystems[index];
  9859. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9860. results.push(particleSystem);
  9861. }
  9862. }
  9863. return results;
  9864. };
  9865. Mesh.prototype.getChildren = function () {
  9866. var results = [];
  9867. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9868. var mesh = this.getScene().meshes[index];
  9869. if (mesh.parent == this) {
  9870. results.push(mesh);
  9871. }
  9872. }
  9873. return results;
  9874. };
  9875. Mesh.prototype._checkDelayState = function () {
  9876. var _this = this;
  9877. var that = this;
  9878. var scene = this.getScene();
  9879. if (this._geometry) {
  9880. this._geometry.load(scene);
  9881. } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9882. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9883. scene._addPendingData(that);
  9884. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9885. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9886. if (data instanceof ArrayBuffer) {
  9887. _this._delayLoadingFunction(data, _this);
  9888. } else {
  9889. _this._delayLoadingFunction(JSON.parse(data), _this);
  9890. }
  9891. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9892. scene._removePendingData(_this);
  9893. }, function () {
  9894. }, scene.database, getBinaryData);
  9895. }
  9896. };
  9897. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  9898. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9899. return false;
  9900. }
  9901. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  9902. return false;
  9903. }
  9904. this._checkDelayState();
  9905. return true;
  9906. };
  9907. Mesh.prototype.setMaterialByID = function (id) {
  9908. var materials = this.getScene().materials;
  9909. for (var index = 0; index < materials.length; index++) {
  9910. if (materials[index].id == id) {
  9911. this.material = materials[index];
  9912. return;
  9913. }
  9914. }
  9915. // Multi
  9916. var multiMaterials = this.getScene().multiMaterials;
  9917. for (index = 0; index < multiMaterials.length; index++) {
  9918. if (multiMaterials[index].id == id) {
  9919. this.material = multiMaterials[index];
  9920. return;
  9921. }
  9922. }
  9923. };
  9924. Mesh.prototype.getAnimatables = function () {
  9925. var results = [];
  9926. if (this.material) {
  9927. results.push(this.material);
  9928. }
  9929. if (this.skeleton) {
  9930. results.push(this.skeleton);
  9931. }
  9932. return results;
  9933. };
  9934. // Geometry
  9935. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  9936. // Position
  9937. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  9938. return;
  9939. }
  9940. this._resetPointsArrayCache();
  9941. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9942. var temp = [];
  9943. for (var index = 0; index < data.length; index += 3) {
  9944. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9945. }
  9946. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  9947. // Normals
  9948. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9949. return;
  9950. }
  9951. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9952. for (index = 0; index < data.length; index += 3) {
  9953. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  9954. }
  9955. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  9956. };
  9957. // Cache
  9958. Mesh.prototype._resetPointsArrayCache = function () {
  9959. this._positions = null;
  9960. };
  9961. Mesh.prototype._generatePointsArray = function () {
  9962. if (this._positions)
  9963. return true;
  9964. this._positions = [];
  9965. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9966. if (!data) {
  9967. return false;
  9968. }
  9969. for (var index = 0; index < data.length; index += 3) {
  9970. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  9971. }
  9972. return true;
  9973. };
  9974. // Clone
  9975. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9976. return new BABYLON.Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  9977. };
  9978. // Dispose
  9979. Mesh.prototype.dispose = function (doNotRecurse) {
  9980. if (this._geometry) {
  9981. this._geometry.releaseForMesh(this, true);
  9982. }
  9983. // Instances
  9984. if (this._worldMatricesInstancesBuffer) {
  9985. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9986. this._worldMatricesInstancesBuffer = null;
  9987. }
  9988. while (this.instances.length) {
  9989. this.instances[0].dispose();
  9990. }
  9991. _super.prototype.dispose.call(this, doNotRecurse);
  9992. };
  9993. // Geometric tools
  9994. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  9995. var _this = this;
  9996. var scene = this.getScene();
  9997. var onload = function (img) {
  9998. // Getting height map data
  9999. var canvas = document.createElement("canvas");
  10000. var context = canvas.getContext("2d");
  10001. var heightMapWidth = img.width;
  10002. var heightMapHeight = img.height;
  10003. canvas.width = heightMapWidth;
  10004. canvas.height = heightMapHeight;
  10005. context.drawImage(img, 0, 0);
  10006. // Create VertexData from map data
  10007. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10008. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10009. };
  10010. BABYLON.Tools.LoadImage(url, onload, function () {
  10011. }, scene.database);
  10012. };
  10013. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10014. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10015. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10016. return;
  10017. }
  10018. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10019. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10020. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10021. var position = BABYLON.Vector3.Zero();
  10022. var normal = BABYLON.Vector3.Zero();
  10023. var uv = BABYLON.Vector2.Zero();
  10024. for (var index = 0; index < positions.length; index += 3) {
  10025. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10026. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10027. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10028. // Compute height
  10029. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10030. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10031. var pos = (u + v * heightMapWidth) * 4;
  10032. var r = buffer[pos] / 255.0;
  10033. var g = buffer[pos + 1] / 255.0;
  10034. var b = buffer[pos + 2] / 255.0;
  10035. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10036. normal.normalize();
  10037. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10038. position = position.add(normal);
  10039. position.toArray(positions, index);
  10040. }
  10041. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10042. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10043. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10044. };
  10045. Mesh.prototype.convertToFlatShadedMesh = function () {
  10046. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10047. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10048. var kinds = this.getVerticesDataKinds();
  10049. var vbs = [];
  10050. var data = [];
  10051. var newdata = [];
  10052. var updatableNormals = false;
  10053. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10054. var kind = kinds[kindIndex];
  10055. var vertexBuffer = this.getVertexBuffer(kind);
  10056. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10057. updatableNormals = vertexBuffer.isUpdatable();
  10058. kinds.splice(kindIndex, 1);
  10059. kindIndex--;
  10060. continue;
  10061. }
  10062. vbs[kind] = vertexBuffer;
  10063. data[kind] = vbs[kind].getData();
  10064. newdata[kind] = [];
  10065. }
  10066. // Save previous submeshes
  10067. var previousSubmeshes = this.subMeshes.slice(0);
  10068. var indices = this.getIndices();
  10069. var totalIndices = this.getTotalIndices();
  10070. for (index = 0; index < totalIndices; index++) {
  10071. var vertexIndex = indices[index];
  10072. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10073. kind = kinds[kindIndex];
  10074. var stride = vbs[kind].getStrideSize();
  10075. for (var offset = 0; offset < stride; offset++) {
  10076. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10077. }
  10078. }
  10079. }
  10080. // Updating faces & normal
  10081. var normals = [];
  10082. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10083. for (var index = 0; index < totalIndices; index += 3) {
  10084. indices[index] = index;
  10085. indices[index + 1] = index + 1;
  10086. indices[index + 2] = index + 2;
  10087. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10088. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10089. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10090. var p1p2 = p1.subtract(p2);
  10091. var p3p2 = p3.subtract(p2);
  10092. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10093. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10094. normals.push(normal.x);
  10095. normals.push(normal.y);
  10096. normals.push(normal.z);
  10097. }
  10098. }
  10099. this.setIndices(indices);
  10100. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10101. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10102. kind = kinds[kindIndex];
  10103. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10104. }
  10105. // Updating submeshes
  10106. this.releaseSubMeshes();
  10107. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10108. var previousOne = previousSubmeshes[submeshIndex];
  10109. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10110. }
  10111. this.synchronizeInstances();
  10112. };
  10113. // Instances
  10114. Mesh.prototype.createInstance = function (name) {
  10115. return new BABYLON.InstancedMesh(name, this);
  10116. };
  10117. Mesh.prototype.synchronizeInstances = function () {
  10118. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10119. var instance = this.instances[instanceIndex];
  10120. instance._syncSubMeshes();
  10121. }
  10122. };
  10123. /**
  10124. * Simplify the mesh according to the given array of settings.
  10125. * Function will return immediately and will simplify async.
  10126. * @param settings a collection of simplification settings.
  10127. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10128. * @param type the type of simplification to run.
  10129. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10130. */
  10131. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10132. var _this = this;
  10133. if (typeof parallelProcessing === "undefined") { parallelProcessing = true; }
  10134. if (typeof type === "undefined") { type = 0 /* QUADRATIC */; }
  10135. var getSimplifier = function () {
  10136. switch (type) {
  10137. case 0 /* QUADRATIC */:
  10138. default:
  10139. return new BABYLON.QuadraticErrorSimplification(_this);
  10140. }
  10141. };
  10142. if (parallelProcessing) {
  10143. //parallel simplifier
  10144. settings.forEach(function (setting) {
  10145. var simplifier = getSimplifier();
  10146. simplifier.simplify(setting, function (newMesh) {
  10147. _this.addLODLevel(setting.distance, newMesh);
  10148. //check if it is the last
  10149. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10150. //all done, run the success callback.
  10151. successCallback();
  10152. }
  10153. });
  10154. });
  10155. } else {
  10156. //single simplifier.
  10157. var simplifier = getSimplifier();
  10158. var runDecimation = function (setting, callback) {
  10159. simplifier.simplify(setting, function (newMesh) {
  10160. _this.addLODLevel(setting.distance, newMesh);
  10161. //run the next quality level
  10162. callback();
  10163. });
  10164. };
  10165. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10166. runDecimation(settings[loop.index], function () {
  10167. loop.executeNext();
  10168. });
  10169. }, function () {
  10170. //execution ended, run the success callback.
  10171. successCallback();
  10172. });
  10173. }
  10174. };
  10175. // Statics
  10176. Mesh.CreateBox = function (name, size, scene, updatable) {
  10177. var box = new BABYLON.Mesh(name, scene);
  10178. var vertexData = BABYLON.VertexData.CreateBox(size);
  10179. vertexData.applyToMesh(box, updatable);
  10180. return box;
  10181. };
  10182. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10183. var sphere = new BABYLON.Mesh(name, scene);
  10184. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10185. vertexData.applyToMesh(sphere, updatable);
  10186. return sphere;
  10187. };
  10188. // Cylinder and cone (Code inspired by SharpDX.org)
  10189. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10190. // subdivisions is a new parameter, we need to support old signature
  10191. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10192. if (scene !== undefined) {
  10193. updatable = scene;
  10194. }
  10195. scene = subdivisions;
  10196. subdivisions = 1;
  10197. }
  10198. var cylinder = new BABYLON.Mesh(name, scene);
  10199. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10200. vertexData.applyToMesh(cylinder, updatable);
  10201. return cylinder;
  10202. };
  10203. // Torus (Code from SharpDX.org)
  10204. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10205. var torus = new BABYLON.Mesh(name, scene);
  10206. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10207. vertexData.applyToMesh(torus, updatable);
  10208. return torus;
  10209. };
  10210. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10211. var torusKnot = new BABYLON.Mesh(name, scene);
  10212. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10213. vertexData.applyToMesh(torusKnot, updatable);
  10214. return torusKnot;
  10215. };
  10216. // Lines
  10217. Mesh.CreateLines = function (name, points, scene, updatable) {
  10218. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10219. var vertexData = BABYLON.VertexData.CreateLines(points);
  10220. vertexData.applyToMesh(lines, updatable);
  10221. return lines;
  10222. };
  10223. // Plane & ground
  10224. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10225. var plane = new BABYLON.Mesh(name, scene);
  10226. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10227. vertexData.applyToMesh(plane, updatable);
  10228. return plane;
  10229. };
  10230. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10231. var ground = new BABYLON.GroundMesh(name, scene);
  10232. ground._setReady(false);
  10233. ground._subdivisions = subdivisions;
  10234. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10235. vertexData.applyToMesh(ground, updatable);
  10236. ground._setReady(true);
  10237. return ground;
  10238. };
  10239. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10240. var tiledGround = new BABYLON.Mesh(name, scene);
  10241. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10242. vertexData.applyToMesh(tiledGround, updatable);
  10243. return tiledGround;
  10244. };
  10245. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10246. var ground = new BABYLON.GroundMesh(name, scene);
  10247. ground._subdivisions = subdivisions;
  10248. ground._setReady(false);
  10249. var onload = function (img) {
  10250. // Getting height map data
  10251. var canvas = document.createElement("canvas");
  10252. var context = canvas.getContext("2d");
  10253. var heightMapWidth = img.width;
  10254. var heightMapHeight = img.height;
  10255. canvas.width = heightMapWidth;
  10256. canvas.height = heightMapHeight;
  10257. context.drawImage(img, 0, 0);
  10258. // Create VertexData from map data
  10259. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10260. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10261. vertexData.applyToMesh(ground, updatable);
  10262. ground._setReady(true);
  10263. };
  10264. BABYLON.Tools.LoadImage(url, onload, function () {
  10265. }, scene.database);
  10266. return ground;
  10267. };
  10268. // Tools
  10269. Mesh.MinMax = function (meshes) {
  10270. var minVector = null;
  10271. var maxVector = null;
  10272. for (var i in meshes) {
  10273. var mesh = meshes[i];
  10274. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10275. if (!minVector) {
  10276. minVector = boundingBox.minimumWorld;
  10277. maxVector = boundingBox.maximumWorld;
  10278. continue;
  10279. }
  10280. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10281. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10282. }
  10283. return {
  10284. min: minVector,
  10285. max: maxVector
  10286. };
  10287. };
  10288. Mesh.Center = function (meshesOrMinMaxVector) {
  10289. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  10290. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10291. };
  10292. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10293. if (typeof disposeSource === "undefined") { disposeSource = true; }
  10294. var source = meshes[0];
  10295. var material = source.material;
  10296. var scene = source.getScene();
  10297. if (!allow32BitsIndices) {
  10298. var totalVertices = 0;
  10299. for (var index = 0; index < meshes.length; index++) {
  10300. totalVertices += meshes[index].getTotalVertices();
  10301. if (totalVertices > 65536) {
  10302. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10303. return null;
  10304. }
  10305. }
  10306. }
  10307. // Merge
  10308. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10309. vertexData.transform(source.getWorldMatrix());
  10310. for (index = 1; index < meshes.length; index++) {
  10311. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10312. otherVertexData.transform(meshes[index].getWorldMatrix());
  10313. vertexData.merge(otherVertexData);
  10314. }
  10315. var newMesh = new Mesh(source.name + "_merged", scene);
  10316. vertexData.applyToMesh(newMesh);
  10317. // Setting properties
  10318. newMesh.material = material;
  10319. newMesh.checkCollisions = source.checkCollisions;
  10320. // Cleaning
  10321. if (disposeSource) {
  10322. for (index = 0; index < meshes.length; index++) {
  10323. meshes[index].dispose();
  10324. }
  10325. }
  10326. return newMesh;
  10327. };
  10328. return Mesh;
  10329. })(BABYLON.AbstractMesh);
  10330. BABYLON.Mesh = Mesh;
  10331. })(BABYLON || (BABYLON = {}));
  10332. //# sourceMappingURL=babylon.mesh.js.map
  10333. var BABYLON;
  10334. (function (BABYLON) {
  10335. var GroundMesh = (function (_super) {
  10336. __extends(GroundMesh, _super);
  10337. function GroundMesh(name, scene) {
  10338. _super.call(this, name, scene);
  10339. this.generateOctree = false;
  10340. this._worldInverse = new BABYLON.Matrix();
  10341. }
  10342. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10343. get: function () {
  10344. return this._subdivisions;
  10345. },
  10346. enumerable: true,
  10347. configurable: true
  10348. });
  10349. GroundMesh.prototype.optimize = function (chunksCount) {
  10350. this.subdivide(this._subdivisions);
  10351. this.createOrUpdateSubmeshesOctree(32);
  10352. };
  10353. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10354. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10355. this.getWorldMatrix().invertToRef(this._worldInverse);
  10356. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10357. var pickInfo = this.intersects(ray);
  10358. if (pickInfo.hit) {
  10359. return pickInfo.pickedPoint.y;
  10360. }
  10361. return 0;
  10362. };
  10363. return GroundMesh;
  10364. })(BABYLON.Mesh);
  10365. BABYLON.GroundMesh = GroundMesh;
  10366. })(BABYLON || (BABYLON = {}));
  10367. //# sourceMappingURL=babylon.groundMesh.js.map
  10368. var BABYLON;
  10369. (function (BABYLON) {
  10370. var InstancedMesh = (function (_super) {
  10371. __extends(InstancedMesh, _super);
  10372. function InstancedMesh(name, source) {
  10373. _super.call(this, name, source.getScene());
  10374. source.instances.push(this);
  10375. this._sourceMesh = source;
  10376. this.position.copyFrom(source.position);
  10377. this.rotation.copyFrom(source.rotation);
  10378. this.scaling.copyFrom(source.scaling);
  10379. if (source.rotationQuaternion) {
  10380. this.rotationQuaternion = source.rotationQuaternion.clone();
  10381. }
  10382. this.infiniteDistance = source.infiniteDistance;
  10383. this.setPivotMatrix(source.getPivotMatrix());
  10384. this.refreshBoundingInfo();
  10385. this._syncSubMeshes();
  10386. }
  10387. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10388. // Methods
  10389. get: function () {
  10390. return this._sourceMesh.receiveShadows;
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. Object.defineProperty(InstancedMesh.prototype, "material", {
  10396. get: function () {
  10397. return this._sourceMesh.material;
  10398. },
  10399. enumerable: true,
  10400. configurable: true
  10401. });
  10402. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10403. get: function () {
  10404. return this._sourceMesh.visibility;
  10405. },
  10406. enumerable: true,
  10407. configurable: true
  10408. });
  10409. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10410. get: function () {
  10411. return this._sourceMesh.skeleton;
  10412. },
  10413. enumerable: true,
  10414. configurable: true
  10415. });
  10416. InstancedMesh.prototype.getTotalVertices = function () {
  10417. return this._sourceMesh.getTotalVertices();
  10418. };
  10419. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10420. get: function () {
  10421. return this._sourceMesh;
  10422. },
  10423. enumerable: true,
  10424. configurable: true
  10425. });
  10426. InstancedMesh.prototype.getVerticesData = function (kind) {
  10427. return this._sourceMesh.getVerticesData(kind);
  10428. };
  10429. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10430. return this._sourceMesh.isVerticesDataPresent(kind);
  10431. };
  10432. InstancedMesh.prototype.getIndices = function () {
  10433. return this._sourceMesh.getIndices();
  10434. };
  10435. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10436. get: function () {
  10437. return this._sourceMesh._positions;
  10438. },
  10439. enumerable: true,
  10440. configurable: true
  10441. });
  10442. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10443. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10444. if (data) {
  10445. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10446. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10447. }
  10448. this._updateBoundingInfo();
  10449. };
  10450. InstancedMesh.prototype._preActivate = function () {
  10451. if (this._currentLOD) {
  10452. this._currentLOD._preActivate();
  10453. }
  10454. };
  10455. InstancedMesh.prototype._activate = function (renderId) {
  10456. if (this._currentLOD) {
  10457. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10458. }
  10459. };
  10460. InstancedMesh.prototype.getLOD = function (camera) {
  10461. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10462. if (this._currentLOD === this.sourceMesh) {
  10463. return this;
  10464. }
  10465. return this._currentLOD;
  10466. };
  10467. InstancedMesh.prototype._syncSubMeshes = function () {
  10468. this.releaseSubMeshes();
  10469. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10470. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10471. }
  10472. };
  10473. InstancedMesh.prototype._generatePointsArray = function () {
  10474. return this._sourceMesh._generatePointsArray();
  10475. };
  10476. // Clone
  10477. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10478. var result = this._sourceMesh.createInstance(name);
  10479. // Deep copy
  10480. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10481. // Bounding info
  10482. this.refreshBoundingInfo();
  10483. // Parent
  10484. if (newParent) {
  10485. result.parent = newParent;
  10486. }
  10487. if (!doNotCloneChildren) {
  10488. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10489. var mesh = this.getScene().meshes[index];
  10490. if (mesh.parent == this) {
  10491. mesh.clone(mesh.name, result);
  10492. }
  10493. }
  10494. }
  10495. result.computeWorldMatrix(true);
  10496. return result;
  10497. };
  10498. // Dispoe
  10499. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10500. // Remove from mesh
  10501. var index = this._sourceMesh.instances.indexOf(this);
  10502. this._sourceMesh.instances.splice(index, 1);
  10503. _super.prototype.dispose.call(this, doNotRecurse);
  10504. };
  10505. return InstancedMesh;
  10506. })(BABYLON.AbstractMesh);
  10507. BABYLON.InstancedMesh = InstancedMesh;
  10508. })(BABYLON || (BABYLON = {}));
  10509. //# sourceMappingURL=babylon.instancedMesh.js.map
  10510. var BABYLON;
  10511. (function (BABYLON) {
  10512. var SubMesh = (function () {
  10513. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10514. if (typeof createBoundingBox === "undefined") { createBoundingBox = true; }
  10515. this.materialIndex = materialIndex;
  10516. this.verticesStart = verticesStart;
  10517. this.verticesCount = verticesCount;
  10518. this.indexStart = indexStart;
  10519. this.indexCount = indexCount;
  10520. this._renderId = 0;
  10521. this._mesh = mesh;
  10522. this._renderingMesh = renderingMesh || mesh;
  10523. mesh.subMeshes.push(this);
  10524. this._id = mesh.subMeshes.length - 1;
  10525. if (createBoundingBox) {
  10526. this.refreshBoundingInfo();
  10527. }
  10528. }
  10529. SubMesh.prototype.getBoundingInfo = function () {
  10530. return this._boundingInfo;
  10531. };
  10532. SubMesh.prototype.getMesh = function () {
  10533. return this._mesh;
  10534. };
  10535. SubMesh.prototype.getRenderingMesh = function () {
  10536. return this._renderingMesh;
  10537. };
  10538. SubMesh.prototype.getMaterial = function () {
  10539. var rootMaterial = this._renderingMesh.material;
  10540. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10541. var multiMaterial = rootMaterial;
  10542. return multiMaterial.getSubMaterial(this.materialIndex);
  10543. }
  10544. if (!rootMaterial) {
  10545. return this._mesh.getScene().defaultMaterial;
  10546. }
  10547. return rootMaterial;
  10548. };
  10549. // Methods
  10550. SubMesh.prototype.refreshBoundingInfo = function () {
  10551. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10552. if (!data) {
  10553. this._boundingInfo = this._mesh._boundingInfo;
  10554. return;
  10555. }
  10556. var indices = this._renderingMesh.getIndices();
  10557. var extend;
  10558. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10559. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10560. } else {
  10561. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10562. }
  10563. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10564. };
  10565. SubMesh.prototype._checkCollision = function (collider) {
  10566. return this._boundingInfo._checkCollision(collider);
  10567. };
  10568. SubMesh.prototype.updateBoundingInfo = function (world) {
  10569. if (!this._boundingInfo) {
  10570. this.refreshBoundingInfo();
  10571. }
  10572. this._boundingInfo._update(world);
  10573. };
  10574. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10575. return this._boundingInfo.isInFrustum(frustumPlanes);
  10576. };
  10577. SubMesh.prototype.render = function () {
  10578. this._renderingMesh.render(this);
  10579. };
  10580. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10581. if (!this._linesIndexBuffer) {
  10582. var linesIndices = [];
  10583. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10584. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10585. }
  10586. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10587. this.linesIndexCount = linesIndices.length;
  10588. }
  10589. return this._linesIndexBuffer;
  10590. };
  10591. SubMesh.prototype.canIntersects = function (ray) {
  10592. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10593. };
  10594. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10595. var intersectInfo = null;
  10596. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10597. var p0 = positions[indices[index]];
  10598. var p1 = positions[indices[index + 1]];
  10599. var p2 = positions[indices[index + 2]];
  10600. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10601. if (currentIntersectInfo) {
  10602. if (currentIntersectInfo.distance < 0) {
  10603. continue;
  10604. }
  10605. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10606. intersectInfo = currentIntersectInfo;
  10607. intersectInfo.faceId = index / 3;
  10608. if (fastCheck) {
  10609. break;
  10610. }
  10611. }
  10612. }
  10613. }
  10614. return intersectInfo;
  10615. };
  10616. // Clone
  10617. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10618. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10619. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10620. return result;
  10621. };
  10622. // Dispose
  10623. SubMesh.prototype.dispose = function () {
  10624. if (this._linesIndexBuffer) {
  10625. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10626. this._linesIndexBuffer = null;
  10627. }
  10628. // Remove from mesh
  10629. var index = this._mesh.subMeshes.indexOf(this);
  10630. this._mesh.subMeshes.splice(index, 1);
  10631. };
  10632. // Statics
  10633. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10634. var minVertexIndex = Number.MAX_VALUE;
  10635. var maxVertexIndex = -Number.MAX_VALUE;
  10636. renderingMesh = renderingMesh || mesh;
  10637. var indices = renderingMesh.getIndices();
  10638. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10639. var vertexIndex = indices[index];
  10640. if (vertexIndex < minVertexIndex)
  10641. minVertexIndex = vertexIndex;
  10642. if (vertexIndex > maxVertexIndex)
  10643. maxVertexIndex = vertexIndex;
  10644. }
  10645. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10646. };
  10647. return SubMesh;
  10648. })();
  10649. BABYLON.SubMesh = SubMesh;
  10650. })(BABYLON || (BABYLON = {}));
  10651. //# sourceMappingURL=babylon.subMesh.js.map
  10652. var BABYLON;
  10653. (function (BABYLON) {
  10654. var BaseTexture = (function () {
  10655. function BaseTexture(scene) {
  10656. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10657. this.hasAlpha = false;
  10658. this.getAlphaFromRGB = false;
  10659. this.level = 1;
  10660. this.isCube = false;
  10661. this.isRenderTarget = false;
  10662. this.animations = new Array();
  10663. this.coordinatesIndex = 0;
  10664. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10665. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10666. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10667. this.anisotropicFilteringLevel = 4;
  10668. this._scene = scene;
  10669. this._scene.textures.push(this);
  10670. }
  10671. BaseTexture.prototype.getScene = function () {
  10672. return this._scene;
  10673. };
  10674. BaseTexture.prototype.getTextureMatrix = function () {
  10675. return null;
  10676. };
  10677. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10678. return null;
  10679. };
  10680. BaseTexture.prototype.getInternalTexture = function () {
  10681. return this._texture;
  10682. };
  10683. BaseTexture.prototype.isReady = function () {
  10684. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10685. return true;
  10686. }
  10687. if (this._texture) {
  10688. return this._texture.isReady;
  10689. }
  10690. return false;
  10691. };
  10692. BaseTexture.prototype.getSize = function () {
  10693. if (this._texture._width) {
  10694. return { width: this._texture._width, height: this._texture._height };
  10695. }
  10696. if (this._texture._size) {
  10697. return { width: this._texture._size, height: this._texture._size };
  10698. }
  10699. return { width: 0, height: 0 };
  10700. };
  10701. BaseTexture.prototype.getBaseSize = function () {
  10702. if (!this.isReady())
  10703. return { width: 0, height: 0 };
  10704. if (this._texture._size) {
  10705. return { width: this._texture._size, height: this._texture._size };
  10706. }
  10707. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10708. };
  10709. BaseTexture.prototype.scale = function (ratio) {
  10710. };
  10711. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10712. get: function () {
  10713. return false;
  10714. },
  10715. enumerable: true,
  10716. configurable: true
  10717. });
  10718. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10719. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10720. for (var index = 0; index < texturesCache.length; index++) {
  10721. var texturesCacheEntry = texturesCache[index];
  10722. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10723. texturesCache.splice(index, 1);
  10724. return;
  10725. }
  10726. }
  10727. };
  10728. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10729. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10730. for (var index = 0; index < texturesCache.length; index++) {
  10731. var texturesCacheEntry = texturesCache[index];
  10732. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10733. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10734. texturesCacheEntry.references++;
  10735. return texturesCacheEntry;
  10736. }
  10737. }
  10738. }
  10739. return null;
  10740. };
  10741. BaseTexture.prototype.delayLoad = function () {
  10742. };
  10743. BaseTexture.prototype.releaseInternalTexture = function () {
  10744. if (!this._texture) {
  10745. return;
  10746. }
  10747. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10748. this._texture.references--;
  10749. // Final reference ?
  10750. if (this._texture.references === 0) {
  10751. var index = texturesCache.indexOf(this._texture);
  10752. texturesCache.splice(index, 1);
  10753. this._scene.getEngine()._releaseTexture(this._texture);
  10754. delete this._texture;
  10755. }
  10756. };
  10757. BaseTexture.prototype.clone = function () {
  10758. return null;
  10759. };
  10760. BaseTexture.prototype.dispose = function () {
  10761. // Remove from scene
  10762. var index = this._scene.textures.indexOf(this);
  10763. if (index >= 0) {
  10764. this._scene.textures.splice(index, 1);
  10765. }
  10766. if (this._texture === undefined) {
  10767. return;
  10768. }
  10769. this.releaseInternalTexture();
  10770. // Callback
  10771. if (this.onDispose) {
  10772. this.onDispose();
  10773. }
  10774. };
  10775. return BaseTexture;
  10776. })();
  10777. BABYLON.BaseTexture = BaseTexture;
  10778. })(BABYLON || (BABYLON = {}));
  10779. //# sourceMappingURL=babylon.baseTexture.js.map
  10780. var BABYLON;
  10781. (function (BABYLON) {
  10782. var RenderingGroup = (function () {
  10783. function RenderingGroup(index, scene) {
  10784. this.index = index;
  10785. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10786. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10787. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10788. this._scene = scene;
  10789. }
  10790. RenderingGroup.prototype.render = function (customRenderFunction) {
  10791. if (customRenderFunction) {
  10792. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10793. return true;
  10794. }
  10795. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10796. return false;
  10797. }
  10798. var engine = this._scene.getEngine();
  10799. // Opaque
  10800. var subIndex;
  10801. var submesh;
  10802. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10803. submesh = this._opaqueSubMeshes.data[subIndex];
  10804. submesh.render();
  10805. }
  10806. // Alpha test
  10807. engine.setAlphaTesting(true);
  10808. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10809. submesh = this._alphaTestSubMeshes.data[subIndex];
  10810. submesh.render();
  10811. }
  10812. engine.setAlphaTesting(false);
  10813. // Transparent
  10814. if (this._transparentSubMeshes.length) {
  10815. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10816. submesh = this._transparentSubMeshes.data[subIndex];
  10817. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10818. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10819. }
  10820. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10821. sortedArray.sort(function (a, b) {
  10822. // Alpha index first
  10823. if (a._alphaIndex > b._alphaIndex) {
  10824. return 1;
  10825. }
  10826. if (a._alphaIndex < b._alphaIndex) {
  10827. return -1;
  10828. }
  10829. // Then distance to camera
  10830. if (a._distanceToCamera < b._distanceToCamera) {
  10831. return 1;
  10832. }
  10833. if (a._distanceToCamera > b._distanceToCamera) {
  10834. return -1;
  10835. }
  10836. return 0;
  10837. });
  10838. // Rendering
  10839. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10840. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10841. submesh = sortedArray[subIndex];
  10842. submesh.render();
  10843. }
  10844. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10845. }
  10846. return true;
  10847. };
  10848. RenderingGroup.prototype.prepare = function () {
  10849. this._opaqueSubMeshes.reset();
  10850. this._transparentSubMeshes.reset();
  10851. this._alphaTestSubMeshes.reset();
  10852. };
  10853. RenderingGroup.prototype.dispatch = function (subMesh) {
  10854. var material = subMesh.getMaterial();
  10855. var mesh = subMesh.getMesh();
  10856. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10857. this._transparentSubMeshes.push(subMesh);
  10858. } else if (material.needAlphaTesting()) {
  10859. this._alphaTestSubMeshes.push(subMesh);
  10860. } else {
  10861. this._opaqueSubMeshes.push(subMesh); // Opaque
  10862. }
  10863. };
  10864. return RenderingGroup;
  10865. })();
  10866. BABYLON.RenderingGroup = RenderingGroup;
  10867. })(BABYLON || (BABYLON = {}));
  10868. //# sourceMappingURL=babylon.renderingGroup.js.map
  10869. var BABYLON;
  10870. (function (BABYLON) {
  10871. var RenderingManager = (function () {
  10872. function RenderingManager(scene) {
  10873. this._renderingGroups = new Array();
  10874. this._scene = scene;
  10875. }
  10876. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10877. if (this._scene._activeParticleSystems.length === 0) {
  10878. return;
  10879. }
  10880. // Particles
  10881. var beforeParticlesDate = BABYLON.Tools.Now;
  10882. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10883. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10884. if (particleSystem.renderingGroupId !== index) {
  10885. continue;
  10886. }
  10887. this._clearDepthBuffer();
  10888. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10889. this._scene._activeParticles += particleSystem.render();
  10890. }
  10891. }
  10892. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10893. };
  10894. RenderingManager.prototype._renderSprites = function (index) {
  10895. if (this._scene.spriteManagers.length === 0) {
  10896. return;
  10897. }
  10898. // Sprites
  10899. var beforeSpritessDate = BABYLON.Tools.Now;
  10900. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  10901. var spriteManager = this._scene.spriteManagers[id];
  10902. if (spriteManager.renderingGroupId === index) {
  10903. this._clearDepthBuffer();
  10904. spriteManager.render();
  10905. }
  10906. }
  10907. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  10908. };
  10909. RenderingManager.prototype._clearDepthBuffer = function () {
  10910. if (this._depthBufferAlreadyCleaned) {
  10911. return;
  10912. }
  10913. this._scene.getEngine().clear(0, false, true);
  10914. this._depthBufferAlreadyCleaned = true;
  10915. };
  10916. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  10917. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  10918. this._depthBufferAlreadyCleaned = false;
  10919. var renderingGroup = this._renderingGroups[index];
  10920. if (renderingGroup) {
  10921. this._clearDepthBuffer();
  10922. if (!renderingGroup.render(customRenderFunction)) {
  10923. this._renderingGroups.splice(index, 1);
  10924. }
  10925. }
  10926. this._renderSprites(index);
  10927. if (renderParticles) {
  10928. this._renderParticles(index, activeMeshes);
  10929. }
  10930. }
  10931. };
  10932. RenderingManager.prototype.reset = function () {
  10933. for (var index in this._renderingGroups) {
  10934. var renderingGroup = this._renderingGroups[index];
  10935. renderingGroup.prepare();
  10936. }
  10937. };
  10938. RenderingManager.prototype.dispatch = function (subMesh) {
  10939. var mesh = subMesh.getMesh();
  10940. var renderingGroupId = mesh.renderingGroupId || 0;
  10941. if (!this._renderingGroups[renderingGroupId]) {
  10942. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  10943. }
  10944. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  10945. };
  10946. RenderingManager.MAX_RENDERINGGROUPS = 4;
  10947. return RenderingManager;
  10948. })();
  10949. BABYLON.RenderingManager = RenderingManager;
  10950. })(BABYLON || (BABYLON = {}));
  10951. //# sourceMappingURL=babylon.renderingManager.js.map
  10952. var BABYLON;
  10953. (function (BABYLON) {
  10954. var Texture = (function (_super) {
  10955. __extends(Texture, _super);
  10956. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  10957. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  10958. if (typeof onLoad === "undefined") { onLoad = null; }
  10959. if (typeof onError === "undefined") { onError = null; }
  10960. if (typeof buffer === "undefined") { buffer = null; }
  10961. if (typeof deleteBuffer === "undefined") { deleteBuffer = false; }
  10962. _super.call(this, scene);
  10963. this.uOffset = 0;
  10964. this.vOffset = 0;
  10965. this.uScale = 1.0;
  10966. this.vScale = 1.0;
  10967. this.uAng = 0;
  10968. this.vAng = 0;
  10969. this.wAng = 0;
  10970. this.name = url;
  10971. this.url = url;
  10972. this._noMipmap = noMipmap;
  10973. this._invertY = invertY;
  10974. this._samplingMode = samplingMode;
  10975. this._buffer = buffer;
  10976. this._deleteBuffer = deleteBuffer;
  10977. if (!url) {
  10978. return;
  10979. }
  10980. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  10981. if (!this._texture) {
  10982. if (!scene.useDelayedTextureLoading) {
  10983. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  10984. if (deleteBuffer) {
  10985. delete this._buffer;
  10986. }
  10987. } else {
  10988. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  10989. }
  10990. }
  10991. }
  10992. Texture.prototype.delayLoad = function () {
  10993. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10994. return;
  10995. }
  10996. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10997. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  10998. if (!this._texture) {
  10999. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11000. if (this._deleteBuffer) {
  11001. delete this._buffer;
  11002. }
  11003. }
  11004. };
  11005. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11006. x -= this.uOffset + 0.5;
  11007. y -= this.vOffset + 0.5;
  11008. z -= 0.5;
  11009. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11010. t.x *= this.uScale;
  11011. t.y *= this.vScale;
  11012. t.x += 0.5;
  11013. t.y += 0.5;
  11014. t.z += 0.5;
  11015. };
  11016. Texture.prototype.getTextureMatrix = function () {
  11017. 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) {
  11018. return this._cachedTextureMatrix;
  11019. }
  11020. this._cachedUOffset = this.uOffset;
  11021. this._cachedVOffset = this.vOffset;
  11022. this._cachedUScale = this.uScale;
  11023. this._cachedVScale = this.vScale;
  11024. this._cachedUAng = this.uAng;
  11025. this._cachedVAng = this.vAng;
  11026. this._cachedWAng = this.wAng;
  11027. if (!this._cachedTextureMatrix) {
  11028. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11029. this._rowGenerationMatrix = new BABYLON.Matrix();
  11030. this._t0 = BABYLON.Vector3.Zero();
  11031. this._t1 = BABYLON.Vector3.Zero();
  11032. this._t2 = BABYLON.Vector3.Zero();
  11033. }
  11034. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11035. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11036. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11037. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11038. this._t1.subtractInPlace(this._t0);
  11039. this._t2.subtractInPlace(this._t0);
  11040. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11041. this._cachedTextureMatrix.m[0] = this._t1.x;
  11042. this._cachedTextureMatrix.m[1] = this._t1.y;
  11043. this._cachedTextureMatrix.m[2] = this._t1.z;
  11044. this._cachedTextureMatrix.m[4] = this._t2.x;
  11045. this._cachedTextureMatrix.m[5] = this._t2.y;
  11046. this._cachedTextureMatrix.m[6] = this._t2.z;
  11047. this._cachedTextureMatrix.m[8] = this._t0.x;
  11048. this._cachedTextureMatrix.m[9] = this._t0.y;
  11049. this._cachedTextureMatrix.m[10] = this._t0.z;
  11050. return this._cachedTextureMatrix;
  11051. };
  11052. Texture.prototype.getReflectionTextureMatrix = function () {
  11053. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11054. return this._cachedTextureMatrix;
  11055. }
  11056. if (!this._cachedTextureMatrix) {
  11057. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11058. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11059. }
  11060. this._cachedCoordinatesMode = this.coordinatesMode;
  11061. switch (this.coordinatesMode) {
  11062. case BABYLON.Texture.SPHERICAL_MODE:
  11063. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11064. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11065. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11066. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11067. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11068. break;
  11069. case BABYLON.Texture.PLANAR_MODE:
  11070. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11071. this._cachedTextureMatrix[0] = this.uScale;
  11072. this._cachedTextureMatrix[5] = this.vScale;
  11073. this._cachedTextureMatrix[12] = this.uOffset;
  11074. this._cachedTextureMatrix[13] = this.vOffset;
  11075. break;
  11076. case BABYLON.Texture.PROJECTION_MODE:
  11077. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11078. this._projectionModeMatrix.m[0] = 0.5;
  11079. this._projectionModeMatrix.m[5] = -0.5;
  11080. this._projectionModeMatrix.m[10] = 0.0;
  11081. this._projectionModeMatrix.m[12] = 0.5;
  11082. this._projectionModeMatrix.m[13] = 0.5;
  11083. this._projectionModeMatrix.m[14] = 1.0;
  11084. this._projectionModeMatrix.m[15] = 1.0;
  11085. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11086. break;
  11087. default:
  11088. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11089. break;
  11090. }
  11091. return this._cachedTextureMatrix;
  11092. };
  11093. Texture.prototype.clone = function () {
  11094. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  11095. // Base texture
  11096. newTexture.hasAlpha = this.hasAlpha;
  11097. newTexture.level = this.level;
  11098. newTexture.wrapU = this.wrapU;
  11099. newTexture.wrapV = this.wrapV;
  11100. newTexture.coordinatesIndex = this.coordinatesIndex;
  11101. newTexture.coordinatesMode = this.coordinatesMode;
  11102. // Texture
  11103. newTexture.uOffset = this.uOffset;
  11104. newTexture.vOffset = this.vOffset;
  11105. newTexture.uScale = this.uScale;
  11106. newTexture.vScale = this.vScale;
  11107. newTexture.uAng = this.uAng;
  11108. newTexture.vAng = this.vAng;
  11109. newTexture.wAng = this.wAng;
  11110. return newTexture;
  11111. };
  11112. // Statics
  11113. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11114. if (typeof samplingMode === "undefined") { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11115. if (typeof onLoad === "undefined") { onLoad = null; }
  11116. if (typeof onError === "undefined") { onError = null; }
  11117. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11118. };
  11119. Texture.NEAREST_SAMPLINGMODE = 1;
  11120. Texture.BILINEAR_SAMPLINGMODE = 2;
  11121. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11122. Texture.EXPLICIT_MODE = 0;
  11123. Texture.SPHERICAL_MODE = 1;
  11124. Texture.PLANAR_MODE = 2;
  11125. Texture.CUBIC_MODE = 3;
  11126. Texture.PROJECTION_MODE = 4;
  11127. Texture.SKYBOX_MODE = 5;
  11128. Texture.CLAMP_ADDRESSMODE = 0;
  11129. Texture.WRAP_ADDRESSMODE = 1;
  11130. Texture.MIRROR_ADDRESSMODE = 2;
  11131. return Texture;
  11132. })(BABYLON.BaseTexture);
  11133. BABYLON.Texture = Texture;
  11134. })(BABYLON || (BABYLON = {}));
  11135. //# sourceMappingURL=babylon.texture.js.map
  11136. var BABYLON;
  11137. (function (BABYLON) {
  11138. var CubeTexture = (function (_super) {
  11139. __extends(CubeTexture, _super);
  11140. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11141. _super.call(this, scene);
  11142. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11143. this.name = rootUrl;
  11144. this.url = rootUrl;
  11145. this._noMipmap = noMipmap;
  11146. this.hasAlpha = false;
  11147. this._texture = this._getFromCache(rootUrl, noMipmap);
  11148. if (!extensions) {
  11149. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11150. }
  11151. this._extensions = extensions;
  11152. if (!this._texture) {
  11153. if (!scene.useDelayedTextureLoading) {
  11154. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11155. } else {
  11156. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11157. }
  11158. }
  11159. this.isCube = true;
  11160. this._textureMatrix = BABYLON.Matrix.Identity();
  11161. }
  11162. CubeTexture.prototype.clone = function () {
  11163. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11164. // Base texture
  11165. newTexture.level = this.level;
  11166. newTexture.wrapU = this.wrapU;
  11167. newTexture.wrapV = this.wrapV;
  11168. newTexture.coordinatesIndex = this.coordinatesIndex;
  11169. newTexture.coordinatesMode = this.coordinatesMode;
  11170. return newTexture;
  11171. };
  11172. // Methods
  11173. CubeTexture.prototype.delayLoad = function () {
  11174. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11175. return;
  11176. }
  11177. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11178. this._texture = this._getFromCache(this.url, this._noMipmap);
  11179. if (!this._texture) {
  11180. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11181. }
  11182. };
  11183. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11184. return this._textureMatrix;
  11185. };
  11186. return CubeTexture;
  11187. })(BABYLON.BaseTexture);
  11188. BABYLON.CubeTexture = CubeTexture;
  11189. })(BABYLON || (BABYLON = {}));
  11190. //# sourceMappingURL=babylon.cubeTexture.js.map
  11191. var BABYLON;
  11192. (function (BABYLON) {
  11193. var RenderTargetTexture = (function (_super) {
  11194. __extends(RenderTargetTexture, _super);
  11195. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  11196. if (typeof doNotChangeAspectRatio === "undefined") { doNotChangeAspectRatio = true; }
  11197. _super.call(this, null, scene, !generateMipMaps);
  11198. this.renderList = new Array();
  11199. this.renderParticles = true;
  11200. this.renderSprites = false;
  11201. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11202. this._currentRefreshId = -1;
  11203. this._refreshRate = 1;
  11204. this.name = name;
  11205. this.isRenderTarget = true;
  11206. this._size = size;
  11207. this._generateMipMaps = generateMipMaps;
  11208. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11209. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11210. // Rendering groups
  11211. this._renderingManager = new BABYLON.RenderingManager(scene);
  11212. }
  11213. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11214. this._currentRefreshId = -1;
  11215. };
  11216. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11217. get: function () {
  11218. return this._refreshRate;
  11219. },
  11220. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11221. set: function (value) {
  11222. this._refreshRate = value;
  11223. this.resetRefreshCounter();
  11224. },
  11225. enumerable: true,
  11226. configurable: true
  11227. });
  11228. RenderTargetTexture.prototype._shouldRender = function () {
  11229. if (this._currentRefreshId === -1) {
  11230. this._currentRefreshId = 1;
  11231. return true;
  11232. }
  11233. if (this.refreshRate == this._currentRefreshId) {
  11234. this._currentRefreshId = 1;
  11235. return true;
  11236. }
  11237. this._currentRefreshId++;
  11238. return false;
  11239. };
  11240. RenderTargetTexture.prototype.isReady = function () {
  11241. if (!this.getScene().renderTargetsEnabled) {
  11242. return false;
  11243. }
  11244. return _super.prototype.isReady.call(this);
  11245. };
  11246. RenderTargetTexture.prototype.getRenderSize = function () {
  11247. return this._size;
  11248. };
  11249. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11250. get: function () {
  11251. return true;
  11252. },
  11253. enumerable: true,
  11254. configurable: true
  11255. });
  11256. RenderTargetTexture.prototype.scale = function (ratio) {
  11257. var newSize = this._size * ratio;
  11258. this.resize(newSize, this._generateMipMaps);
  11259. };
  11260. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11261. this.releaseInternalTexture();
  11262. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11263. };
  11264. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11265. var scene = this.getScene();
  11266. var engine = scene.getEngine();
  11267. if (this._waitingRenderList) {
  11268. this.renderList = [];
  11269. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11270. var id = this._waitingRenderList[index];
  11271. this.renderList.push(scene.getMeshByID(id));
  11272. }
  11273. delete this._waitingRenderList;
  11274. }
  11275. if (!this.renderList) {
  11276. return;
  11277. }
  11278. // Bind
  11279. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11280. engine.bindFramebuffer(this._texture);
  11281. }
  11282. // Clear
  11283. engine.clear(scene.clearColor, true, true);
  11284. this._renderingManager.reset();
  11285. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11286. var mesh = this.renderList[meshIndex];
  11287. if (mesh) {
  11288. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11289. // Reset _currentRefreshId
  11290. this.resetRefreshCounter();
  11291. continue;
  11292. }
  11293. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11294. mesh._activate(scene.getRenderId());
  11295. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11296. var subMesh = mesh.subMeshes[subIndex];
  11297. scene._activeVertices += subMesh.indexCount;
  11298. this._renderingManager.dispatch(subMesh);
  11299. }
  11300. }
  11301. }
  11302. }
  11303. if (!this._doNotChangeAspectRatio) {
  11304. scene.updateTransformMatrix(true);
  11305. }
  11306. if (this.onBeforeRender) {
  11307. this.onBeforeRender();
  11308. }
  11309. // Render
  11310. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11311. if (useCameraPostProcess) {
  11312. scene.postProcessManager._finalizeFrame(false, this._texture);
  11313. }
  11314. if (this.onAfterRender) {
  11315. this.onAfterRender();
  11316. }
  11317. // Unbind
  11318. engine.unBindFramebuffer(this._texture);
  11319. if (!this._doNotChangeAspectRatio) {
  11320. scene.updateTransformMatrix(true);
  11321. }
  11322. };
  11323. RenderTargetTexture.prototype.clone = function () {
  11324. var textureSize = this.getSize();
  11325. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11326. // Base texture
  11327. newTexture.hasAlpha = this.hasAlpha;
  11328. newTexture.level = this.level;
  11329. // RenderTarget Texture
  11330. newTexture.coordinatesMode = this.coordinatesMode;
  11331. newTexture.renderList = this.renderList.slice(0);
  11332. return newTexture;
  11333. };
  11334. return RenderTargetTexture;
  11335. })(BABYLON.Texture);
  11336. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11337. })(BABYLON || (BABYLON = {}));
  11338. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11339. var BABYLON;
  11340. (function (BABYLON) {
  11341. var ProceduralTexture = (function (_super) {
  11342. __extends(ProceduralTexture, _super);
  11343. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11344. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  11345. _super.call(this, null, scene, !generateMipMaps);
  11346. this._currentRefreshId = -1;
  11347. this._refreshRate = 1;
  11348. this._vertexDeclaration = [2];
  11349. this._vertexStrideSize = 2 * 4;
  11350. this._uniforms = new Array();
  11351. this._samplers = new Array();
  11352. this._textures = new Array();
  11353. this._floats = new Array();
  11354. this._floatsArrays = {};
  11355. this._colors3 = new Array();
  11356. this._colors4 = new Array();
  11357. this._vectors2 = new Array();
  11358. this._vectors3 = new Array();
  11359. this._matrices = new Array();
  11360. this._fallbackTextureUsed = false;
  11361. scene._proceduralTextures.push(this);
  11362. this.name = name;
  11363. this.isRenderTarget = true;
  11364. this._size = size;
  11365. this._generateMipMaps = generateMipMaps;
  11366. this.setFragment(fragment);
  11367. this._fallbackTexture = fallbackTexture;
  11368. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11369. // VBO
  11370. var vertices = [];
  11371. vertices.push(1, 1);
  11372. vertices.push(-1, 1);
  11373. vertices.push(-1, -1);
  11374. vertices.push(1, -1);
  11375. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11376. // Indices
  11377. var indices = [];
  11378. indices.push(0);
  11379. indices.push(1);
  11380. indices.push(2);
  11381. indices.push(0);
  11382. indices.push(2);
  11383. indices.push(3);
  11384. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11385. }
  11386. ProceduralTexture.prototype.reset = function () {
  11387. if (this._effect === undefined) {
  11388. return;
  11389. }
  11390. var engine = this.getScene().getEngine();
  11391. engine._releaseEffect(this._effect);
  11392. };
  11393. ProceduralTexture.prototype.isReady = function () {
  11394. var _this = this;
  11395. var engine = this.getScene().getEngine();
  11396. var shaders;
  11397. if (!this._fragment) {
  11398. return false;
  11399. }
  11400. if (this._fallbackTextureUsed) {
  11401. return true;
  11402. }
  11403. if (this._fragment.fragmentElement !== undefined) {
  11404. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11405. } else {
  11406. shaders = { vertex: "procedural", fragment: this._fragment };
  11407. }
  11408. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11409. _this.releaseInternalTexture();
  11410. if (_this._fallbackTexture) {
  11411. _this._texture = _this._fallbackTexture._texture;
  11412. _this._texture.references++;
  11413. }
  11414. _this._fallbackTextureUsed = true;
  11415. });
  11416. return this._effect.isReady();
  11417. };
  11418. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11419. this._currentRefreshId = -1;
  11420. };
  11421. ProceduralTexture.prototype.setFragment = function (fragment) {
  11422. this._fragment = fragment;
  11423. };
  11424. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11425. get: function () {
  11426. return this._refreshRate;
  11427. },
  11428. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11429. set: function (value) {
  11430. this._refreshRate = value;
  11431. this.resetRefreshCounter();
  11432. },
  11433. enumerable: true,
  11434. configurable: true
  11435. });
  11436. ProceduralTexture.prototype._shouldRender = function () {
  11437. if (!this.isReady() || !this._texture) {
  11438. return false;
  11439. }
  11440. if (this._fallbackTextureUsed) {
  11441. return false;
  11442. }
  11443. if (this._currentRefreshId === -1) {
  11444. this._currentRefreshId = 1;
  11445. return true;
  11446. }
  11447. if (this.refreshRate === this._currentRefreshId) {
  11448. this._currentRefreshId = 1;
  11449. return true;
  11450. }
  11451. this._currentRefreshId++;
  11452. return false;
  11453. };
  11454. ProceduralTexture.prototype.getRenderSize = function () {
  11455. return this._size;
  11456. };
  11457. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11458. if (this._fallbackTextureUsed) {
  11459. return;
  11460. }
  11461. this.releaseInternalTexture();
  11462. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11463. };
  11464. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11465. if (this._uniforms.indexOf(uniformName) === -1) {
  11466. this._uniforms.push(uniformName);
  11467. }
  11468. };
  11469. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11470. if (this._samplers.indexOf(name) === -1) {
  11471. this._samplers.push(name);
  11472. }
  11473. this._textures[name] = texture;
  11474. return this;
  11475. };
  11476. ProceduralTexture.prototype.setFloat = function (name, value) {
  11477. this._checkUniform(name);
  11478. this._floats[name] = value;
  11479. return this;
  11480. };
  11481. ProceduralTexture.prototype.setFloats = function (name, value) {
  11482. this._checkUniform(name);
  11483. this._floatsArrays[name] = value;
  11484. return this;
  11485. };
  11486. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11487. this._checkUniform(name);
  11488. this._colors3[name] = value;
  11489. return this;
  11490. };
  11491. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11492. this._checkUniform(name);
  11493. this._colors4[name] = value;
  11494. return this;
  11495. };
  11496. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11497. this._checkUniform(name);
  11498. this._vectors2[name] = value;
  11499. return this;
  11500. };
  11501. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11502. this._checkUniform(name);
  11503. this._vectors3[name] = value;
  11504. return this;
  11505. };
  11506. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11507. this._checkUniform(name);
  11508. this._matrices[name] = value;
  11509. return this;
  11510. };
  11511. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11512. var scene = this.getScene();
  11513. var engine = scene.getEngine();
  11514. engine.bindFramebuffer(this._texture);
  11515. // Clear
  11516. engine.clear(scene.clearColor, true, true);
  11517. // Render
  11518. engine.enableEffect(this._effect);
  11519. engine.setState(false);
  11520. for (var name in this._textures) {
  11521. this._effect.setTexture(name, this._textures[name]);
  11522. }
  11523. for (name in this._floats) {
  11524. this._effect.setFloat(name, this._floats[name]);
  11525. }
  11526. for (name in this._floatsArrays) {
  11527. this._effect.setArray(name, this._floatsArrays[name]);
  11528. }
  11529. for (name in this._colors3) {
  11530. this._effect.setColor3(name, this._colors3[name]);
  11531. }
  11532. for (name in this._colors4) {
  11533. var color = this._colors4[name];
  11534. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11535. }
  11536. for (name in this._vectors2) {
  11537. this._effect.setVector2(name, this._vectors2[name]);
  11538. }
  11539. for (name in this._vectors3) {
  11540. this._effect.setVector3(name, this._vectors3[name]);
  11541. }
  11542. for (name in this._matrices) {
  11543. this._effect.setMatrix(name, this._matrices[name]);
  11544. }
  11545. // VBOs
  11546. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11547. // Draw order
  11548. engine.draw(true, 0, 6);
  11549. // Unbind
  11550. engine.unBindFramebuffer(this._texture);
  11551. };
  11552. ProceduralTexture.prototype.clone = function () {
  11553. var textureSize = this.getSize();
  11554. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11555. // Base texture
  11556. newTexture.hasAlpha = this.hasAlpha;
  11557. newTexture.level = this.level;
  11558. // RenderTarget Texture
  11559. newTexture.coordinatesMode = this.coordinatesMode;
  11560. return newTexture;
  11561. };
  11562. ProceduralTexture.prototype.dispose = function () {
  11563. var index = this.getScene()._proceduralTextures.indexOf(this);
  11564. if (index >= 0) {
  11565. this.getScene()._proceduralTextures.splice(index, 1);
  11566. }
  11567. _super.prototype.dispose.call(this);
  11568. };
  11569. return ProceduralTexture;
  11570. })(BABYLON.Texture);
  11571. BABYLON.ProceduralTexture = ProceduralTexture;
  11572. })(BABYLON || (BABYLON = {}));
  11573. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11574. var BABYLON;
  11575. (function (BABYLON) {
  11576. var WoodProceduralTexture = (function (_super) {
  11577. __extends(WoodProceduralTexture, _super);
  11578. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11579. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11580. this._ampScale = 100.0;
  11581. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11582. this.updateShaderUniforms();
  11583. this.refreshRate = 0;
  11584. }
  11585. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11586. this.setFloat("ampScale", this._ampScale);
  11587. this.setColor3("woodColor", this._woodColor);
  11588. };
  11589. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11590. get: function () {
  11591. return this._ampScale;
  11592. },
  11593. set: function (value) {
  11594. this._ampScale = value;
  11595. this.updateShaderUniforms();
  11596. },
  11597. enumerable: true,
  11598. configurable: true
  11599. });
  11600. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11601. get: function () {
  11602. return this._woodColor;
  11603. },
  11604. set: function (value) {
  11605. this._woodColor = value;
  11606. this.updateShaderUniforms();
  11607. },
  11608. enumerable: true,
  11609. configurable: true
  11610. });
  11611. return WoodProceduralTexture;
  11612. })(BABYLON.ProceduralTexture);
  11613. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11614. var FireProceduralTexture = (function (_super) {
  11615. __extends(FireProceduralTexture, _super);
  11616. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11617. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11618. this._time = 0.0;
  11619. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11620. this._shift = 1.6;
  11621. this._autoGenerateTime = true;
  11622. this._alphaThreshold = 0.5;
  11623. this._fireColors = FireProceduralTexture.RedFireColors;
  11624. this.updateShaderUniforms();
  11625. this.refreshRate = 1;
  11626. }
  11627. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11628. this.setFloat("time", this._time);
  11629. this.setVector2("speed", this._speed);
  11630. this.setFloat("shift", this._shift);
  11631. this.setColor3("c1", this._fireColors[0]);
  11632. this.setColor3("c2", this._fireColors[1]);
  11633. this.setColor3("c3", this._fireColors[2]);
  11634. this.setColor3("c4", this._fireColors[3]);
  11635. this.setColor3("c5", this._fireColors[4]);
  11636. this.setColor3("c6", this._fireColors[5]);
  11637. this.setFloat("alphaThreshold", this._alphaThreshold);
  11638. };
  11639. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11640. if (this._autoGenerateTime) {
  11641. this._time += this.getScene().getAnimationRatio() * 0.03;
  11642. this.updateShaderUniforms();
  11643. }
  11644. _super.prototype.render.call(this, useCameraPostProcess);
  11645. };
  11646. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11647. get: function () {
  11648. return [
  11649. new BABYLON.Color3(0.5, 0.0, 1.0),
  11650. new BABYLON.Color3(0.9, 0.0, 1.0),
  11651. new BABYLON.Color3(0.2, 0.0, 1.0),
  11652. new BABYLON.Color3(1.0, 0.9, 1.0),
  11653. new BABYLON.Color3(0.1, 0.1, 1.0),
  11654. new BABYLON.Color3(0.9, 0.9, 1.0)
  11655. ];
  11656. },
  11657. enumerable: true,
  11658. configurable: true
  11659. });
  11660. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11661. get: function () {
  11662. return [
  11663. new BABYLON.Color3(0.5, 1.0, 0.0),
  11664. new BABYLON.Color3(0.5, 1.0, 0.0),
  11665. new BABYLON.Color3(0.3, 0.4, 0.0),
  11666. new BABYLON.Color3(0.5, 1.0, 0.0),
  11667. new BABYLON.Color3(0.2, 0.0, 0.0),
  11668. new BABYLON.Color3(0.5, 1.0, 0.0)
  11669. ];
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11675. get: function () {
  11676. return [
  11677. new BABYLON.Color3(0.5, 0.0, 0.1),
  11678. new BABYLON.Color3(0.9, 0.0, 0.0),
  11679. new BABYLON.Color3(0.2, 0.0, 0.0),
  11680. new BABYLON.Color3(1.0, 0.9, 0.0),
  11681. new BABYLON.Color3(0.1, 0.1, 0.1),
  11682. new BABYLON.Color3(0.9, 0.9, 0.9)
  11683. ];
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11689. get: function () {
  11690. return [
  11691. new BABYLON.Color3(0.1, 0.0, 0.5),
  11692. new BABYLON.Color3(0.0, 0.0, 0.5),
  11693. new BABYLON.Color3(0.1, 0.0, 0.2),
  11694. new BABYLON.Color3(0.0, 0.0, 1.0),
  11695. new BABYLON.Color3(0.1, 0.2, 0.3),
  11696. new BABYLON.Color3(0.0, 0.2, 0.9)
  11697. ];
  11698. },
  11699. enumerable: true,
  11700. configurable: true
  11701. });
  11702. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11703. get: function () {
  11704. return this._fireColors;
  11705. },
  11706. set: function (value) {
  11707. this._fireColors = value;
  11708. this.updateShaderUniforms();
  11709. },
  11710. enumerable: true,
  11711. configurable: true
  11712. });
  11713. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11714. get: function () {
  11715. return this._time;
  11716. },
  11717. set: function (value) {
  11718. this._time = value;
  11719. this.updateShaderUniforms();
  11720. },
  11721. enumerable: true,
  11722. configurable: true
  11723. });
  11724. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11725. get: function () {
  11726. return this._speed;
  11727. },
  11728. set: function (value) {
  11729. this._speed = value;
  11730. this.updateShaderUniforms();
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11736. get: function () {
  11737. return this._shift;
  11738. },
  11739. set: function (value) {
  11740. this._shift = value;
  11741. this.updateShaderUniforms();
  11742. },
  11743. enumerable: true,
  11744. configurable: true
  11745. });
  11746. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11747. get: function () {
  11748. return this._alphaThreshold;
  11749. },
  11750. set: function (value) {
  11751. this._alphaThreshold = value;
  11752. this.updateShaderUniforms();
  11753. },
  11754. enumerable: true,
  11755. configurable: true
  11756. });
  11757. return FireProceduralTexture;
  11758. })(BABYLON.ProceduralTexture);
  11759. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11760. var CloudProceduralTexture = (function (_super) {
  11761. __extends(CloudProceduralTexture, _super);
  11762. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11763. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11764. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11765. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11766. this.updateShaderUniforms();
  11767. this.refreshRate = 0;
  11768. }
  11769. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11770. this.setColor3("skyColor", this._skyColor);
  11771. this.setColor3("cloudColor", this._cloudColor);
  11772. };
  11773. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11774. get: function () {
  11775. return this._skyColor;
  11776. },
  11777. set: function (value) {
  11778. this._skyColor = value;
  11779. this.updateShaderUniforms();
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11785. get: function () {
  11786. return this._cloudColor;
  11787. },
  11788. set: function (value) {
  11789. this._cloudColor = value;
  11790. this.updateShaderUniforms();
  11791. },
  11792. enumerable: true,
  11793. configurable: true
  11794. });
  11795. return CloudProceduralTexture;
  11796. })(BABYLON.ProceduralTexture);
  11797. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11798. var GrassProceduralTexture = (function (_super) {
  11799. __extends(GrassProceduralTexture, _super);
  11800. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11801. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11802. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11803. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11804. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11805. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11806. this._grassColors = [
  11807. new BABYLON.Color3(0.29, 0.38, 0.02),
  11808. new BABYLON.Color3(0.36, 0.49, 0.09),
  11809. new BABYLON.Color3(0.51, 0.6, 0.28)
  11810. ];
  11811. this.updateShaderUniforms();
  11812. this.refreshRate = 0;
  11813. }
  11814. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11815. this.setColor3("herb1Color", this._grassColors[0]);
  11816. this.setColor3("herb2Color", this._grassColors[1]);
  11817. this.setColor3("herb3Color", this._grassColors[2]);
  11818. this.setColor3("groundColor", this._groundColor);
  11819. };
  11820. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11821. get: function () {
  11822. return this._grassColors;
  11823. },
  11824. set: function (value) {
  11825. this._grassColors = value;
  11826. this.updateShaderUniforms();
  11827. },
  11828. enumerable: true,
  11829. configurable: true
  11830. });
  11831. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11832. get: function () {
  11833. return this._groundColor;
  11834. },
  11835. set: function (value) {
  11836. this.groundColor = value;
  11837. this.updateShaderUniforms();
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. return GrassProceduralTexture;
  11843. })(BABYLON.ProceduralTexture);
  11844. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11845. var RoadProceduralTexture = (function (_super) {
  11846. __extends(RoadProceduralTexture, _super);
  11847. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11848. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11849. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11850. this.updateShaderUniforms();
  11851. this.refreshRate = 0;
  11852. }
  11853. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11854. this.setColor3("roadColor", this._roadColor);
  11855. };
  11856. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11857. get: function () {
  11858. return this._roadColor;
  11859. },
  11860. set: function (value) {
  11861. this._roadColor = value;
  11862. this.updateShaderUniforms();
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. return RoadProceduralTexture;
  11868. })(BABYLON.ProceduralTexture);
  11869. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11870. var BrickProceduralTexture = (function (_super) {
  11871. __extends(BrickProceduralTexture, _super);
  11872. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11873. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11874. this._numberOfBricksHeight = 15;
  11875. this._numberOfBricksWidth = 5;
  11876. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11877. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11878. this.updateShaderUniforms();
  11879. this.refreshRate = 0;
  11880. }
  11881. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11882. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11883. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11884. this.setColor3("brickColor", this._brickColor);
  11885. this.setColor3("jointColor", this._jointColor);
  11886. };
  11887. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11888. get: function () {
  11889. return this._numberOfBricksHeight;
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  11895. set: function (value) {
  11896. this._numberOfBricksHeight = value;
  11897. this.updateShaderUniforms();
  11898. },
  11899. enumerable: true,
  11900. configurable: true
  11901. });
  11902. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  11903. get: function () {
  11904. return this._numberOfBricksWidth;
  11905. },
  11906. set: function (value) {
  11907. this._numberOfBricksHeight = value;
  11908. this.updateShaderUniforms();
  11909. },
  11910. enumerable: true,
  11911. configurable: true
  11912. });
  11913. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  11914. get: function () {
  11915. return this._jointColor;
  11916. },
  11917. set: function (value) {
  11918. this._jointColor = value;
  11919. this.updateShaderUniforms();
  11920. },
  11921. enumerable: true,
  11922. configurable: true
  11923. });
  11924. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  11925. get: function () {
  11926. return this._brickColor;
  11927. },
  11928. set: function (value) {
  11929. this._brickColor = value;
  11930. this.updateShaderUniforms();
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. return BrickProceduralTexture;
  11936. })(BABYLON.ProceduralTexture);
  11937. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  11938. var MarbleProceduralTexture = (function (_super) {
  11939. __extends(MarbleProceduralTexture, _super);
  11940. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11941. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  11942. this._numberOfTilesHeight = 3;
  11943. this._numberOfTilesWidth = 3;
  11944. this._amplitude = 9.0;
  11945. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11946. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11947. this.updateShaderUniforms();
  11948. this.refreshRate = 0;
  11949. }
  11950. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  11951. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  11952. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  11953. this.setFloat("amplitude", this._amplitude);
  11954. this.setColor3("marbleColor", this._marbleColor);
  11955. this.setColor3("jointColor", this._jointColor);
  11956. };
  11957. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  11958. get: function () {
  11959. return this._numberOfTilesHeight;
  11960. },
  11961. set: function (value) {
  11962. this._numberOfTilesHeight = value;
  11963. this.updateShaderUniforms();
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  11969. get: function () {
  11970. return this._numberOfTilesWidth;
  11971. },
  11972. set: function (value) {
  11973. this._numberOfTilesWidth = value;
  11974. this.updateShaderUniforms();
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  11980. get: function () {
  11981. return this._jointColor;
  11982. },
  11983. set: function (value) {
  11984. this._jointColor = value;
  11985. this.updateShaderUniforms();
  11986. },
  11987. enumerable: true,
  11988. configurable: true
  11989. });
  11990. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  11991. get: function () {
  11992. return this._marbleColor;
  11993. },
  11994. set: function (value) {
  11995. this._marbleColor = value;
  11996. this.updateShaderUniforms();
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. return MarbleProceduralTexture;
  12002. })(BABYLON.ProceduralTexture);
  12003. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12004. })(BABYLON || (BABYLON = {}));
  12005. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12006. var BABYLON;
  12007. (function (BABYLON) {
  12008. var CustomProceduralTexture = (function (_super) {
  12009. __extends(CustomProceduralTexture, _super);
  12010. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12011. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12012. this._animate = true;
  12013. this._time = 0;
  12014. this._texturePath = texturePath;
  12015. //Try to load json
  12016. this.loadJson(texturePath);
  12017. this.refreshRate = 1;
  12018. }
  12019. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12020. var _this = this;
  12021. var that = this;
  12022. function noConfigFile() {
  12023. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12024. try {
  12025. that.setFragment(that._texturePath);
  12026. } catch (ex) {
  12027. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12028. }
  12029. }
  12030. var configFileUrl = jsonUrl + "/config.json";
  12031. var xhr = new XMLHttpRequest();
  12032. xhr.open("GET", configFileUrl, true);
  12033. xhr.addEventListener("load", function () {
  12034. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12035. try {
  12036. _this._config = JSON.parse(xhr.response);
  12037. _this.updateShaderUniforms();
  12038. _this.updateTextures();
  12039. _this.setFragment(_this._texturePath + "/custom");
  12040. _this._animate = _this._config.animate;
  12041. _this.refreshRate = _this._config.refreshrate;
  12042. } catch (ex) {
  12043. noConfigFile();
  12044. }
  12045. } else {
  12046. noConfigFile();
  12047. }
  12048. }, false);
  12049. xhr.addEventListener("error", function (event) {
  12050. noConfigFile();
  12051. }, false);
  12052. try {
  12053. xhr.send();
  12054. } catch (ex) {
  12055. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12056. }
  12057. };
  12058. CustomProceduralTexture.prototype.isReady = function () {
  12059. if (!_super.prototype.isReady.call(this)) {
  12060. return false;
  12061. }
  12062. for (var name in this._textures) {
  12063. var texture = this._textures[name];
  12064. if (!texture.isReady()) {
  12065. return false;
  12066. }
  12067. }
  12068. return true;
  12069. };
  12070. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12071. if (this._animate) {
  12072. this._time += this.getScene().getAnimationRatio() * 0.03;
  12073. this.updateShaderUniforms();
  12074. }
  12075. _super.prototype.render.call(this, useCameraPostProcess);
  12076. };
  12077. CustomProceduralTexture.prototype.updateTextures = function () {
  12078. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12079. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12080. }
  12081. };
  12082. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12083. if (this._config) {
  12084. for (var j = 0; j < this._config.uniforms.length; j++) {
  12085. var uniform = this._config.uniforms[j];
  12086. switch (uniform.type) {
  12087. case "float":
  12088. this.setFloat(uniform.name, uniform.value);
  12089. break;
  12090. case "color3":
  12091. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12092. break;
  12093. case "color4":
  12094. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12095. break;
  12096. case "vector2":
  12097. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12098. break;
  12099. case "vector3":
  12100. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12101. break;
  12102. }
  12103. }
  12104. }
  12105. this.setFloat("time", this._time);
  12106. };
  12107. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12108. get: function () {
  12109. return this._animate;
  12110. },
  12111. set: function (value) {
  12112. this._animate = value;
  12113. },
  12114. enumerable: true,
  12115. configurable: true
  12116. });
  12117. return CustomProceduralTexture;
  12118. })(BABYLON.ProceduralTexture);
  12119. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12120. })(BABYLON || (BABYLON = {}));
  12121. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12122. var BABYLON;
  12123. (function (BABYLON) {
  12124. var MirrorTexture = (function (_super) {
  12125. __extends(MirrorTexture, _super);
  12126. function MirrorTexture(name, size, scene, generateMipMaps) {
  12127. var _this = this;
  12128. _super.call(this, name, size, scene, generateMipMaps, true);
  12129. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12130. this._transformMatrix = BABYLON.Matrix.Zero();
  12131. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12132. this.onBeforeRender = function () {
  12133. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12134. _this._savedViewMatrix = scene.getViewMatrix();
  12135. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12136. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12137. scene.clipPlane = _this.mirrorPlane;
  12138. scene.getEngine().cullBackFaces = false;
  12139. };
  12140. this.onAfterRender = function () {
  12141. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12142. scene.getEngine().cullBackFaces = true;
  12143. delete scene.clipPlane;
  12144. };
  12145. }
  12146. MirrorTexture.prototype.clone = function () {
  12147. var textureSize = this.getSize();
  12148. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12149. // Base texture
  12150. newTexture.hasAlpha = this.hasAlpha;
  12151. newTexture.level = this.level;
  12152. // Mirror Texture
  12153. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12154. newTexture.renderList = this.renderList.slice(0);
  12155. return newTexture;
  12156. };
  12157. return MirrorTexture;
  12158. })(BABYLON.RenderTargetTexture);
  12159. BABYLON.MirrorTexture = MirrorTexture;
  12160. })(BABYLON || (BABYLON = {}));
  12161. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12162. var BABYLON;
  12163. (function (BABYLON) {
  12164. var DynamicTexture = (function (_super) {
  12165. __extends(DynamicTexture, _super);
  12166. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12167. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12168. _super.call(this, null, scene, !generateMipMaps);
  12169. this.name = name;
  12170. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12171. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12172. this._generateMipMaps = generateMipMaps;
  12173. if (options.getContext) {
  12174. this._canvas = options;
  12175. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12176. } else {
  12177. this._canvas = document.createElement("canvas");
  12178. if (options.width) {
  12179. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12180. } else {
  12181. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12182. }
  12183. }
  12184. var textureSize = this.getSize();
  12185. this._canvas.width = textureSize.width;
  12186. this._canvas.height = textureSize.height;
  12187. this._context = this._canvas.getContext("2d");
  12188. }
  12189. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12190. get: function () {
  12191. return true;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. DynamicTexture.prototype.scale = function (ratio) {
  12197. var textureSize = this.getSize();
  12198. textureSize.width *= ratio;
  12199. textureSize.height *= ratio;
  12200. this._canvas.width = textureSize.width;
  12201. this._canvas.height = textureSize.height;
  12202. this.releaseInternalTexture();
  12203. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12204. };
  12205. DynamicTexture.prototype.getContext = function () {
  12206. return this._context;
  12207. };
  12208. DynamicTexture.prototype.clear = function () {
  12209. var size = this.getSize();
  12210. this._context.fillRect(0, 0, size.width, size.height);
  12211. };
  12212. DynamicTexture.prototype.update = function (invertY) {
  12213. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12214. };
  12215. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12216. if (typeof update === "undefined") { update = true; }
  12217. var size = this.getSize();
  12218. if (clearColor) {
  12219. this._context.fillStyle = clearColor;
  12220. this._context.fillRect(0, 0, size.width, size.height);
  12221. }
  12222. this._context.font = font;
  12223. if (x === null) {
  12224. var textSize = this._context.measureText(text);
  12225. x = (size.width - textSize.width) / 2;
  12226. }
  12227. this._context.fillStyle = color;
  12228. this._context.fillText(text, x, y);
  12229. if (update) {
  12230. this.update(invertY);
  12231. }
  12232. };
  12233. DynamicTexture.prototype.clone = function () {
  12234. var textureSize = this.getSize();
  12235. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12236. // Base texture
  12237. newTexture.hasAlpha = this.hasAlpha;
  12238. newTexture.level = this.level;
  12239. // Dynamic Texture
  12240. newTexture.wrapU = this.wrapU;
  12241. newTexture.wrapV = this.wrapV;
  12242. return newTexture;
  12243. };
  12244. return DynamicTexture;
  12245. })(BABYLON.Texture);
  12246. BABYLON.DynamicTexture = DynamicTexture;
  12247. })(BABYLON || (BABYLON = {}));
  12248. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12249. var BABYLON;
  12250. (function (BABYLON) {
  12251. var VideoTexture = (function (_super) {
  12252. __extends(VideoTexture, _super);
  12253. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12254. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12255. var _this = this;
  12256. _super.call(this, null, scene, !generateMipMaps, invertY);
  12257. this._autoLaunch = true;
  12258. this.name = name;
  12259. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12260. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12261. var requiredWidth = size.width || size;
  12262. var requiredHeight = size.height || size;
  12263. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12264. var textureSize = this.getSize();
  12265. this.video = document.createElement("video");
  12266. this.video.width = textureSize.width;
  12267. this.video.height = textureSize.height;
  12268. this.video.autoplay = false;
  12269. this.video.loop = true;
  12270. this.video.addEventListener("canplaythrough", function () {
  12271. if (_this._texture) {
  12272. _this._texture.isReady = true;
  12273. }
  12274. });
  12275. urls.forEach(function (url) {
  12276. var source = document.createElement("source");
  12277. source.src = url;
  12278. _this.video.appendChild(source);
  12279. });
  12280. this._lastUpdate = BABYLON.Tools.Now;
  12281. }
  12282. VideoTexture.prototype.update = function () {
  12283. if (this._autoLaunch) {
  12284. this._autoLaunch = false;
  12285. this.video.play();
  12286. }
  12287. var now = BABYLON.Tools.Now;
  12288. if (now - this._lastUpdate < 15) {
  12289. return false;
  12290. }
  12291. this._lastUpdate = now;
  12292. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12293. return true;
  12294. };
  12295. return VideoTexture;
  12296. })(BABYLON.Texture);
  12297. BABYLON.VideoTexture = VideoTexture;
  12298. })(BABYLON || (BABYLON = {}));
  12299. //# sourceMappingURL=babylon.videoTexture.js.map
  12300. var BABYLON;
  12301. (function (BABYLON) {
  12302. var EffectFallbacks = (function () {
  12303. function EffectFallbacks() {
  12304. this._defines = {};
  12305. this._currentRank = 32;
  12306. this._maxRank = -1;
  12307. }
  12308. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12309. if (!this._defines[rank]) {
  12310. if (rank < this._currentRank) {
  12311. this._currentRank = rank;
  12312. }
  12313. if (rank > this._maxRank) {
  12314. this._maxRank = rank;
  12315. }
  12316. this._defines[rank] = new Array();
  12317. }
  12318. this._defines[rank].push(define);
  12319. };
  12320. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12321. get: function () {
  12322. return this._currentRank <= this._maxRank;
  12323. },
  12324. enumerable: true,
  12325. configurable: true
  12326. });
  12327. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12328. var currentFallbacks = this._defines[this._currentRank];
  12329. for (var index = 0; index < currentFallbacks.length; index++) {
  12330. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12331. }
  12332. this._currentRank++;
  12333. return currentDefines;
  12334. };
  12335. return EffectFallbacks;
  12336. })();
  12337. BABYLON.EffectFallbacks = EffectFallbacks;
  12338. var Effect = (function () {
  12339. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12340. var _this = this;
  12341. this._isReady = false;
  12342. this._compilationError = "";
  12343. this._valueCache = [];
  12344. this._engine = engine;
  12345. this.name = baseName;
  12346. this.defines = defines;
  12347. this._uniformsNames = uniformsNames.concat(samplers);
  12348. this._samplers = samplers;
  12349. this._attributesNames = attributesNames;
  12350. this.onError = onError;
  12351. this.onCompiled = onCompiled;
  12352. var vertexSource;
  12353. var fragmentSource;
  12354. if (baseName.vertexElement) {
  12355. vertexSource = document.getElementById(baseName.vertexElement);
  12356. if (!vertexSource) {
  12357. vertexSource = baseName.vertexElement;
  12358. }
  12359. } else {
  12360. vertexSource = baseName.vertex || baseName;
  12361. }
  12362. if (baseName.fragmentElement) {
  12363. fragmentSource = document.getElementById(baseName.fragmentElement);
  12364. if (!fragmentSource) {
  12365. fragmentSource = baseName.fragmentElement;
  12366. }
  12367. } else {
  12368. fragmentSource = baseName.fragment || baseName;
  12369. }
  12370. this._loadVertexShader(vertexSource, function (vertexCode) {
  12371. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12372. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12373. });
  12374. });
  12375. }
  12376. // Properties
  12377. Effect.prototype.isReady = function () {
  12378. return this._isReady;
  12379. };
  12380. Effect.prototype.getProgram = function () {
  12381. return this._program;
  12382. };
  12383. Effect.prototype.getAttributesNames = function () {
  12384. return this._attributesNames;
  12385. };
  12386. Effect.prototype.getAttributeLocation = function (index) {
  12387. return this._attributes[index];
  12388. };
  12389. Effect.prototype.getAttributeLocationByName = function (name) {
  12390. var index = this._attributesNames.indexOf(name);
  12391. return this._attributes[index];
  12392. };
  12393. Effect.prototype.getAttributesCount = function () {
  12394. return this._attributes.length;
  12395. };
  12396. Effect.prototype.getUniformIndex = function (uniformName) {
  12397. return this._uniformsNames.indexOf(uniformName);
  12398. };
  12399. Effect.prototype.getUniform = function (uniformName) {
  12400. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12401. };
  12402. Effect.prototype.getSamplers = function () {
  12403. return this._samplers;
  12404. };
  12405. Effect.prototype.getCompilationError = function () {
  12406. return this._compilationError;
  12407. };
  12408. // Methods
  12409. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12410. // DOM element ?
  12411. if (vertex instanceof HTMLElement) {
  12412. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12413. callback(vertexCode);
  12414. return;
  12415. }
  12416. // Is in local store ?
  12417. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12418. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12419. return;
  12420. }
  12421. var vertexShaderUrl;
  12422. if (vertex[0] === ".") {
  12423. vertexShaderUrl = vertex;
  12424. } else {
  12425. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12426. }
  12427. // Vertex shader
  12428. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12429. };
  12430. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12431. // DOM element ?
  12432. if (fragment instanceof HTMLElement) {
  12433. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12434. callback(fragmentCode);
  12435. return;
  12436. }
  12437. // Is in local store ?
  12438. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12439. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12440. return;
  12441. }
  12442. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12443. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12444. return;
  12445. }
  12446. var fragmentShaderUrl;
  12447. if (fragment[0] === ".") {
  12448. fragmentShaderUrl = fragment;
  12449. } else {
  12450. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12451. }
  12452. // Fragment shader
  12453. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12454. };
  12455. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12456. try {
  12457. var engine = this._engine;
  12458. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12459. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12460. this._attributes = engine.getAttributes(this._program, attributesNames);
  12461. for (var index = 0; index < this._samplers.length; index++) {
  12462. var sampler = this.getUniform(this._samplers[index]);
  12463. if (sampler == null) {
  12464. this._samplers.splice(index, 1);
  12465. index--;
  12466. }
  12467. }
  12468. engine.bindSamplers(this);
  12469. this._isReady = true;
  12470. if (this.onCompiled) {
  12471. this.onCompiled(this);
  12472. }
  12473. } catch (e) {
  12474. // Is it a problem with precision?
  12475. if (e.message.indexOf("highp") !== -1) {
  12476. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12477. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12478. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12479. return;
  12480. }
  12481. // Let's go through fallbacks then
  12482. if (fallbacks && fallbacks.isMoreFallbacks) {
  12483. defines = fallbacks.reduce(defines);
  12484. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12485. } else {
  12486. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12487. BABYLON.Tools.Error("Defines: " + defines);
  12488. BABYLON.Tools.Error("Error: " + e.message);
  12489. this._compilationError = e.message;
  12490. if (this.onError) {
  12491. this.onError(this, this._compilationError);
  12492. }
  12493. }
  12494. }
  12495. };
  12496. Effect.prototype._bindTexture = function (channel, texture) {
  12497. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12498. };
  12499. Effect.prototype.setTexture = function (channel, texture) {
  12500. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12501. };
  12502. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12503. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12504. };
  12505. //public _cacheMatrix(uniformName, matrix) {
  12506. // if (!this._valueCache[uniformName]) {
  12507. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12508. // }
  12509. // for (var index = 0; index < 16; index++) {
  12510. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12511. // }
  12512. //};
  12513. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12514. if (!this._valueCache[uniformName]) {
  12515. this._valueCache[uniformName] = [x, y];
  12516. return;
  12517. }
  12518. this._valueCache[uniformName][0] = x;
  12519. this._valueCache[uniformName][1] = y;
  12520. };
  12521. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12522. if (!this._valueCache[uniformName]) {
  12523. this._valueCache[uniformName] = [x, y, z];
  12524. return;
  12525. }
  12526. this._valueCache[uniformName][0] = x;
  12527. this._valueCache[uniformName][1] = y;
  12528. this._valueCache[uniformName][2] = z;
  12529. };
  12530. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12531. if (!this._valueCache[uniformName]) {
  12532. this._valueCache[uniformName] = [x, y, z, w];
  12533. return;
  12534. }
  12535. this._valueCache[uniformName][0] = x;
  12536. this._valueCache[uniformName][1] = y;
  12537. this._valueCache[uniformName][2] = z;
  12538. this._valueCache[uniformName][3] = w;
  12539. };
  12540. Effect.prototype.setArray = function (uniformName, array) {
  12541. this._engine.setArray(this.getUniform(uniformName), array);
  12542. return this;
  12543. };
  12544. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12545. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12546. return this;
  12547. };
  12548. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12549. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12550. // return;
  12551. //this._cacheMatrix(uniformName, matrix);
  12552. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12553. return this;
  12554. };
  12555. Effect.prototype.setFloat = function (uniformName, value) {
  12556. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12557. return this;
  12558. this._valueCache[uniformName] = value;
  12559. this._engine.setFloat(this.getUniform(uniformName), value);
  12560. return this;
  12561. };
  12562. Effect.prototype.setBool = function (uniformName, bool) {
  12563. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12564. return this;
  12565. this._valueCache[uniformName] = bool;
  12566. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12567. return this;
  12568. };
  12569. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12570. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12571. return this;
  12572. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12573. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12574. return this;
  12575. };
  12576. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12577. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12578. return this;
  12579. this._cacheFloat2(uniformName, x, y);
  12580. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12581. return this;
  12582. };
  12583. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12584. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12585. return this;
  12586. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12587. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12588. return this;
  12589. };
  12590. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12591. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12592. return this;
  12593. this._cacheFloat3(uniformName, x, y, z);
  12594. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12595. return this;
  12596. };
  12597. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12598. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12599. return this;
  12600. this._cacheFloat4(uniformName, x, y, z, w);
  12601. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12602. return this;
  12603. };
  12604. Effect.prototype.setColor3 = function (uniformName, color3) {
  12605. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12606. return this;
  12607. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12608. this._engine.setColor3(this.getUniform(uniformName), color3);
  12609. return this;
  12610. };
  12611. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12612. 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)
  12613. return this;
  12614. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12615. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12616. return this;
  12617. };
  12618. 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}",
  12619. 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}",
  12620. 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}",
  12621. 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}",
  12622. 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}",
  12623. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12624. 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}",
  12625. 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}",
  12626. 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}",
  12627. 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}",
  12628. 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}",
  12629. 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}",
  12630. 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}",
  12631. 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}",
  12632. 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}",
  12633. 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}",
  12634. 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}",
  12635. 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}",
  12636. 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}",
  12637. 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}",
  12638. 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}",
  12639. 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}",
  12640. 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}",
  12641. 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}",
  12642. 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}",
  12643. 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}",
  12644. 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}",
  12645. 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}",
  12646. 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}",
  12647. 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}",
  12648. 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}",
  12649. 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}",
  12650. 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}",
  12651. 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}",
  12652. 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}",
  12653. 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}",
  12654. 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}",
  12655. };
  12656. return Effect;
  12657. })();
  12658. BABYLON.Effect = Effect;
  12659. })(BABYLON || (BABYLON = {}));
  12660. //# sourceMappingURL=babylon.effect.js.map
  12661. var BABYLON;
  12662. (function (BABYLON) {
  12663. var Material = (function () {
  12664. function Material(name, scene, doNotAdd) {
  12665. this.name = name;
  12666. this.checkReadyOnEveryCall = true;
  12667. this.checkReadyOnlyOnce = false;
  12668. this.state = "";
  12669. this.alpha = 1.0;
  12670. this.backFaceCulling = true;
  12671. this._wasPreviouslyReady = false;
  12672. this._fillMode = Material.TriangleFillMode;
  12673. this.pointSize = 1.0;
  12674. this.id = name;
  12675. this._scene = scene;
  12676. if (!doNotAdd) {
  12677. scene.materials.push(this);
  12678. }
  12679. }
  12680. Object.defineProperty(Material, "TriangleFillMode", {
  12681. get: function () {
  12682. return Material._TriangleFillMode;
  12683. },
  12684. enumerable: true,
  12685. configurable: true
  12686. });
  12687. Object.defineProperty(Material, "WireFrameFillMode", {
  12688. get: function () {
  12689. return Material._WireFrameFillMode;
  12690. },
  12691. enumerable: true,
  12692. configurable: true
  12693. });
  12694. Object.defineProperty(Material, "PointFillMode", {
  12695. get: function () {
  12696. return Material._PointFillMode;
  12697. },
  12698. enumerable: true,
  12699. configurable: true
  12700. });
  12701. Object.defineProperty(Material.prototype, "wireframe", {
  12702. get: function () {
  12703. return this._fillMode === Material.WireFrameFillMode;
  12704. },
  12705. set: function (value) {
  12706. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12707. },
  12708. enumerable: true,
  12709. configurable: true
  12710. });
  12711. Object.defineProperty(Material.prototype, "pointsCloud", {
  12712. get: function () {
  12713. return this._fillMode === Material.PointFillMode;
  12714. },
  12715. set: function (value) {
  12716. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12717. },
  12718. enumerable: true,
  12719. configurable: true
  12720. });
  12721. Object.defineProperty(Material.prototype, "fillMode", {
  12722. get: function () {
  12723. return this._fillMode;
  12724. },
  12725. set: function (value) {
  12726. this._fillMode = value;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Material.prototype.isReady = function (mesh, useInstances) {
  12732. return true;
  12733. };
  12734. Material.prototype.getEffect = function () {
  12735. return this._effect;
  12736. };
  12737. Material.prototype.getScene = function () {
  12738. return this._scene;
  12739. };
  12740. Material.prototype.needAlphaBlending = function () {
  12741. return (this.alpha < 1.0);
  12742. };
  12743. Material.prototype.needAlphaTesting = function () {
  12744. return false;
  12745. };
  12746. Material.prototype.getAlphaTestTexture = function () {
  12747. return null;
  12748. };
  12749. Material.prototype.trackCreation = function (onCompiled, onError) {
  12750. };
  12751. Material.prototype._preBind = function () {
  12752. var engine = this._scene.getEngine();
  12753. engine.enableEffect(this._effect);
  12754. engine.setState(this.backFaceCulling);
  12755. };
  12756. Material.prototype.bind = function (world, mesh) {
  12757. this._scene._cachedMaterial = this;
  12758. if (this.onBind) {
  12759. this.onBind(this);
  12760. }
  12761. };
  12762. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12763. };
  12764. Material.prototype.unbind = function () {
  12765. };
  12766. Material.prototype.dispose = function (forceDisposeEffect) {
  12767. // Remove from scene
  12768. var index = this._scene.materials.indexOf(this);
  12769. this._scene.materials.splice(index, 1);
  12770. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12771. if (forceDisposeEffect && this._effect) {
  12772. this._scene.getEngine()._releaseEffect(this._effect);
  12773. this._effect = null;
  12774. }
  12775. // Callback
  12776. if (this.onDispose) {
  12777. this.onDispose();
  12778. }
  12779. };
  12780. Material._TriangleFillMode = 0;
  12781. Material._WireFrameFillMode = 1;
  12782. Material._PointFillMode = 2;
  12783. return Material;
  12784. })();
  12785. BABYLON.Material = Material;
  12786. })(BABYLON || (BABYLON = {}));
  12787. //# sourceMappingURL=babylon.material.js.map
  12788. var BABYLON;
  12789. (function (BABYLON) {
  12790. var maxSimultaneousLights = 4;
  12791. var FresnelParameters = (function () {
  12792. function FresnelParameters() {
  12793. this.isEnabled = true;
  12794. this.leftColor = BABYLON.Color3.White();
  12795. this.rightColor = BABYLON.Color3.Black();
  12796. this.bias = 0;
  12797. this.power = 1;
  12798. }
  12799. return FresnelParameters;
  12800. })();
  12801. BABYLON.FresnelParameters = FresnelParameters;
  12802. var StandardMaterial = (function (_super) {
  12803. __extends(StandardMaterial, _super);
  12804. function StandardMaterial(name, scene) {
  12805. var _this = this;
  12806. _super.call(this, name, scene);
  12807. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12808. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12809. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12810. this.specularPower = 64;
  12811. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12812. this.useAlphaFromDiffuseTexture = false;
  12813. this.useSpecularOverAlpha = true;
  12814. this.fogEnabled = true;
  12815. this._cachedDefines = null;
  12816. this._renderTargets = new BABYLON.SmartArray(16);
  12817. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12818. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12819. this._scaledDiffuse = new BABYLON.Color3();
  12820. this._scaledSpecular = new BABYLON.Color3();
  12821. this.getRenderTargetTextures = function () {
  12822. _this._renderTargets.reset();
  12823. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12824. _this._renderTargets.push(_this.reflectionTexture);
  12825. }
  12826. return _this._renderTargets;
  12827. };
  12828. }
  12829. StandardMaterial.prototype.needAlphaBlending = function () {
  12830. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12831. };
  12832. StandardMaterial.prototype.needAlphaTesting = function () {
  12833. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12834. };
  12835. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12836. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12837. };
  12838. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12839. return this.diffuseTexture;
  12840. };
  12841. // Methods
  12842. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12843. if (this.checkReadyOnlyOnce) {
  12844. if (this._wasPreviouslyReady) {
  12845. return true;
  12846. }
  12847. }
  12848. var scene = this.getScene();
  12849. if (!this.checkReadyOnEveryCall) {
  12850. if (this._renderId === scene.getRenderId()) {
  12851. return true;
  12852. }
  12853. }
  12854. var engine = scene.getEngine();
  12855. var defines = [];
  12856. var fallbacks = new BABYLON.EffectFallbacks();
  12857. // Textures
  12858. if (scene.texturesEnabled) {
  12859. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12860. if (!this.diffuseTexture.isReady()) {
  12861. return false;
  12862. } else {
  12863. defines.push("#define DIFFUSE");
  12864. }
  12865. }
  12866. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12867. if (!this.ambientTexture.isReady()) {
  12868. return false;
  12869. } else {
  12870. defines.push("#define AMBIENT");
  12871. }
  12872. }
  12873. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12874. if (!this.opacityTexture.isReady()) {
  12875. return false;
  12876. } else {
  12877. defines.push("#define OPACITY");
  12878. if (this.opacityTexture.getAlphaFromRGB) {
  12879. defines.push("#define OPACITYRGB");
  12880. }
  12881. }
  12882. }
  12883. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  12884. if (!this.reflectionTexture.isReady()) {
  12885. return false;
  12886. } else {
  12887. defines.push("#define REFLECTION");
  12888. fallbacks.addFallback(0, "REFLECTION");
  12889. }
  12890. }
  12891. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  12892. if (!this.emissiveTexture.isReady()) {
  12893. return false;
  12894. } else {
  12895. defines.push("#define EMISSIVE");
  12896. }
  12897. }
  12898. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  12899. if (!this.specularTexture.isReady()) {
  12900. return false;
  12901. } else {
  12902. defines.push("#define SPECULAR");
  12903. fallbacks.addFallback(0, "SPECULAR");
  12904. }
  12905. }
  12906. }
  12907. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  12908. if (!this.bumpTexture.isReady()) {
  12909. return false;
  12910. } else {
  12911. defines.push("#define BUMP");
  12912. fallbacks.addFallback(0, "BUMP");
  12913. }
  12914. }
  12915. // Effect
  12916. if (this.useSpecularOverAlpha) {
  12917. defines.push("#define SPECULAROVERALPHA");
  12918. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  12919. }
  12920. if (scene.clipPlane) {
  12921. defines.push("#define CLIPPLANE");
  12922. }
  12923. if (engine.getAlphaTesting()) {
  12924. defines.push("#define ALPHATEST");
  12925. }
  12926. if (this._shouldUseAlphaFromDiffuseTexture()) {
  12927. defines.push("#define ALPHAFROMDIFFUSE");
  12928. }
  12929. // Point size
  12930. if (this.pointsCloud || scene.forcePointsCloud) {
  12931. defines.push("#define POINTSIZE");
  12932. }
  12933. // Fog
  12934. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  12935. defines.push("#define FOG");
  12936. fallbacks.addFallback(1, "FOG");
  12937. }
  12938. var shadowsActivated = false;
  12939. var lightIndex = 0;
  12940. if (scene.lightsEnabled) {
  12941. for (var index = 0; index < scene.lights.length; index++) {
  12942. var light = scene.lights[index];
  12943. if (!light.isEnabled()) {
  12944. continue;
  12945. }
  12946. // Excluded check
  12947. if (light._excludedMeshesIds.length > 0) {
  12948. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  12949. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  12950. if (excludedMesh) {
  12951. light.excludedMeshes.push(excludedMesh);
  12952. }
  12953. }
  12954. light._excludedMeshesIds = [];
  12955. }
  12956. // Included check
  12957. if (light._includedOnlyMeshesIds.length > 0) {
  12958. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  12959. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  12960. if (includedOnlyMesh) {
  12961. light.includedOnlyMeshes.push(includedOnlyMesh);
  12962. }
  12963. }
  12964. light._includedOnlyMeshesIds = [];
  12965. }
  12966. if (!light.canAffectMesh(mesh)) {
  12967. continue;
  12968. }
  12969. defines.push("#define LIGHT" + lightIndex);
  12970. if (lightIndex > 0) {
  12971. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  12972. }
  12973. var type;
  12974. if (light instanceof BABYLON.SpotLight) {
  12975. type = "#define SPOTLIGHT" + lightIndex;
  12976. } else if (light instanceof BABYLON.HemisphericLight) {
  12977. type = "#define HEMILIGHT" + lightIndex;
  12978. } else {
  12979. type = "#define POINTDIRLIGHT" + lightIndex;
  12980. }
  12981. defines.push(type);
  12982. if (lightIndex > 0) {
  12983. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  12984. }
  12985. // Shadows
  12986. if (scene.shadowsEnabled) {
  12987. var shadowGenerator = light.getShadowGenerator();
  12988. if (mesh && mesh.receiveShadows && shadowGenerator) {
  12989. defines.push("#define SHADOW" + lightIndex);
  12990. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  12991. if (!shadowsActivated) {
  12992. defines.push("#define SHADOWS");
  12993. shadowsActivated = true;
  12994. }
  12995. if (shadowGenerator.useVarianceShadowMap) {
  12996. defines.push("#define SHADOWVSM" + lightIndex);
  12997. if (lightIndex > 0) {
  12998. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  12999. }
  13000. }
  13001. if (shadowGenerator.usePoissonSampling) {
  13002. defines.push("#define SHADOWPCF" + lightIndex);
  13003. if (lightIndex > 0) {
  13004. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13005. }
  13006. }
  13007. }
  13008. }
  13009. lightIndex++;
  13010. if (lightIndex === maxSimultaneousLights)
  13011. break;
  13012. }
  13013. }
  13014. if (StandardMaterial.FresnelEnabled) {
  13015. // Fresnel
  13016. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13017. var fresnelRank = 1;
  13018. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13019. defines.push("#define DIFFUSEFRESNEL");
  13020. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13021. fresnelRank++;
  13022. }
  13023. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13024. defines.push("#define OPACITYFRESNEL");
  13025. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13026. fresnelRank++;
  13027. }
  13028. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13029. defines.push("#define REFLECTIONFRESNEL");
  13030. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13031. fresnelRank++;
  13032. }
  13033. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13034. defines.push("#define EMISSIVEFRESNEL");
  13035. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13036. fresnelRank++;
  13037. }
  13038. defines.push("#define FRESNEL");
  13039. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13040. }
  13041. }
  13042. // Attribs
  13043. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13044. if (mesh) {
  13045. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13046. attribs.push(BABYLON.VertexBuffer.UVKind);
  13047. defines.push("#define UV1");
  13048. }
  13049. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13050. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13051. defines.push("#define UV2");
  13052. }
  13053. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13054. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13055. defines.push("#define VERTEXCOLOR");
  13056. if (mesh.hasVertexAlpha) {
  13057. defines.push("#define VERTEXALPHA");
  13058. }
  13059. }
  13060. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13061. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13062. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13063. defines.push("#define BONES");
  13064. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13065. defines.push("#define BONES4");
  13066. fallbacks.addFallback(0, "BONES4");
  13067. }
  13068. // Instances
  13069. if (useInstances) {
  13070. defines.push("#define INSTANCES");
  13071. attribs.push("world0");
  13072. attribs.push("world1");
  13073. attribs.push("world2");
  13074. attribs.push("world3");
  13075. }
  13076. }
  13077. // Get correct effect
  13078. var join = defines.join("\n");
  13079. if (this._cachedDefines !== join) {
  13080. this._cachedDefines = join;
  13081. scene.resetCachedMaterial();
  13082. // Legacy browser patch
  13083. var shaderName = "default";
  13084. if (!scene.getEngine().getCaps().standardDerivatives) {
  13085. shaderName = "legacydefault";
  13086. }
  13087. this._effect = scene.getEngine().createEffect(shaderName, attribs, [
  13088. "world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  13089. "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0",
  13090. "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1",
  13091. "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2",
  13092. "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3",
  13093. "vFogInfos", "vFogColor", "pointSize",
  13094. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos",
  13095. "mBones",
  13096. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix",
  13097. "darkness0", "darkness1", "darkness2", "darkness3",
  13098. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"
  13099. ], [
  13100. "diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler",
  13101. "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"
  13102. ], join, fallbacks, this.onCompiled, this.onError);
  13103. }
  13104. if (!this._effect.isReady()) {
  13105. return false;
  13106. }
  13107. this._renderId = scene.getRenderId();
  13108. this._wasPreviouslyReady = true;
  13109. return true;
  13110. };
  13111. StandardMaterial.prototype.unbind = function () {
  13112. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13113. this._effect.setTexture("reflection2DSampler", null);
  13114. }
  13115. };
  13116. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13117. this._effect.setMatrix("world", world);
  13118. };
  13119. StandardMaterial.prototype.bind = function (world, mesh) {
  13120. var scene = this.getScene();
  13121. // Matrices
  13122. this.bindOnlyWorldMatrix(world);
  13123. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13124. // Bones
  13125. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13126. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13127. }
  13128. if (scene.getCachedMaterial() !== this) {
  13129. if (StandardMaterial.FresnelEnabled) {
  13130. // Fresnel
  13131. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13132. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13133. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13134. }
  13135. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13136. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13137. }
  13138. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13139. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13140. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13141. }
  13142. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13143. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13144. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13145. }
  13146. }
  13147. // Textures
  13148. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13149. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13150. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13151. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13152. }
  13153. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13154. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13155. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13156. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13157. }
  13158. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13159. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13160. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13161. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13162. }
  13163. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13164. if (this.reflectionTexture.isCube) {
  13165. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13166. } else {
  13167. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13168. }
  13169. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13170. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13171. }
  13172. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13173. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13174. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13175. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13176. }
  13177. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13178. this._effect.setTexture("specularSampler", this.specularTexture);
  13179. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13180. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13181. }
  13182. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13183. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13184. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13185. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13186. }
  13187. // Clip plane
  13188. if (scene.clipPlane) {
  13189. var clipPlane = scene.clipPlane;
  13190. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13191. }
  13192. // Point size
  13193. if (this.pointsCloud) {
  13194. this._effect.setFloat("pointSize", this.pointSize);
  13195. }
  13196. // Colors
  13197. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13198. // Scaling down color according to emissive
  13199. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13200. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13201. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13202. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13203. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13204. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13205. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13206. }
  13207. // Scaling down color according to emissive
  13208. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13209. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13210. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13211. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13212. if (scene.lightsEnabled) {
  13213. var lightIndex = 0;
  13214. for (var index = 0; index < scene.lights.length; index++) {
  13215. var light = scene.lights[index];
  13216. if (!light.isEnabled()) {
  13217. continue;
  13218. }
  13219. if (!light.canAffectMesh(mesh)) {
  13220. continue;
  13221. }
  13222. if (light instanceof BABYLON.PointLight) {
  13223. // Point Light
  13224. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13225. } else if (light instanceof BABYLON.DirectionalLight) {
  13226. // Directional Light
  13227. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13228. } else if (light instanceof BABYLON.SpotLight) {
  13229. // Spot Light
  13230. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13231. } else if (light instanceof BABYLON.HemisphericLight) {
  13232. // Hemispheric Light
  13233. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13234. }
  13235. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13236. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13237. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13238. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13239. // Shadows
  13240. if (scene.shadowsEnabled) {
  13241. var shadowGenerator = light.getShadowGenerator();
  13242. if (mesh.receiveShadows && shadowGenerator) {
  13243. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13244. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13245. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13246. }
  13247. }
  13248. lightIndex++;
  13249. if (lightIndex === maxSimultaneousLights)
  13250. break;
  13251. }
  13252. }
  13253. // View
  13254. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13255. this._effect.setMatrix("view", scene.getViewMatrix());
  13256. }
  13257. // Fog
  13258. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13259. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13260. this._effect.setColor3("vFogColor", scene.fogColor);
  13261. }
  13262. _super.prototype.bind.call(this, world, mesh);
  13263. };
  13264. StandardMaterial.prototype.getAnimatables = function () {
  13265. var results = [];
  13266. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13267. results.push(this.diffuseTexture);
  13268. }
  13269. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13270. results.push(this.ambientTexture);
  13271. }
  13272. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13273. results.push(this.opacityTexture);
  13274. }
  13275. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13276. results.push(this.reflectionTexture);
  13277. }
  13278. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13279. results.push(this.emissiveTexture);
  13280. }
  13281. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13282. results.push(this.specularTexture);
  13283. }
  13284. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13285. results.push(this.bumpTexture);
  13286. }
  13287. return results;
  13288. };
  13289. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13290. if (this.diffuseTexture) {
  13291. this.diffuseTexture.dispose();
  13292. }
  13293. if (this.ambientTexture) {
  13294. this.ambientTexture.dispose();
  13295. }
  13296. if (this.opacityTexture) {
  13297. this.opacityTexture.dispose();
  13298. }
  13299. if (this.reflectionTexture) {
  13300. this.reflectionTexture.dispose();
  13301. }
  13302. if (this.emissiveTexture) {
  13303. this.emissiveTexture.dispose();
  13304. }
  13305. if (this.specularTexture) {
  13306. this.specularTexture.dispose();
  13307. }
  13308. if (this.bumpTexture) {
  13309. this.bumpTexture.dispose();
  13310. }
  13311. _super.prototype.dispose.call(this, forceDisposeEffect);
  13312. };
  13313. StandardMaterial.prototype.clone = function (name) {
  13314. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13315. // Base material
  13316. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13317. newStandardMaterial.alpha = this.alpha;
  13318. newStandardMaterial.fillMode = this.fillMode;
  13319. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13320. // Standard material
  13321. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13322. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13323. }
  13324. if (this.ambientTexture && this.ambientTexture.clone) {
  13325. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13326. }
  13327. if (this.opacityTexture && this.opacityTexture.clone) {
  13328. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13329. }
  13330. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13331. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13332. }
  13333. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13334. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13335. }
  13336. if (this.specularTexture && this.specularTexture.clone) {
  13337. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13338. }
  13339. if (this.bumpTexture && this.bumpTexture.clone) {
  13340. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13341. }
  13342. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13343. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13344. newStandardMaterial.specularColor = this.specularColor.clone();
  13345. newStandardMaterial.specularPower = this.specularPower;
  13346. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13347. return newStandardMaterial;
  13348. };
  13349. StandardMaterial.DiffuseTextureEnabled = true;
  13350. StandardMaterial.AmbientTextureEnabled = true;
  13351. StandardMaterial.OpacityTextureEnabled = true;
  13352. StandardMaterial.ReflectionTextureEnabled = true;
  13353. StandardMaterial.EmissiveTextureEnabled = true;
  13354. StandardMaterial.SpecularTextureEnabled = true;
  13355. StandardMaterial.BumpTextureEnabled = true;
  13356. StandardMaterial.FresnelEnabled = true;
  13357. return StandardMaterial;
  13358. })(BABYLON.Material);
  13359. BABYLON.StandardMaterial = StandardMaterial;
  13360. })(BABYLON || (BABYLON = {}));
  13361. //# sourceMappingURL=babylon.standardMaterial.js.map
  13362. var BABYLON;
  13363. (function (BABYLON) {
  13364. var MultiMaterial = (function (_super) {
  13365. __extends(MultiMaterial, _super);
  13366. function MultiMaterial(name, scene) {
  13367. _super.call(this, name, scene, true);
  13368. this.subMaterials = new Array();
  13369. scene.multiMaterials.push(this);
  13370. }
  13371. // Properties
  13372. MultiMaterial.prototype.getSubMaterial = function (index) {
  13373. if (index < 0 || index >= this.subMaterials.length) {
  13374. return this.getScene().defaultMaterial;
  13375. }
  13376. return this.subMaterials[index];
  13377. };
  13378. // Methods
  13379. MultiMaterial.prototype.isReady = function (mesh) {
  13380. for (var index = 0; index < this.subMaterials.length; index++) {
  13381. var subMaterial = this.subMaterials[index];
  13382. if (subMaterial) {
  13383. if (!this.subMaterials[index].isReady(mesh)) {
  13384. return false;
  13385. }
  13386. }
  13387. }
  13388. return true;
  13389. };
  13390. return MultiMaterial;
  13391. })(BABYLON.Material);
  13392. BABYLON.MultiMaterial = MultiMaterial;
  13393. })(BABYLON || (BABYLON = {}));
  13394. //# sourceMappingURL=babylon.multiMaterial.js.map
  13395. var BABYLON;
  13396. (function (BABYLON) {
  13397. var Database = (function () {
  13398. function Database(urlToScene, callbackManifestChecked) {
  13399. // Handling various flavors of prefixed version of IndexedDB
  13400. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13401. this.callbackManifestChecked = callbackManifestChecked;
  13402. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13403. this.db = null;
  13404. this.enableSceneOffline = false;
  13405. this.enableTexturesOffline = false;
  13406. this.manifestVersionFound = 0;
  13407. this.mustUpdateRessources = false;
  13408. this.hasReachedQuota = false;
  13409. this.checkManifestFile();
  13410. }
  13411. Database.prototype.checkManifestFile = function () {
  13412. var _this = this;
  13413. function noManifestFile() {
  13414. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13415. that.enableSceneOffline = false;
  13416. that.enableTexturesOffline = false;
  13417. that.callbackManifestChecked(false);
  13418. }
  13419. var that = this;
  13420. var manifestURL = this.currentSceneUrl + ".manifest";
  13421. var xhr = new XMLHttpRequest();
  13422. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13423. xhr.open("GET", manifestURLTimeStamped, true);
  13424. xhr.addEventListener("load", function () {
  13425. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13426. try {
  13427. var manifestFile = JSON.parse(xhr.response);
  13428. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13429. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13430. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13431. _this.manifestVersionFound = manifestFile.version;
  13432. }
  13433. if (_this.callbackManifestChecked) {
  13434. _this.callbackManifestChecked(true);
  13435. }
  13436. } catch (ex) {
  13437. noManifestFile();
  13438. }
  13439. } else {
  13440. noManifestFile();
  13441. }
  13442. }, false);
  13443. xhr.addEventListener("error", function (event) {
  13444. noManifestFile();
  13445. }, false);
  13446. try {
  13447. xhr.send();
  13448. } catch (ex) {
  13449. BABYLON.Tools.Error("Error on XHR send request.");
  13450. that.callbackManifestChecked(false);
  13451. }
  13452. };
  13453. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13454. var _this = this;
  13455. function handleError() {
  13456. that.isSupported = false;
  13457. if (errorCallback)
  13458. errorCallback();
  13459. }
  13460. var that = this;
  13461. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13462. // Your browser doesn't support IndexedDB
  13463. this.isSupported = false;
  13464. if (errorCallback)
  13465. errorCallback();
  13466. } else {
  13467. // If the DB hasn't been opened or created yet
  13468. if (!this.db) {
  13469. this.hasReachedQuota = false;
  13470. this.isSupported = true;
  13471. var request = this.idbFactory.open("babylonjs", 1);
  13472. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13473. request.onerror = function (event) {
  13474. handleError();
  13475. };
  13476. // executes when a version change transaction cannot complete due to other active transactions
  13477. request.onblocked = function (event) {
  13478. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13479. handleError();
  13480. };
  13481. // DB has been opened successfully
  13482. request.onsuccess = function (event) {
  13483. _this.db = request.result;
  13484. successCallback();
  13485. };
  13486. // Initialization of the DB. Creating Scenes & Textures stores
  13487. request.onupgradeneeded = function (event) {
  13488. _this.db = (event.target).result;
  13489. try {
  13490. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13491. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13492. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13493. } catch (ex) {
  13494. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13495. handleError();
  13496. }
  13497. };
  13498. } else {
  13499. if (successCallback)
  13500. successCallback();
  13501. }
  13502. }
  13503. };
  13504. Database.prototype.loadImageFromDB = function (url, image) {
  13505. var _this = this;
  13506. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13507. var saveAndLoadImage = function () {
  13508. if (!_this.hasReachedQuota && _this.db !== null) {
  13509. // the texture is not yet in the DB, let's try to save it
  13510. _this._saveImageIntoDBAsync(completeURL, image);
  13511. } else {
  13512. image.src = url;
  13513. }
  13514. };
  13515. if (!this.mustUpdateRessources) {
  13516. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13517. } else {
  13518. saveAndLoadImage();
  13519. }
  13520. };
  13521. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13522. if (this.isSupported && this.db !== null) {
  13523. var texture;
  13524. var transaction = this.db.transaction(["textures"]);
  13525. transaction.onabort = function (event) {
  13526. image.src = url;
  13527. };
  13528. transaction.oncomplete = function (event) {
  13529. var blobTextureURL;
  13530. if (texture) {
  13531. var URL = window.URL || window.webkitURL;
  13532. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13533. image.onerror = function () {
  13534. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13535. image.src = url;
  13536. };
  13537. image.src = blobTextureURL;
  13538. } else {
  13539. notInDBCallback();
  13540. }
  13541. };
  13542. var getRequest = transaction.objectStore("textures").get(url);
  13543. getRequest.onsuccess = function (event) {
  13544. texture = (event.target).result;
  13545. };
  13546. getRequest.onerror = function (event) {
  13547. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13548. image.src = url;
  13549. };
  13550. } else {
  13551. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13552. image.src = url;
  13553. }
  13554. };
  13555. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13556. var _this = this;
  13557. if (this.isSupported) {
  13558. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13559. var generateBlobUrl = function () {
  13560. var blobTextureURL;
  13561. if (blob) {
  13562. var URL = window.URL || window.webkitURL;
  13563. try {
  13564. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13565. } catch (ex) {
  13566. blobTextureURL = URL.createObjectURL(blob);
  13567. }
  13568. }
  13569. image.src = blobTextureURL;
  13570. };
  13571. if (BABYLON.Database.isUASupportingBlobStorage) {
  13572. var xhr = new XMLHttpRequest(), blob;
  13573. xhr.open("GET", url, true);
  13574. xhr.responseType = "blob";
  13575. xhr.addEventListener("load", function () {
  13576. if (xhr.status === 200) {
  13577. // Blob as response (XHR2)
  13578. blob = xhr.response;
  13579. var transaction = _this.db.transaction(["textures"], "readwrite");
  13580. // the transaction could abort because of a QuotaExceededError error
  13581. transaction.onabort = function (event) {
  13582. try {
  13583. if (event.srcElement.error.name === "QuotaExceededError") {
  13584. this.hasReachedQuota = true;
  13585. }
  13586. } catch (ex) {
  13587. }
  13588. generateBlobUrl();
  13589. };
  13590. transaction.oncomplete = function (event) {
  13591. generateBlobUrl();
  13592. };
  13593. var newTexture = { textureUrl: url, data: blob };
  13594. try {
  13595. // Put the blob into the dabase
  13596. var addRequest = transaction.objectStore("textures").put(newTexture);
  13597. addRequest.onsuccess = function (event) {
  13598. };
  13599. addRequest.onerror = function (event) {
  13600. generateBlobUrl();
  13601. };
  13602. } catch (ex) {
  13603. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13604. if (ex.code === 25) {
  13605. BABYLON.Database.isUASupportingBlobStorage = false;
  13606. }
  13607. image.src = url;
  13608. }
  13609. } else {
  13610. image.src = url;
  13611. }
  13612. }, false);
  13613. xhr.addEventListener("error", function (event) {
  13614. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13615. image.src = url;
  13616. }, false);
  13617. xhr.send();
  13618. } else {
  13619. image.src = url;
  13620. }
  13621. } else {
  13622. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13623. image.src = url;
  13624. }
  13625. };
  13626. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13627. var _this = this;
  13628. var updateVersion = function (event) {
  13629. // the version is not yet in the DB or we need to update it
  13630. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13631. };
  13632. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13633. };
  13634. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13635. var _this = this;
  13636. if (this.isSupported) {
  13637. var version;
  13638. try {
  13639. var transaction = this.db.transaction(["versions"]);
  13640. transaction.oncomplete = function (event) {
  13641. if (version) {
  13642. // If the version in the JSON file is > than the version in DB
  13643. if (_this.manifestVersionFound > version.data) {
  13644. _this.mustUpdateRessources = true;
  13645. updateInDBCallback();
  13646. } else {
  13647. callback(version.data);
  13648. }
  13649. } else {
  13650. _this.mustUpdateRessources = true;
  13651. updateInDBCallback();
  13652. }
  13653. };
  13654. transaction.onabort = function (event) {
  13655. callback(-1);
  13656. };
  13657. var getRequest = transaction.objectStore("versions").get(url);
  13658. getRequest.onsuccess = function (event) {
  13659. version = (event.target).result;
  13660. };
  13661. getRequest.onerror = function (event) {
  13662. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13663. callback(-1);
  13664. };
  13665. } catch (ex) {
  13666. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13667. callback(-1);
  13668. }
  13669. } else {
  13670. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13671. callback(-1);
  13672. }
  13673. };
  13674. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13675. var _this = this;
  13676. if (this.isSupported && !this.hasReachedQuota) {
  13677. try {
  13678. // Open a transaction to the database
  13679. var transaction = this.db.transaction(["versions"], "readwrite");
  13680. // the transaction could abort because of a QuotaExceededError error
  13681. transaction.onabort = function (event) {
  13682. try {
  13683. if (event.srcElement.error.name === "QuotaExceededError") {
  13684. _this.hasReachedQuota = true;
  13685. }
  13686. } catch (ex) {
  13687. }
  13688. callback(-1);
  13689. };
  13690. transaction.oncomplete = function (event) {
  13691. callback(_this.manifestVersionFound);
  13692. };
  13693. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13694. // Put the scene into the database
  13695. var addRequest = transaction.objectStore("versions").put(newVersion);
  13696. addRequest.onsuccess = function (event) {
  13697. };
  13698. addRequest.onerror = function (event) {
  13699. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13700. };
  13701. } catch (ex) {
  13702. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13703. callback(-1);
  13704. }
  13705. } else {
  13706. callback(-1);
  13707. }
  13708. };
  13709. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13710. var _this = this;
  13711. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13712. var saveAndLoadFile = function (event) {
  13713. // the scene is not yet in the DB, let's try to save it
  13714. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13715. };
  13716. this._checkVersionFromDB(completeUrl, function (version) {
  13717. if (version !== -1) {
  13718. if (!_this.mustUpdateRessources) {
  13719. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13720. } else {
  13721. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13722. }
  13723. } else {
  13724. errorCallback();
  13725. }
  13726. });
  13727. };
  13728. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13729. if (this.isSupported) {
  13730. var targetStore;
  13731. if (url.indexOf(".babylon") !== -1) {
  13732. targetStore = "scenes";
  13733. } else {
  13734. targetStore = "textures";
  13735. }
  13736. var file;
  13737. var transaction = this.db.transaction([targetStore]);
  13738. transaction.oncomplete = function (event) {
  13739. if (file) {
  13740. callback(file.data);
  13741. } else {
  13742. notInDBCallback();
  13743. }
  13744. };
  13745. transaction.onabort = function (event) {
  13746. notInDBCallback();
  13747. };
  13748. var getRequest = transaction.objectStore(targetStore).get(url);
  13749. getRequest.onsuccess = function (event) {
  13750. file = (event.target).result;
  13751. };
  13752. getRequest.onerror = function (event) {
  13753. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13754. notInDBCallback();
  13755. };
  13756. } else {
  13757. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13758. callback();
  13759. }
  13760. };
  13761. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13762. var _this = this;
  13763. if (this.isSupported) {
  13764. var targetStore;
  13765. if (url.indexOf(".babylon") !== -1) {
  13766. targetStore = "scenes";
  13767. } else {
  13768. targetStore = "textures";
  13769. }
  13770. // Create XHR
  13771. var xhr = new XMLHttpRequest(), fileData;
  13772. xhr.open("GET", url, true);
  13773. if (useArrayBuffer) {
  13774. xhr.responseType = "arraybuffer";
  13775. }
  13776. xhr.onprogress = progressCallback;
  13777. xhr.addEventListener("load", function () {
  13778. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13779. // Blob as response (XHR2)
  13780. //fileData = xhr.responseText;
  13781. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13782. if (!_this.hasReachedQuota) {
  13783. // Open a transaction to the database
  13784. var transaction = _this.db.transaction([targetStore], "readwrite");
  13785. // the transaction could abort because of a QuotaExceededError error
  13786. transaction.onabort = function (event) {
  13787. try {
  13788. if (event.srcElement.error.name === "QuotaExceededError") {
  13789. this.hasReachedQuota = true;
  13790. }
  13791. } catch (ex) {
  13792. }
  13793. callback(fileData);
  13794. };
  13795. transaction.oncomplete = function (event) {
  13796. callback(fileData);
  13797. };
  13798. var newFile;
  13799. if (targetStore === "scenes") {
  13800. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13801. } else {
  13802. newFile = { textureUrl: url, data: fileData };
  13803. }
  13804. try {
  13805. // Put the scene into the database
  13806. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13807. addRequest.onsuccess = function (event) {
  13808. };
  13809. addRequest.onerror = function (event) {
  13810. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13811. };
  13812. } catch (ex) {
  13813. callback(fileData);
  13814. }
  13815. } else {
  13816. callback(fileData);
  13817. }
  13818. } else {
  13819. callback();
  13820. }
  13821. }, false);
  13822. xhr.addEventListener("error", function (event) {
  13823. BABYLON.Tools.Error("error on XHR request.");
  13824. callback();
  13825. }, false);
  13826. xhr.send();
  13827. } else {
  13828. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13829. callback();
  13830. }
  13831. };
  13832. Database.isUASupportingBlobStorage = true;
  13833. Database.parseURL = function (url) {
  13834. var a = document.createElement('a');
  13835. a.href = url;
  13836. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13837. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13838. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13839. return absLocation;
  13840. };
  13841. Database.ReturnFullUrlLocation = function (url) {
  13842. if (url.indexOf("http:/") === -1) {
  13843. return (BABYLON.Database.parseURL(window.location.href) + url);
  13844. } else {
  13845. return url;
  13846. }
  13847. };
  13848. return Database;
  13849. })();
  13850. BABYLON.Database = Database;
  13851. })(BABYLON || (BABYLON = {}));
  13852. //# sourceMappingURL=babylon.database.js.map
  13853. var BABYLON;
  13854. (function (BABYLON) {
  13855. var SpriteManager = (function () {
  13856. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  13857. this.name = name;
  13858. this.cellSize = cellSize;
  13859. this.sprites = new Array();
  13860. this.renderingGroupId = 0;
  13861. this.fogEnabled = true;
  13862. this._vertexDeclaration = [3, 4, 4, 4];
  13863. this._vertexStrideSize = 15 * 4;
  13864. this._capacity = capacity;
  13865. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  13866. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13867. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13868. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  13869. this._scene = scene;
  13870. this._scene.spriteManagers.push(this);
  13871. // VBO
  13872. this._vertexDeclaration = [3, 4, 4, 4];
  13873. this._vertexStrideSize = 15 * 4;
  13874. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  13875. var indices = [];
  13876. var index = 0;
  13877. for (var count = 0; count < capacity; count++) {
  13878. indices.push(index);
  13879. indices.push(index + 1);
  13880. indices.push(index + 2);
  13881. indices.push(index);
  13882. indices.push(index + 2);
  13883. indices.push(index + 3);
  13884. index += 4;
  13885. }
  13886. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  13887. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  13888. // Effects
  13889. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  13890. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  13891. }
  13892. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  13893. var arrayOffset = index * 15;
  13894. if (offsetX == 0)
  13895. offsetX = this._epsilon;
  13896. else if (offsetX == 1)
  13897. offsetX = 1 - this._epsilon;
  13898. if (offsetY == 0)
  13899. offsetY = this._epsilon;
  13900. else if (offsetY == 1)
  13901. offsetY = 1 - this._epsilon;
  13902. this._vertices[arrayOffset] = sprite.position.x;
  13903. this._vertices[arrayOffset + 1] = sprite.position.y;
  13904. this._vertices[arrayOffset + 2] = sprite.position.z;
  13905. this._vertices[arrayOffset + 3] = sprite.angle;
  13906. this._vertices[arrayOffset + 4] = sprite.size;
  13907. this._vertices[arrayOffset + 5] = offsetX;
  13908. this._vertices[arrayOffset + 6] = offsetY;
  13909. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  13910. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  13911. var offset = (sprite.cellIndex / rowSize) >> 0;
  13912. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  13913. this._vertices[arrayOffset + 10] = offset;
  13914. // Color
  13915. this._vertices[arrayOffset + 11] = sprite.color.r;
  13916. this._vertices[arrayOffset + 12] = sprite.color.g;
  13917. this._vertices[arrayOffset + 13] = sprite.color.b;
  13918. this._vertices[arrayOffset + 14] = sprite.color.a;
  13919. };
  13920. SpriteManager.prototype.render = function () {
  13921. // Check
  13922. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  13923. return;
  13924. var engine = this._scene.getEngine();
  13925. var baseSize = this._spriteTexture.getBaseSize();
  13926. // Sprites
  13927. var deltaTime = engine.getDeltaTime();
  13928. var max = Math.min(this._capacity, this.sprites.length);
  13929. var rowSize = baseSize.width / this.cellSize;
  13930. var offset = 0;
  13931. for (var index = 0; index < max; index++) {
  13932. var sprite = this.sprites[index];
  13933. if (!sprite) {
  13934. continue;
  13935. }
  13936. sprite._animate(deltaTime);
  13937. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  13938. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  13939. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  13940. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  13941. }
  13942. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  13943. // Render
  13944. var effect = this._effectBase;
  13945. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13946. effect = this._effectFog;
  13947. }
  13948. engine.enableEffect(effect);
  13949. var viewMatrix = this._scene.getViewMatrix();
  13950. effect.setTexture("diffuseSampler", this._spriteTexture);
  13951. effect.setMatrix("view", viewMatrix);
  13952. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  13953. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  13954. // Fog
  13955. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13956. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  13957. effect.setColor3("vFogColor", this._scene.fogColor);
  13958. }
  13959. // VBOs
  13960. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  13961. // Draw order
  13962. effect.setBool("alphaTest", true);
  13963. engine.setColorWrite(false);
  13964. engine.draw(true, 0, max * 6);
  13965. engine.setColorWrite(true);
  13966. effect.setBool("alphaTest", false);
  13967. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  13968. engine.draw(true, 0, max * 6);
  13969. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  13970. };
  13971. SpriteManager.prototype.dispose = function () {
  13972. if (this._vertexBuffer) {
  13973. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  13974. this._vertexBuffer = null;
  13975. }
  13976. if (this._indexBuffer) {
  13977. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  13978. this._indexBuffer = null;
  13979. }
  13980. if (this._spriteTexture) {
  13981. this._spriteTexture.dispose();
  13982. this._spriteTexture = null;
  13983. }
  13984. // Remove from scene
  13985. var index = this._scene.spriteManagers.indexOf(this);
  13986. this._scene.spriteManagers.splice(index, 1);
  13987. // Callback
  13988. if (this.onDispose) {
  13989. this.onDispose();
  13990. }
  13991. };
  13992. return SpriteManager;
  13993. })();
  13994. BABYLON.SpriteManager = SpriteManager;
  13995. })(BABYLON || (BABYLON = {}));
  13996. //# sourceMappingURL=babylon.spriteManager.js.map
  13997. var BABYLON;
  13998. (function (BABYLON) {
  13999. var Sprite = (function () {
  14000. function Sprite(name, manager) {
  14001. this.name = name;
  14002. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14003. this.size = 1.0;
  14004. this.angle = 0;
  14005. this.cellIndex = 0;
  14006. this.invertU = 0;
  14007. this.invertV = 0;
  14008. this.animations = new Array();
  14009. this._animationStarted = false;
  14010. this._loopAnimation = false;
  14011. this._fromIndex = 0;
  14012. this._toIndex = 0;
  14013. this._delay = 0;
  14014. this._direction = 1;
  14015. this._frameCount = 0;
  14016. this._time = 0;
  14017. this._manager = manager;
  14018. this._manager.sprites.push(this);
  14019. this.position = BABYLON.Vector3.Zero();
  14020. }
  14021. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14022. this._fromIndex = from;
  14023. this._toIndex = to;
  14024. this._loopAnimation = loop;
  14025. this._delay = delay;
  14026. this._animationStarted = true;
  14027. this._direction = from < to ? 1 : -1;
  14028. this.cellIndex = from;
  14029. this._time = 0;
  14030. };
  14031. Sprite.prototype.stopAnimation = function () {
  14032. this._animationStarted = false;
  14033. };
  14034. Sprite.prototype._animate = function (deltaTime) {
  14035. if (!this._animationStarted)
  14036. return;
  14037. this._time += deltaTime;
  14038. if (this._time > this._delay) {
  14039. this._time = this._time % this._delay;
  14040. this.cellIndex += this._direction;
  14041. if (this.cellIndex == this._toIndex) {
  14042. if (this._loopAnimation) {
  14043. this.cellIndex = this._fromIndex;
  14044. } else {
  14045. this._animationStarted = false;
  14046. if (this.disposeWhenFinishedAnimating) {
  14047. this.dispose();
  14048. }
  14049. }
  14050. }
  14051. }
  14052. };
  14053. Sprite.prototype.dispose = function () {
  14054. for (var i = 0; i < this._manager.sprites.length; i++) {
  14055. if (this._manager.sprites[i] == this) {
  14056. this._manager.sprites.splice(i, 1);
  14057. }
  14058. }
  14059. };
  14060. return Sprite;
  14061. })();
  14062. BABYLON.Sprite = Sprite;
  14063. })(BABYLON || (BABYLON = {}));
  14064. //# sourceMappingURL=babylon.sprite.js.map
  14065. var BABYLON;
  14066. (function (BABYLON) {
  14067. var Layer = (function () {
  14068. function Layer(name, imgUrl, scene, isBackground, color) {
  14069. this.name = name;
  14070. this._vertexDeclaration = [2];
  14071. this._vertexStrideSize = 2 * 4;
  14072. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14073. this.isBackground = isBackground === undefined ? true : isBackground;
  14074. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14075. this._scene = scene;
  14076. this._scene.layers.push(this);
  14077. // VBO
  14078. var vertices = [];
  14079. vertices.push(1, 1);
  14080. vertices.push(-1, 1);
  14081. vertices.push(-1, -1);
  14082. vertices.push(1, -1);
  14083. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14084. // Indices
  14085. var indices = [];
  14086. indices.push(0);
  14087. indices.push(1);
  14088. indices.push(2);
  14089. indices.push(0);
  14090. indices.push(2);
  14091. indices.push(3);
  14092. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14093. // Effects
  14094. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14095. }
  14096. Layer.prototype.render = function () {
  14097. // Check
  14098. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14099. return;
  14100. var engine = this._scene.getEngine();
  14101. // Render
  14102. engine.enableEffect(this._effect);
  14103. engine.setState(false);
  14104. // Texture
  14105. this._effect.setTexture("textureSampler", this.texture);
  14106. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14107. // Color
  14108. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14109. // VBOs
  14110. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14111. // Draw order
  14112. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14113. engine.draw(true, 0, 6);
  14114. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14115. };
  14116. Layer.prototype.dispose = function () {
  14117. if (this._vertexBuffer) {
  14118. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14119. this._vertexBuffer = null;
  14120. }
  14121. if (this._indexBuffer) {
  14122. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14123. this._indexBuffer = null;
  14124. }
  14125. if (this.texture) {
  14126. this.texture.dispose();
  14127. this.texture = null;
  14128. }
  14129. // Remove from scene
  14130. var index = this._scene.layers.indexOf(this);
  14131. this._scene.layers.splice(index, 1);
  14132. // Callback
  14133. if (this.onDispose) {
  14134. this.onDispose();
  14135. }
  14136. };
  14137. return Layer;
  14138. })();
  14139. BABYLON.Layer = Layer;
  14140. })(BABYLON || (BABYLON = {}));
  14141. //# sourceMappingURL=babylon.layer.js.map
  14142. var BABYLON;
  14143. (function (BABYLON) {
  14144. var Particle = (function () {
  14145. function Particle() {
  14146. this.position = BABYLON.Vector3.Zero();
  14147. this.direction = BABYLON.Vector3.Zero();
  14148. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14149. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14150. this.lifeTime = 1.0;
  14151. this.age = 0;
  14152. this.size = 0;
  14153. this.angle = 0;
  14154. this.angularSpeed = 0;
  14155. }
  14156. Particle.prototype.copyTo = function (other) {
  14157. other.position.copyFrom(this.position);
  14158. other.direction.copyFrom(this.direction);
  14159. other.color.copyFrom(this.color);
  14160. other.colorStep.copyFrom(this.colorStep);
  14161. other.lifeTime = this.lifeTime;
  14162. other.age = this.age;
  14163. other.size = this.size;
  14164. other.angle = this.angle;
  14165. other.angularSpeed = this.angularSpeed;
  14166. };
  14167. return Particle;
  14168. })();
  14169. BABYLON.Particle = Particle;
  14170. })(BABYLON || (BABYLON = {}));
  14171. //# sourceMappingURL=babylon.particle.js.map
  14172. var BABYLON;
  14173. (function (BABYLON) {
  14174. var randomNumber = function (min, max) {
  14175. if (min === max) {
  14176. return (min);
  14177. }
  14178. var random = Math.random();
  14179. return ((random * (max - min)) + min);
  14180. };
  14181. var ParticleSystem = (function () {
  14182. function ParticleSystem(name, capacity, scene, customEffect) {
  14183. var _this = this;
  14184. this.name = name;
  14185. this.renderingGroupId = 0;
  14186. this.emitter = null;
  14187. this.emitRate = 10;
  14188. this.manualEmitCount = -1;
  14189. this.updateSpeed = 0.01;
  14190. this.targetStopDuration = 0;
  14191. this.disposeOnStop = false;
  14192. this.minEmitPower = 1;
  14193. this.maxEmitPower = 1;
  14194. this.minLifeTime = 1;
  14195. this.maxLifeTime = 1;
  14196. this.minSize = 1;
  14197. this.maxSize = 1;
  14198. this.minAngularSpeed = 0;
  14199. this.maxAngularSpeed = 0;
  14200. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14201. this.forceDepthWrite = false;
  14202. this.gravity = BABYLON.Vector3.Zero();
  14203. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14204. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14205. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14206. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14207. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14208. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14209. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14210. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14211. this.particles = new Array();
  14212. this._vertexDeclaration = [3, 4, 4];
  14213. this._vertexStrideSize = 11 * 4;
  14214. this._stockParticles = new Array();
  14215. this._newPartsExcess = 0;
  14216. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14217. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14218. this._scaledDirection = BABYLON.Vector3.Zero();
  14219. this._scaledGravity = BABYLON.Vector3.Zero();
  14220. this._currentRenderId = -1;
  14221. this._started = false;
  14222. this._stopped = false;
  14223. this._actualFrame = 0;
  14224. this.id = name;
  14225. this._capacity = capacity;
  14226. this._scene = scene;
  14227. this._customEffect = customEffect;
  14228. scene.particleSystems.push(this);
  14229. // VBO
  14230. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14231. var indices = [];
  14232. var index = 0;
  14233. for (var count = 0; count < capacity; count++) {
  14234. indices.push(index);
  14235. indices.push(index + 1);
  14236. indices.push(index + 2);
  14237. indices.push(index);
  14238. indices.push(index + 2);
  14239. indices.push(index + 3);
  14240. index += 4;
  14241. }
  14242. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14243. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14244. // Default behaviors
  14245. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14246. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14247. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14248. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14249. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14250. };
  14251. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14252. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14253. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14254. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14255. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14256. };
  14257. this.updateFunction = function (particles) {
  14258. for (var index = 0; index < particles.length; index++) {
  14259. var particle = particles[index];
  14260. particle.age += _this._scaledUpdateSpeed;
  14261. if (particle.age >= particle.lifeTime) {
  14262. _this.recycleParticle(particle);
  14263. index--;
  14264. continue;
  14265. } else {
  14266. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14267. particle.color.addInPlace(_this._scaledColorStep);
  14268. if (particle.color.a < 0)
  14269. particle.color.a = 0;
  14270. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14271. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14272. particle.position.addInPlace(_this._scaledDirection);
  14273. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14274. particle.direction.addInPlace(_this._scaledGravity);
  14275. }
  14276. }
  14277. };
  14278. }
  14279. ParticleSystem.prototype.recycleParticle = function (particle) {
  14280. var lastParticle = this.particles.pop();
  14281. if (lastParticle !== particle) {
  14282. lastParticle.copyTo(particle);
  14283. this._stockParticles.push(lastParticle);
  14284. }
  14285. };
  14286. ParticleSystem.prototype.getCapacity = function () {
  14287. return this._capacity;
  14288. };
  14289. ParticleSystem.prototype.isAlive = function () {
  14290. return this._alive;
  14291. };
  14292. ParticleSystem.prototype.isStarted = function () {
  14293. return this._started;
  14294. };
  14295. ParticleSystem.prototype.start = function () {
  14296. this._started = true;
  14297. this._stopped = false;
  14298. this._actualFrame = 0;
  14299. };
  14300. ParticleSystem.prototype.stop = function () {
  14301. this._stopped = true;
  14302. };
  14303. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14304. var offset = index * 11;
  14305. this._vertices[offset] = particle.position.x;
  14306. this._vertices[offset + 1] = particle.position.y;
  14307. this._vertices[offset + 2] = particle.position.z;
  14308. this._vertices[offset + 3] = particle.color.r;
  14309. this._vertices[offset + 4] = particle.color.g;
  14310. this._vertices[offset + 5] = particle.color.b;
  14311. this._vertices[offset + 6] = particle.color.a;
  14312. this._vertices[offset + 7] = particle.angle;
  14313. this._vertices[offset + 8] = particle.size;
  14314. this._vertices[offset + 9] = offsetX;
  14315. this._vertices[offset + 10] = offsetY;
  14316. };
  14317. ParticleSystem.prototype._update = function (newParticles) {
  14318. // Update current
  14319. this._alive = this.particles.length > 0;
  14320. this.updateFunction(this.particles);
  14321. // Add new ones
  14322. var worldMatrix;
  14323. if (this.emitter.position) {
  14324. worldMatrix = this.emitter.getWorldMatrix();
  14325. } else {
  14326. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14327. }
  14328. for (var index = 0; index < newParticles; index++) {
  14329. if (this.particles.length === this._capacity) {
  14330. break;
  14331. }
  14332. if (this._stockParticles.length !== 0) {
  14333. var particle = this._stockParticles.pop();
  14334. particle.age = 0;
  14335. } else {
  14336. particle = new BABYLON.Particle();
  14337. }
  14338. this.particles.push(particle);
  14339. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14340. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14341. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14342. particle.size = randomNumber(this.minSize, this.maxSize);
  14343. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14344. this.startPositionFunction(worldMatrix, particle.position);
  14345. var step = randomNumber(0, 1.0);
  14346. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14347. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14348. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14349. }
  14350. };
  14351. ParticleSystem.prototype._getEffect = function () {
  14352. if (this._customEffect) {
  14353. return this._customEffect;
  14354. }
  14355. ;
  14356. var defines = [];
  14357. if (this._scene.clipPlane) {
  14358. defines.push("#define CLIPPLANE");
  14359. }
  14360. // Effect
  14361. var join = defines.join("\n");
  14362. if (this._cachedDefines !== join) {
  14363. this._cachedDefines = join;
  14364. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14365. }
  14366. return this._effect;
  14367. };
  14368. ParticleSystem.prototype.animate = function () {
  14369. if (!this._started)
  14370. return;
  14371. var effect = this._getEffect();
  14372. // Check
  14373. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14374. return;
  14375. if (this._currentRenderId === this._scene.getRenderId()) {
  14376. return;
  14377. }
  14378. this._currentRenderId = this._scene.getRenderId();
  14379. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14380. // determine the number of particles we need to create
  14381. var emitCout;
  14382. if (this.manualEmitCount > -1) {
  14383. emitCout = this.manualEmitCount;
  14384. this.manualEmitCount = 0;
  14385. } else {
  14386. emitCout = this.emitRate;
  14387. }
  14388. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14389. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14390. if (this._newPartsExcess > 1.0) {
  14391. newParticles += this._newPartsExcess >> 0;
  14392. this._newPartsExcess -= this._newPartsExcess >> 0;
  14393. }
  14394. this._alive = false;
  14395. if (!this._stopped) {
  14396. this._actualFrame += this._scaledUpdateSpeed;
  14397. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14398. this.stop();
  14399. } else {
  14400. newParticles = 0;
  14401. }
  14402. this._update(newParticles);
  14403. // Stopped?
  14404. if (this._stopped) {
  14405. if (!this._alive) {
  14406. this._started = false;
  14407. if (this.disposeOnStop) {
  14408. this._scene._toBeDisposed.push(this);
  14409. }
  14410. }
  14411. }
  14412. // Update VBO
  14413. var offset = 0;
  14414. for (var index = 0; index < this.particles.length; index++) {
  14415. var particle = this.particles[index];
  14416. this._appendParticleVertex(offset++, particle, 0, 0);
  14417. this._appendParticleVertex(offset++, particle, 1, 0);
  14418. this._appendParticleVertex(offset++, particle, 1, 1);
  14419. this._appendParticleVertex(offset++, particle, 0, 1);
  14420. }
  14421. var engine = this._scene.getEngine();
  14422. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14423. };
  14424. ParticleSystem.prototype.render = function () {
  14425. var effect = this._getEffect();
  14426. // Check
  14427. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14428. return 0;
  14429. var engine = this._scene.getEngine();
  14430. // Render
  14431. engine.enableEffect(effect);
  14432. engine.setState(false);
  14433. var viewMatrix = this._scene.getViewMatrix();
  14434. effect.setTexture("diffuseSampler", this.particleTexture);
  14435. effect.setMatrix("view", viewMatrix);
  14436. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14437. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14438. if (this._scene.clipPlane) {
  14439. var clipPlane = this._scene.clipPlane;
  14440. var invView = viewMatrix.clone();
  14441. invView.invert();
  14442. effect.setMatrix("invView", invView);
  14443. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14444. }
  14445. // VBOs
  14446. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14447. // Draw order
  14448. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14449. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14450. } else {
  14451. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14452. }
  14453. if (this.forceDepthWrite) {
  14454. engine.setDepthWrite(true);
  14455. }
  14456. engine.draw(true, 0, this.particles.length * 6);
  14457. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14458. return this.particles.length;
  14459. };
  14460. ParticleSystem.prototype.dispose = function () {
  14461. if (this._vertexBuffer) {
  14462. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14463. this._vertexBuffer = null;
  14464. }
  14465. if (this._indexBuffer) {
  14466. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14467. this._indexBuffer = null;
  14468. }
  14469. if (this.particleTexture) {
  14470. this.particleTexture.dispose();
  14471. this.particleTexture = null;
  14472. }
  14473. // Remove from scene
  14474. var index = this._scene.particleSystems.indexOf(this);
  14475. this._scene.particleSystems.splice(index, 1);
  14476. // Callback
  14477. if (this.onDispose) {
  14478. this.onDispose();
  14479. }
  14480. };
  14481. // Clone
  14482. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14483. var result = new ParticleSystem(name, this._capacity, this._scene);
  14484. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14485. if (newEmitter === undefined) {
  14486. newEmitter = this.emitter;
  14487. }
  14488. result.emitter = newEmitter;
  14489. if (this.particleTexture) {
  14490. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14491. }
  14492. result.start();
  14493. return result;
  14494. };
  14495. ParticleSystem.BLENDMODE_ONEONE = 0;
  14496. ParticleSystem.BLENDMODE_STANDARD = 1;
  14497. return ParticleSystem;
  14498. })();
  14499. BABYLON.ParticleSystem = ParticleSystem;
  14500. })(BABYLON || (BABYLON = {}));
  14501. //# sourceMappingURL=babylon.particleSystem.js.map
  14502. var BABYLON;
  14503. (function (BABYLON) {
  14504. var Animation = (function () {
  14505. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14506. this.name = name;
  14507. this.targetProperty = targetProperty;
  14508. this.framePerSecond = framePerSecond;
  14509. this.dataType = dataType;
  14510. this.loopMode = loopMode;
  14511. this._offsetsCache = {};
  14512. this._highLimitsCache = {};
  14513. this._stopped = false;
  14514. this.targetPropertyPath = targetProperty.split(".");
  14515. this.dataType = dataType;
  14516. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14517. }
  14518. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14519. var dataType = undefined;
  14520. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14521. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14522. } else if (from instanceof BABYLON.Quaternion) {
  14523. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14524. } else if (from instanceof BABYLON.Vector3) {
  14525. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14526. } else if (from instanceof BABYLON.Vector2) {
  14527. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14528. } else if (from instanceof BABYLON.Color3) {
  14529. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14530. }
  14531. if (dataType == undefined) {
  14532. return;
  14533. }
  14534. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14535. var keys = [];
  14536. keys.push({ frame: 0, value: from });
  14537. keys.push({ frame: totalFrame, value: to });
  14538. animation.setKeys(keys);
  14539. mesh.animations.push(animation);
  14540. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14541. };
  14542. // Methods
  14543. Animation.prototype.isStopped = function () {
  14544. return this._stopped;
  14545. };
  14546. Animation.prototype.getKeys = function () {
  14547. return this._keys;
  14548. };
  14549. Animation.prototype.getEasingFunction = function () {
  14550. return this._easingFunction;
  14551. };
  14552. Animation.prototype.setEasingFunction = function (easingFunction) {
  14553. this._easingFunction = easingFunction;
  14554. };
  14555. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14556. return startValue + (endValue - startValue) * gradient;
  14557. };
  14558. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14559. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14560. };
  14561. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14562. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14563. };
  14564. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14565. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14566. };
  14567. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14568. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14569. };
  14570. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  14571. var startScale = new BABYLON.Vector3(0, 0, 0);
  14572. var startRotation = new BABYLON.Quaternion();
  14573. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  14574. startValue.decompose(startScale, startRotation, startTranslation);
  14575. var endScale = new BABYLON.Vector3(0, 0, 0);
  14576. var endRotation = new BABYLON.Quaternion();
  14577. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  14578. endValue.decompose(endScale, endRotation, endTranslation);
  14579. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  14580. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  14581. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  14582. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  14583. return result;
  14584. };
  14585. Animation.prototype.clone = function () {
  14586. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14587. clone.setKeys(this._keys);
  14588. return clone;
  14589. };
  14590. Animation.prototype.setKeys = function (values) {
  14591. this._keys = values.slice(0);
  14592. this._offsetsCache = {};
  14593. this._highLimitsCache = {};
  14594. };
  14595. Animation.prototype._getKeyValue = function (value) {
  14596. if (typeof value === "function") {
  14597. return value();
  14598. }
  14599. return value;
  14600. };
  14601. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14602. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14603. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14604. }
  14605. this.currentFrame = currentFrame;
  14606. for (var key = 0; key < this._keys.length; key++) {
  14607. // for each frame, we need the key just before the frame superior
  14608. if (this._keys[key + 1].frame >= currentFrame) {
  14609. var startValue = this._getKeyValue(this._keys[key].value);
  14610. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14611. // gradient : percent of currentFrame between the frame inf and the frame sup
  14612. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14613. // check for easingFunction and correction of gradient
  14614. if (this._easingFunction != null) {
  14615. gradient = this._easingFunction.ease(gradient);
  14616. }
  14617. switch (this.dataType) {
  14618. case Animation.ANIMATIONTYPE_FLOAT:
  14619. switch (loopMode) {
  14620. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14621. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14622. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14623. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14624. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14625. }
  14626. break;
  14627. case Animation.ANIMATIONTYPE_QUATERNION:
  14628. var quaternion = null;
  14629. switch (loopMode) {
  14630. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14631. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14632. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14633. break;
  14634. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14635. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14636. break;
  14637. }
  14638. return quaternion;
  14639. case Animation.ANIMATIONTYPE_VECTOR3:
  14640. switch (loopMode) {
  14641. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14642. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14643. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14644. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14645. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14646. }
  14647. case Animation.ANIMATIONTYPE_VECTOR2:
  14648. switch (loopMode) {
  14649. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14650. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14651. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14652. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14653. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14654. }
  14655. case Animation.ANIMATIONTYPE_COLOR3:
  14656. switch (loopMode) {
  14657. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14658. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14659. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14660. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14661. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14662. }
  14663. case Animation.ANIMATIONTYPE_MATRIX:
  14664. switch (loopMode) {
  14665. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14666. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14667. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  14668. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14669. return startValue;
  14670. }
  14671. default:
  14672. break;
  14673. }
  14674. break;
  14675. }
  14676. }
  14677. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14678. };
  14679. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14680. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14681. this._stopped = true;
  14682. return false;
  14683. }
  14684. var returnValue = true;
  14685. // Adding a start key at frame 0 if missing
  14686. if (this._keys[0].frame !== 0) {
  14687. var newKey = { frame: 0, value: this._keys[0].value };
  14688. this._keys.splice(0, 0, newKey);
  14689. }
  14690. // Check limits
  14691. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14692. from = this._keys[0].frame;
  14693. }
  14694. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14695. to = this._keys[this._keys.length - 1].frame;
  14696. }
  14697. // Compute ratio
  14698. var range = to - from;
  14699. var offsetValue;
  14700. // ratio represents the frame delta between from and to
  14701. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14702. var highLimitValue = 0;
  14703. if (ratio > range && !loop) {
  14704. returnValue = false;
  14705. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14706. } else {
  14707. // Get max value if required
  14708. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14709. var keyOffset = to.toString() + from.toString();
  14710. if (!this._offsetsCache[keyOffset]) {
  14711. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14712. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14713. switch (this.dataType) {
  14714. case Animation.ANIMATIONTYPE_FLOAT:
  14715. this._offsetsCache[keyOffset] = toValue - fromValue;
  14716. break;
  14717. case Animation.ANIMATIONTYPE_QUATERNION:
  14718. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14719. break;
  14720. case Animation.ANIMATIONTYPE_VECTOR3:
  14721. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14722. case Animation.ANIMATIONTYPE_VECTOR2:
  14723. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14724. case Animation.ANIMATIONTYPE_COLOR3:
  14725. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14726. default:
  14727. break;
  14728. }
  14729. this._highLimitsCache[keyOffset] = toValue;
  14730. }
  14731. highLimitValue = this._highLimitsCache[keyOffset];
  14732. offsetValue = this._offsetsCache[keyOffset];
  14733. }
  14734. }
  14735. if (offsetValue === undefined) {
  14736. switch (this.dataType) {
  14737. case Animation.ANIMATIONTYPE_FLOAT:
  14738. offsetValue = 0;
  14739. break;
  14740. case Animation.ANIMATIONTYPE_QUATERNION:
  14741. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14742. break;
  14743. case Animation.ANIMATIONTYPE_VECTOR3:
  14744. offsetValue = BABYLON.Vector3.Zero();
  14745. break;
  14746. case Animation.ANIMATIONTYPE_VECTOR2:
  14747. offsetValue = BABYLON.Vector2.Zero();
  14748. break;
  14749. case Animation.ANIMATIONTYPE_COLOR3:
  14750. offsetValue = BABYLON.Color3.Black();
  14751. }
  14752. }
  14753. // Compute value
  14754. var repeatCount = (ratio / range) >> 0;
  14755. var currentFrame = returnValue ? from + ratio % range : to;
  14756. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14757. // Set value
  14758. if (this.targetPropertyPath.length > 1) {
  14759. var property = this._target[this.targetPropertyPath[0]];
  14760. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14761. property = property[this.targetPropertyPath[index]];
  14762. }
  14763. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14764. } else {
  14765. this._target[this.targetPropertyPath[0]] = currentValue;
  14766. }
  14767. if (this._target.markAsDirty) {
  14768. this._target.markAsDirty(this.targetProperty);
  14769. }
  14770. if (!returnValue) {
  14771. this._stopped = true;
  14772. }
  14773. return returnValue;
  14774. };
  14775. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14776. get: function () {
  14777. return Animation._ANIMATIONTYPE_FLOAT;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14783. get: function () {
  14784. return Animation._ANIMATIONTYPE_VECTOR3;
  14785. },
  14786. enumerable: true,
  14787. configurable: true
  14788. });
  14789. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14790. get: function () {
  14791. return Animation._ANIMATIONTYPE_VECTOR2;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14797. get: function () {
  14798. return Animation._ANIMATIONTYPE_QUATERNION;
  14799. },
  14800. enumerable: true,
  14801. configurable: true
  14802. });
  14803. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14804. get: function () {
  14805. return Animation._ANIMATIONTYPE_MATRIX;
  14806. },
  14807. enumerable: true,
  14808. configurable: true
  14809. });
  14810. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14811. get: function () {
  14812. return Animation._ANIMATIONTYPE_COLOR3;
  14813. },
  14814. enumerable: true,
  14815. configurable: true
  14816. });
  14817. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14818. get: function () {
  14819. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14820. },
  14821. enumerable: true,
  14822. configurable: true
  14823. });
  14824. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14825. get: function () {
  14826. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14827. },
  14828. enumerable: true,
  14829. configurable: true
  14830. });
  14831. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14832. get: function () {
  14833. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14834. },
  14835. enumerable: true,
  14836. configurable: true
  14837. });
  14838. Animation._ANIMATIONTYPE_FLOAT = 0;
  14839. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  14840. Animation._ANIMATIONTYPE_QUATERNION = 2;
  14841. Animation._ANIMATIONTYPE_MATRIX = 3;
  14842. Animation._ANIMATIONTYPE_COLOR3 = 4;
  14843. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  14844. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  14845. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  14846. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  14847. return Animation;
  14848. })();
  14849. BABYLON.Animation = Animation;
  14850. })(BABYLON || (BABYLON = {}));
  14851. //# sourceMappingURL=babylon.animation.js.map
  14852. var BABYLON;
  14853. (function (BABYLON) {
  14854. var Animatable = (function () {
  14855. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  14856. if (typeof fromFrame === "undefined") { fromFrame = 0; }
  14857. if (typeof toFrame === "undefined") { toFrame = 100; }
  14858. if (typeof loopAnimation === "undefined") { loopAnimation = false; }
  14859. if (typeof speedRatio === "undefined") { speedRatio = 1.0; }
  14860. this.target = target;
  14861. this.fromFrame = fromFrame;
  14862. this.toFrame = toFrame;
  14863. this.loopAnimation = loopAnimation;
  14864. this.speedRatio = speedRatio;
  14865. this.onAnimationEnd = onAnimationEnd;
  14866. this._animations = new Array();
  14867. this._paused = false;
  14868. this.animationStarted = false;
  14869. if (animations) {
  14870. this.appendAnimations(target, animations);
  14871. }
  14872. this._scene = scene;
  14873. scene._activeAnimatables.push(this);
  14874. }
  14875. // Methods
  14876. Animatable.prototype.appendAnimations = function (target, animations) {
  14877. for (var index = 0; index < animations.length; index++) {
  14878. var animation = animations[index];
  14879. animation._target = target;
  14880. this._animations.push(animation);
  14881. }
  14882. };
  14883. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  14884. var animations = this._animations;
  14885. for (var index = 0; index < animations.length; index++) {
  14886. if (animations[index].targetProperty === property) {
  14887. return animations[index];
  14888. }
  14889. }
  14890. return null;
  14891. };
  14892. Animatable.prototype.pause = function () {
  14893. if (this._paused) {
  14894. return;
  14895. }
  14896. this._paused = true;
  14897. };
  14898. Animatable.prototype.restart = function () {
  14899. this._paused = false;
  14900. };
  14901. Animatable.prototype.stop = function () {
  14902. var index = this._scene._activeAnimatables.indexOf(this);
  14903. if (index > -1) {
  14904. this._scene._activeAnimatables.splice(index, 1);
  14905. }
  14906. if (this.onAnimationEnd) {
  14907. this.onAnimationEnd();
  14908. }
  14909. };
  14910. Animatable.prototype._animate = function (delay) {
  14911. if (this._paused) {
  14912. if (!this._pausedDelay) {
  14913. this._pausedDelay = delay;
  14914. }
  14915. return true;
  14916. }
  14917. if (!this._localDelayOffset) {
  14918. this._localDelayOffset = delay;
  14919. } else if (this._pausedDelay) {
  14920. this._localDelayOffset += delay - this._pausedDelay;
  14921. this._pausedDelay = null;
  14922. }
  14923. // Animating
  14924. var running = false;
  14925. var animations = this._animations;
  14926. for (var index = 0; index < animations.length; index++) {
  14927. var animation = animations[index];
  14928. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  14929. running = running || isRunning;
  14930. }
  14931. if (!running && this.onAnimationEnd) {
  14932. this.onAnimationEnd();
  14933. }
  14934. return running;
  14935. };
  14936. return Animatable;
  14937. })();
  14938. BABYLON.Animatable = Animatable;
  14939. })(BABYLON || (BABYLON = {}));
  14940. //# sourceMappingURL=babylon.animatable.js.map
  14941. var BABYLON;
  14942. (function (BABYLON) {
  14943. var EasingFunction = (function () {
  14944. function EasingFunction() {
  14945. // Properties
  14946. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  14947. }
  14948. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  14949. get: function () {
  14950. return EasingFunction._EASINGMODE_EASEIN;
  14951. },
  14952. enumerable: true,
  14953. configurable: true
  14954. });
  14955. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  14956. get: function () {
  14957. return EasingFunction._EASINGMODE_EASEOUT;
  14958. },
  14959. enumerable: true,
  14960. configurable: true
  14961. });
  14962. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  14963. get: function () {
  14964. return EasingFunction._EASINGMODE_EASEINOUT;
  14965. },
  14966. enumerable: true,
  14967. configurable: true
  14968. });
  14969. EasingFunction.prototype.setEasingMode = function (easingMode) {
  14970. var n = Math.min(Math.max(easingMode, 0), 2);
  14971. this._easingMode = n;
  14972. };
  14973. EasingFunction.prototype.getEasingMode = function () {
  14974. return this._easingMode;
  14975. };
  14976. EasingFunction.prototype.easeInCore = function (gradient) {
  14977. throw new Error('You must implement this method');
  14978. };
  14979. EasingFunction.prototype.ease = function (gradient) {
  14980. switch (this._easingMode) {
  14981. case EasingFunction.EASINGMODE_EASEIN:
  14982. return this.easeInCore(gradient);
  14983. case EasingFunction.EASINGMODE_EASEOUT:
  14984. return (1 - this.easeInCore(1 - gradient));
  14985. }
  14986. if (gradient >= 0.5) {
  14987. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  14988. }
  14989. return (this.easeInCore(gradient * 2) * 0.5);
  14990. };
  14991. EasingFunction._EASINGMODE_EASEIN = 0;
  14992. EasingFunction._EASINGMODE_EASEOUT = 1;
  14993. EasingFunction._EASINGMODE_EASEINOUT = 2;
  14994. return EasingFunction;
  14995. })();
  14996. BABYLON.EasingFunction = EasingFunction;
  14997. var CircleEase = (function (_super) {
  14998. __extends(CircleEase, _super);
  14999. function CircleEase() {
  15000. _super.apply(this, arguments);
  15001. }
  15002. CircleEase.prototype.easeInCore = function (gradient) {
  15003. gradient = Math.max(0, Math.min(1, gradient));
  15004. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15005. };
  15006. return CircleEase;
  15007. })(EasingFunction);
  15008. BABYLON.CircleEase = CircleEase;
  15009. var BackEase = (function (_super) {
  15010. __extends(BackEase, _super);
  15011. function BackEase(amplitude) {
  15012. if (typeof amplitude === "undefined") { amplitude = 1; }
  15013. _super.call(this);
  15014. this.amplitude = amplitude;
  15015. }
  15016. BackEase.prototype.easeInCore = function (gradient) {
  15017. var num = Math.max(0, this.amplitude);
  15018. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15019. };
  15020. return BackEase;
  15021. })(EasingFunction);
  15022. BABYLON.BackEase = BackEase;
  15023. var BounceEase = (function (_super) {
  15024. __extends(BounceEase, _super);
  15025. function BounceEase(bounces, bounciness) {
  15026. if (typeof bounces === "undefined") { bounces = 3; }
  15027. if (typeof bounciness === "undefined") { bounciness = 2; }
  15028. _super.call(this);
  15029. this.bounces = bounces;
  15030. this.bounciness = bounciness;
  15031. }
  15032. BounceEase.prototype.easeInCore = function (gradient) {
  15033. var y = Math.max(0.0, this.bounces);
  15034. var bounciness = this.bounciness;
  15035. if (bounciness <= 1.0) {
  15036. bounciness = 1.001;
  15037. }
  15038. var num9 = Math.pow(bounciness, y);
  15039. var num5 = 1.0 - bounciness;
  15040. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15041. var num15 = gradient * num4;
  15042. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15043. var num3 = Math.floor(num65);
  15044. var num13 = num3 + 1.0;
  15045. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15046. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15047. var num7 = (num8 + num12) * 0.5;
  15048. var num6 = gradient - num7;
  15049. var num2 = num7 - num8;
  15050. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15051. };
  15052. return BounceEase;
  15053. })(EasingFunction);
  15054. BABYLON.BounceEase = BounceEase;
  15055. var CubicEase = (function (_super) {
  15056. __extends(CubicEase, _super);
  15057. function CubicEase() {
  15058. _super.apply(this, arguments);
  15059. }
  15060. CubicEase.prototype.easeInCore = function (gradient) {
  15061. return (gradient * gradient * gradient);
  15062. };
  15063. return CubicEase;
  15064. })(EasingFunction);
  15065. BABYLON.CubicEase = CubicEase;
  15066. var ElasticEase = (function (_super) {
  15067. __extends(ElasticEase, _super);
  15068. function ElasticEase(oscillations, springiness) {
  15069. if (typeof oscillations === "undefined") { oscillations = 3; }
  15070. if (typeof springiness === "undefined") { springiness = 3; }
  15071. _super.call(this);
  15072. this.oscillations = oscillations;
  15073. this.springiness = springiness;
  15074. }
  15075. ElasticEase.prototype.easeInCore = function (gradient) {
  15076. var num2;
  15077. var num3 = Math.max(0.0, this.oscillations);
  15078. var num = Math.max(0.0, this.springiness);
  15079. if (num == 0) {
  15080. num2 = gradient;
  15081. } else {
  15082. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15083. }
  15084. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15085. };
  15086. return ElasticEase;
  15087. })(EasingFunction);
  15088. BABYLON.ElasticEase = ElasticEase;
  15089. var ExponentialEase = (function (_super) {
  15090. __extends(ExponentialEase, _super);
  15091. function ExponentialEase(exponent) {
  15092. if (typeof exponent === "undefined") { exponent = 2; }
  15093. _super.call(this);
  15094. this.exponent = exponent;
  15095. }
  15096. ExponentialEase.prototype.easeInCore = function (gradient) {
  15097. if (this.exponent <= 0) {
  15098. return gradient;
  15099. }
  15100. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15101. };
  15102. return ExponentialEase;
  15103. })(EasingFunction);
  15104. BABYLON.ExponentialEase = ExponentialEase;
  15105. var PowerEase = (function (_super) {
  15106. __extends(PowerEase, _super);
  15107. function PowerEase(power) {
  15108. if (typeof power === "undefined") { power = 2; }
  15109. _super.call(this);
  15110. this.power = power;
  15111. }
  15112. PowerEase.prototype.easeInCore = function (gradient) {
  15113. var y = Math.max(0.0, this.power);
  15114. return Math.pow(gradient, y);
  15115. };
  15116. return PowerEase;
  15117. })(EasingFunction);
  15118. BABYLON.PowerEase = PowerEase;
  15119. var QuadraticEase = (function (_super) {
  15120. __extends(QuadraticEase, _super);
  15121. function QuadraticEase() {
  15122. _super.apply(this, arguments);
  15123. }
  15124. QuadraticEase.prototype.easeInCore = function (gradient) {
  15125. return (gradient * gradient);
  15126. };
  15127. return QuadraticEase;
  15128. })(EasingFunction);
  15129. BABYLON.QuadraticEase = QuadraticEase;
  15130. var QuarticEase = (function (_super) {
  15131. __extends(QuarticEase, _super);
  15132. function QuarticEase() {
  15133. _super.apply(this, arguments);
  15134. }
  15135. QuarticEase.prototype.easeInCore = function (gradient) {
  15136. return (gradient * gradient * gradient * gradient);
  15137. };
  15138. return QuarticEase;
  15139. })(EasingFunction);
  15140. BABYLON.QuarticEase = QuarticEase;
  15141. var QuinticEase = (function (_super) {
  15142. __extends(QuinticEase, _super);
  15143. function QuinticEase() {
  15144. _super.apply(this, arguments);
  15145. }
  15146. QuinticEase.prototype.easeInCore = function (gradient) {
  15147. return (gradient * gradient * gradient * gradient * gradient);
  15148. };
  15149. return QuinticEase;
  15150. })(EasingFunction);
  15151. BABYLON.QuinticEase = QuinticEase;
  15152. var SineEase = (function (_super) {
  15153. __extends(SineEase, _super);
  15154. function SineEase() {
  15155. _super.apply(this, arguments);
  15156. }
  15157. SineEase.prototype.easeInCore = function (gradient) {
  15158. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15159. };
  15160. return SineEase;
  15161. })(EasingFunction);
  15162. BABYLON.SineEase = SineEase;
  15163. var BezierCurveEase = (function (_super) {
  15164. __extends(BezierCurveEase, _super);
  15165. function BezierCurveEase(x1, y1, x2, y2) {
  15166. if (typeof x1 === "undefined") { x1 = 0; }
  15167. if (typeof y1 === "undefined") { y1 = 0; }
  15168. if (typeof x2 === "undefined") { x2 = 1; }
  15169. if (typeof y2 === "undefined") { y2 = 1; }
  15170. _super.call(this);
  15171. this.x1 = x1;
  15172. this.y1 = y1;
  15173. this.x2 = x2;
  15174. this.y2 = y2;
  15175. }
  15176. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15177. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15178. };
  15179. return BezierCurveEase;
  15180. })(EasingFunction);
  15181. BABYLON.BezierCurveEase = BezierCurveEase;
  15182. })(BABYLON || (BABYLON = {}));
  15183. //# sourceMappingURL=babylon.easing.js.map
  15184. var BABYLON;
  15185. (function (BABYLON) {
  15186. var Octree = (function () {
  15187. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15188. if (typeof maxDepth === "undefined") { maxDepth = 2; }
  15189. this.maxDepth = maxDepth;
  15190. this.dynamicContent = new Array();
  15191. this._maxBlockCapacity = maxBlockCapacity || 64;
  15192. this._selectionContent = new BABYLON.SmartArray(1024);
  15193. this._creationFunc = creationFunc;
  15194. }
  15195. // Methods
  15196. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15197. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15198. };
  15199. Octree.prototype.addMesh = function (entry) {
  15200. for (var index = 0; index < this.blocks.length; index++) {
  15201. var block = this.blocks[index];
  15202. block.addEntry(entry);
  15203. }
  15204. };
  15205. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15206. this._selectionContent.reset();
  15207. for (var index = 0; index < this.blocks.length; index++) {
  15208. var block = this.blocks[index];
  15209. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15210. }
  15211. if (allowDuplicate) {
  15212. this._selectionContent.concat(this.dynamicContent);
  15213. } else {
  15214. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15215. }
  15216. return this._selectionContent;
  15217. };
  15218. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15219. this._selectionContent.reset();
  15220. for (var index = 0; index < this.blocks.length; index++) {
  15221. var block = this.blocks[index];
  15222. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15223. }
  15224. if (allowDuplicate) {
  15225. this._selectionContent.concat(this.dynamicContent);
  15226. } else {
  15227. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15228. }
  15229. return this._selectionContent;
  15230. };
  15231. Octree.prototype.intersectsRay = function (ray) {
  15232. this._selectionContent.reset();
  15233. for (var index = 0; index < this.blocks.length; index++) {
  15234. var block = this.blocks[index];
  15235. block.intersectsRay(ray, this._selectionContent);
  15236. }
  15237. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15238. return this._selectionContent;
  15239. };
  15240. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15241. target.blocks = new Array();
  15242. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15243. for (var x = 0; x < 2; x++) {
  15244. for (var y = 0; y < 2; y++) {
  15245. for (var z = 0; z < 2; z++) {
  15246. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15247. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15248. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15249. block.addEntries(entries);
  15250. target.blocks.push(block);
  15251. }
  15252. }
  15253. }
  15254. };
  15255. Octree.CreationFuncForMeshes = function (entry, block) {
  15256. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15257. block.entries.push(entry);
  15258. }
  15259. };
  15260. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15261. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15262. block.entries.push(entry);
  15263. }
  15264. };
  15265. return Octree;
  15266. })();
  15267. BABYLON.Octree = Octree;
  15268. })(BABYLON || (BABYLON = {}));
  15269. //# sourceMappingURL=babylon.octree.js.map
  15270. var BABYLON;
  15271. (function (BABYLON) {
  15272. var OctreeBlock = (function () {
  15273. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15274. this.entries = new Array();
  15275. this._boundingVectors = new Array();
  15276. this._capacity = capacity;
  15277. this._depth = depth;
  15278. this._maxDepth = maxDepth;
  15279. this._creationFunc = creationFunc;
  15280. this._minPoint = minPoint;
  15281. this._maxPoint = maxPoint;
  15282. this._boundingVectors.push(minPoint.clone());
  15283. this._boundingVectors.push(maxPoint.clone());
  15284. this._boundingVectors.push(minPoint.clone());
  15285. this._boundingVectors[2].x = maxPoint.x;
  15286. this._boundingVectors.push(minPoint.clone());
  15287. this._boundingVectors[3].y = maxPoint.y;
  15288. this._boundingVectors.push(minPoint.clone());
  15289. this._boundingVectors[4].z = maxPoint.z;
  15290. this._boundingVectors.push(maxPoint.clone());
  15291. this._boundingVectors[5].z = minPoint.z;
  15292. this._boundingVectors.push(maxPoint.clone());
  15293. this._boundingVectors[6].x = minPoint.x;
  15294. this._boundingVectors.push(maxPoint.clone());
  15295. this._boundingVectors[7].y = minPoint.y;
  15296. }
  15297. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15298. // Property
  15299. get: function () {
  15300. return this._capacity;
  15301. },
  15302. enumerable: true,
  15303. configurable: true
  15304. });
  15305. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15306. get: function () {
  15307. return this._minPoint;
  15308. },
  15309. enumerable: true,
  15310. configurable: true
  15311. });
  15312. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15313. get: function () {
  15314. return this._maxPoint;
  15315. },
  15316. enumerable: true,
  15317. configurable: true
  15318. });
  15319. // Methods
  15320. OctreeBlock.prototype.addEntry = function (entry) {
  15321. if (this.blocks) {
  15322. for (var index = 0; index < this.blocks.length; index++) {
  15323. var block = this.blocks[index];
  15324. block.addEntry(entry);
  15325. }
  15326. return;
  15327. }
  15328. this._creationFunc(entry, this);
  15329. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15330. this.createInnerBlocks();
  15331. }
  15332. };
  15333. OctreeBlock.prototype.addEntries = function (entries) {
  15334. for (var index = 0; index < entries.length; index++) {
  15335. var mesh = entries[index];
  15336. this.addEntry(mesh);
  15337. }
  15338. };
  15339. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15340. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15341. if (this.blocks) {
  15342. for (var index = 0; index < this.blocks.length; index++) {
  15343. var block = this.blocks[index];
  15344. block.select(frustumPlanes, selection, allowDuplicate);
  15345. }
  15346. return;
  15347. }
  15348. if (allowDuplicate) {
  15349. selection.concat(this.entries);
  15350. } else {
  15351. selection.concatWithNoDuplicate(this.entries);
  15352. }
  15353. }
  15354. };
  15355. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15356. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15357. if (this.blocks) {
  15358. for (var index = 0; index < this.blocks.length; index++) {
  15359. var block = this.blocks[index];
  15360. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15361. }
  15362. return;
  15363. }
  15364. if (allowDuplicate) {
  15365. selection.concat(this.entries);
  15366. } else {
  15367. selection.concatWithNoDuplicate(this.entries);
  15368. }
  15369. }
  15370. };
  15371. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15372. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15373. if (this.blocks) {
  15374. for (var index = 0; index < this.blocks.length; index++) {
  15375. var block = this.blocks[index];
  15376. block.intersectsRay(ray, selection);
  15377. }
  15378. return;
  15379. }
  15380. selection.concatWithNoDuplicate(this.entries);
  15381. }
  15382. };
  15383. OctreeBlock.prototype.createInnerBlocks = function () {
  15384. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15385. };
  15386. return OctreeBlock;
  15387. })();
  15388. BABYLON.OctreeBlock = OctreeBlock;
  15389. })(BABYLON || (BABYLON = {}));
  15390. //# sourceMappingURL=babylon.octreeBlock.js.map
  15391. var BABYLON;
  15392. (function (BABYLON) {
  15393. var Bone = (function () {
  15394. function Bone(name, skeleton, parentBone, matrix) {
  15395. this.name = name;
  15396. this.children = new Array();
  15397. this.animations = new Array();
  15398. this._worldTransform = new BABYLON.Matrix();
  15399. this._absoluteTransform = new BABYLON.Matrix();
  15400. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15401. this._skeleton = skeleton;
  15402. this._matrix = matrix;
  15403. this._baseMatrix = matrix;
  15404. skeleton.bones.push(this);
  15405. if (parentBone) {
  15406. this._parent = parentBone;
  15407. parentBone.children.push(this);
  15408. } else {
  15409. this._parent = null;
  15410. }
  15411. this._updateDifferenceMatrix();
  15412. }
  15413. // Members
  15414. Bone.prototype.getParent = function () {
  15415. return this._parent;
  15416. };
  15417. Bone.prototype.getLocalMatrix = function () {
  15418. return this._matrix;
  15419. };
  15420. Bone.prototype.getBaseMatrix = function () {
  15421. return this._baseMatrix;
  15422. };
  15423. Bone.prototype.getWorldMatrix = function () {
  15424. return this._worldTransform;
  15425. };
  15426. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15427. return this._invertedAbsoluteTransform;
  15428. };
  15429. Bone.prototype.getAbsoluteMatrix = function () {
  15430. var matrix = this._matrix.clone();
  15431. var parent = this._parent;
  15432. while (parent) {
  15433. matrix = matrix.multiply(parent.getLocalMatrix());
  15434. parent = parent.getParent();
  15435. }
  15436. return matrix;
  15437. };
  15438. // Methods
  15439. Bone.prototype.updateMatrix = function (matrix) {
  15440. this._matrix = matrix;
  15441. this._skeleton._markAsDirty();
  15442. this._updateDifferenceMatrix();
  15443. };
  15444. Bone.prototype._updateDifferenceMatrix = function () {
  15445. if (this._parent) {
  15446. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15447. } else {
  15448. this._absoluteTransform.copyFrom(this._matrix);
  15449. }
  15450. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15451. for (var index = 0; index < this.children.length; index++) {
  15452. this.children[index]._updateDifferenceMatrix();
  15453. }
  15454. };
  15455. Bone.prototype.markAsDirty = function () {
  15456. this._skeleton._markAsDirty();
  15457. };
  15458. return Bone;
  15459. })();
  15460. BABYLON.Bone = Bone;
  15461. })(BABYLON || (BABYLON = {}));
  15462. //# sourceMappingURL=babylon.bone.js.map
  15463. var BABYLON;
  15464. (function (BABYLON) {
  15465. var Skeleton = (function () {
  15466. function Skeleton(name, id, scene) {
  15467. this.name = name;
  15468. this.id = id;
  15469. this.bones = new Array();
  15470. this._isDirty = true;
  15471. this._identity = BABYLON.Matrix.Identity();
  15472. this.bones = [];
  15473. this._scene = scene;
  15474. scene.skeletons.push(this);
  15475. }
  15476. // Members
  15477. Skeleton.prototype.getTransformMatrices = function () {
  15478. return this._transformMatrices;
  15479. };
  15480. // Methods
  15481. Skeleton.prototype._markAsDirty = function () {
  15482. this._isDirty = true;
  15483. };
  15484. Skeleton.prototype.prepare = function () {
  15485. if (!this._isDirty) {
  15486. return;
  15487. }
  15488. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15489. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15490. }
  15491. for (var index = 0; index < this.bones.length; index++) {
  15492. var bone = this.bones[index];
  15493. var parentBone = bone.getParent();
  15494. if (parentBone) {
  15495. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15496. } else {
  15497. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15498. }
  15499. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15500. }
  15501. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15502. this._isDirty = false;
  15503. };
  15504. Skeleton.prototype.getAnimatables = function () {
  15505. if (!this._animatables || this._animatables.length != this.bones.length) {
  15506. this._animatables = [];
  15507. for (var index = 0; index < this.bones.length; index++) {
  15508. this._animatables.push(this.bones[index]);
  15509. }
  15510. }
  15511. return this._animatables;
  15512. };
  15513. Skeleton.prototype.clone = function (name, id) {
  15514. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15515. for (var index = 0; index < this.bones.length; index++) {
  15516. var source = this.bones[index];
  15517. var parentBone = null;
  15518. if (source.getParent()) {
  15519. var parentIndex = this.bones.indexOf(source.getParent());
  15520. parentBone = result.bones[parentIndex];
  15521. }
  15522. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15523. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15524. }
  15525. return result;
  15526. };
  15527. return Skeleton;
  15528. })();
  15529. BABYLON.Skeleton = Skeleton;
  15530. })(BABYLON || (BABYLON = {}));
  15531. //# sourceMappingURL=babylon.skeleton.js.map
  15532. var BABYLON;
  15533. (function (BABYLON) {
  15534. var PostProcess = (function () {
  15535. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15536. this.name = name;
  15537. this.width = -1;
  15538. this.height = -1;
  15539. this._reusable = false;
  15540. this._textures = new BABYLON.SmartArray(2);
  15541. this._currentRenderTextureInd = 0;
  15542. if (camera != null) {
  15543. this._camera = camera;
  15544. this._scene = camera.getScene();
  15545. camera.attachPostProcess(this);
  15546. this._engine = this._scene.getEngine();
  15547. } else {
  15548. this._engine = engine;
  15549. }
  15550. this._renderRatio = ratio;
  15551. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15552. this._reusable = reusable || false;
  15553. samplers = samplers || [];
  15554. samplers.push("textureSampler");
  15555. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15556. }
  15557. PostProcess.prototype.isReusable = function () {
  15558. return this._reusable;
  15559. };
  15560. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15561. camera = camera || this._camera;
  15562. var scene = camera.getScene();
  15563. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15564. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15565. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15566. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15567. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15568. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15569. if (this._textures.length > 0) {
  15570. for (var i = 0; i < this._textures.length; i++) {
  15571. this._engine._releaseTexture(this._textures.data[i]);
  15572. }
  15573. this._textures.reset();
  15574. }
  15575. this.width = desiredWidth;
  15576. this.height = desiredHeight;
  15577. 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 }));
  15578. if (this._reusable) {
  15579. 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 }));
  15580. }
  15581. if (this.onSizeChanged) {
  15582. this.onSizeChanged();
  15583. }
  15584. }
  15585. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15586. if (this.onActivate) {
  15587. this.onActivate(camera);
  15588. }
  15589. // Clear
  15590. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15591. if (this._reusable) {
  15592. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15593. }
  15594. };
  15595. PostProcess.prototype.apply = function () {
  15596. // Check
  15597. if (!this._effect.isReady())
  15598. return null;
  15599. // States
  15600. this._engine.enableEffect(this._effect);
  15601. this._engine.setState(false);
  15602. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15603. this._engine.setDepthBuffer(false);
  15604. this._engine.setDepthWrite(false);
  15605. // Texture
  15606. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15607. // Parameters
  15608. if (this.onApply) {
  15609. this.onApply(this._effect);
  15610. }
  15611. return this._effect;
  15612. };
  15613. PostProcess.prototype.dispose = function (camera) {
  15614. camera = camera || this._camera;
  15615. if (this._textures.length > 0) {
  15616. for (var i = 0; i < this._textures.length; i++) {
  15617. this._engine._releaseTexture(this._textures.data[i]);
  15618. }
  15619. this._textures.reset();
  15620. }
  15621. camera.detachPostProcess(this);
  15622. var index = camera._postProcesses.indexOf(this);
  15623. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15624. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15625. }
  15626. };
  15627. return PostProcess;
  15628. })();
  15629. BABYLON.PostProcess = PostProcess;
  15630. })(BABYLON || (BABYLON = {}));
  15631. //# sourceMappingURL=babylon.postProcess.js.map
  15632. var BABYLON;
  15633. (function (BABYLON) {
  15634. var PostProcessManager = (function () {
  15635. function PostProcessManager(scene) {
  15636. this._vertexDeclaration = [2];
  15637. this._vertexStrideSize = 2 * 4;
  15638. this._scene = scene;
  15639. // VBO
  15640. var vertices = [];
  15641. vertices.push(1, 1);
  15642. vertices.push(-1, 1);
  15643. vertices.push(-1, -1);
  15644. vertices.push(1, -1);
  15645. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15646. // Indices
  15647. var indices = [];
  15648. indices.push(0);
  15649. indices.push(1);
  15650. indices.push(2);
  15651. indices.push(0);
  15652. indices.push(2);
  15653. indices.push(3);
  15654. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15655. }
  15656. // Methods
  15657. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15658. var postProcesses = this._scene.activeCamera._postProcesses;
  15659. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15660. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15661. return false;
  15662. }
  15663. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15664. return true;
  15665. };
  15666. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15667. var postProcesses = this._scene.activeCamera._postProcesses;
  15668. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15669. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15670. return;
  15671. }
  15672. var engine = this._scene.getEngine();
  15673. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15674. if (index < postProcessesTakenIndices.length - 1) {
  15675. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15676. } else {
  15677. if (targetTexture) {
  15678. engine.bindFramebuffer(targetTexture);
  15679. } else {
  15680. engine.restoreDefaultFramebuffer();
  15681. }
  15682. }
  15683. if (doNotPresent) {
  15684. break;
  15685. }
  15686. var pp = postProcesses[postProcessesTakenIndices[index]];
  15687. var effect = pp.apply();
  15688. if (effect) {
  15689. if (pp.onBeforeRender) {
  15690. pp.onBeforeRender(effect);
  15691. }
  15692. // VBOs
  15693. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15694. // Draw order
  15695. engine.draw(true, 0, 6);
  15696. }
  15697. }
  15698. // Restore depth buffer
  15699. engine.setDepthBuffer(true);
  15700. engine.setDepthWrite(true);
  15701. };
  15702. PostProcessManager.prototype.dispose = function () {
  15703. if (this._vertexBuffer) {
  15704. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15705. this._vertexBuffer = null;
  15706. }
  15707. if (this._indexBuffer) {
  15708. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15709. this._indexBuffer = null;
  15710. }
  15711. };
  15712. return PostProcessManager;
  15713. })();
  15714. BABYLON.PostProcessManager = PostProcessManager;
  15715. })(BABYLON || (BABYLON = {}));
  15716. //# sourceMappingURL=babylon.postProcessManager.js.map
  15717. var BABYLON;
  15718. (function (BABYLON) {
  15719. var PassPostProcess = (function (_super) {
  15720. __extends(PassPostProcess, _super);
  15721. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15722. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15723. }
  15724. return PassPostProcess;
  15725. })(BABYLON.PostProcess);
  15726. BABYLON.PassPostProcess = PassPostProcess;
  15727. })(BABYLON || (BABYLON = {}));
  15728. //# sourceMappingURL=babylon.passPostProcess.js.map
  15729. var BABYLON;
  15730. (function (BABYLON) {
  15731. var BlurPostProcess = (function (_super) {
  15732. __extends(BlurPostProcess, _super);
  15733. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15734. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15735. var _this = this;
  15736. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15737. this.direction = direction;
  15738. this.blurWidth = blurWidth;
  15739. this.onApply = function (effect) {
  15740. effect.setFloat2("screenSize", _this.width, _this.height);
  15741. effect.setVector2("direction", _this.direction);
  15742. effect.setFloat("blurWidth", _this.blurWidth);
  15743. };
  15744. }
  15745. return BlurPostProcess;
  15746. })(BABYLON.PostProcess);
  15747. BABYLON.BlurPostProcess = BlurPostProcess;
  15748. })(BABYLON || (BABYLON = {}));
  15749. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15750. var BABYLON;
  15751. (function (BABYLON) {
  15752. var FilterPostProcess = (function (_super) {
  15753. __extends(FilterPostProcess, _super);
  15754. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15755. var _this = this;
  15756. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15757. this.kernelMatrix = kernelMatrix;
  15758. this.onApply = function (effect) {
  15759. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15760. };
  15761. }
  15762. return FilterPostProcess;
  15763. })(BABYLON.PostProcess);
  15764. BABYLON.FilterPostProcess = FilterPostProcess;
  15765. })(BABYLON || (BABYLON = {}));
  15766. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15767. var BABYLON;
  15768. (function (BABYLON) {
  15769. var RefractionPostProcess = (function (_super) {
  15770. __extends(RefractionPostProcess, _super);
  15771. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15772. var _this = this;
  15773. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15774. this.color = color;
  15775. this.depth = depth;
  15776. this.colorLevel = colorLevel;
  15777. this.onActivate = function (cam) {
  15778. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15779. };
  15780. this.onApply = function (effect) {
  15781. effect.setColor3("baseColor", _this.color);
  15782. effect.setFloat("depth", _this.depth);
  15783. effect.setFloat("colorLevel", _this.colorLevel);
  15784. effect.setTexture("refractionSampler", _this._refRexture);
  15785. };
  15786. }
  15787. // Methods
  15788. RefractionPostProcess.prototype.dispose = function (camera) {
  15789. if (this._refRexture) {
  15790. this._refRexture.dispose();
  15791. }
  15792. _super.prototype.dispose.call(this, camera);
  15793. };
  15794. return RefractionPostProcess;
  15795. })(BABYLON.PostProcess);
  15796. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15797. })(BABYLON || (BABYLON = {}));
  15798. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15799. var BABYLON;
  15800. (function (BABYLON) {
  15801. var BlackAndWhitePostProcess = (function (_super) {
  15802. __extends(BlackAndWhitePostProcess, _super);
  15803. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15804. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15805. }
  15806. return BlackAndWhitePostProcess;
  15807. })(BABYLON.PostProcess);
  15808. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15809. })(BABYLON || (BABYLON = {}));
  15810. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15811. var BABYLON;
  15812. (function (BABYLON) {
  15813. var ConvolutionPostProcess = (function (_super) {
  15814. __extends(ConvolutionPostProcess, _super);
  15815. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15816. var _this = this;
  15817. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15818. this.kernel = kernel;
  15819. this.onApply = function (effect) {
  15820. effect.setFloat2("screenSize", _this.width, _this.height);
  15821. effect.setArray("kernel", _this.kernel);
  15822. };
  15823. }
  15824. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15825. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15826. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  15827. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  15828. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  15829. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  15830. return ConvolutionPostProcess;
  15831. })(BABYLON.PostProcess);
  15832. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  15833. })(BABYLON || (BABYLON = {}));
  15834. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  15835. var BABYLON;
  15836. (function (BABYLON) {
  15837. var FxaaPostProcess = (function (_super) {
  15838. __extends(FxaaPostProcess, _super);
  15839. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15840. var _this = this;
  15841. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  15842. this.onSizeChanged = function () {
  15843. _this.texelWidth = 1.0 / _this.width;
  15844. _this.texelHeight = 1.0 / _this.height;
  15845. };
  15846. this.onApply = function (effect) {
  15847. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  15848. };
  15849. }
  15850. return FxaaPostProcess;
  15851. })(BABYLON.PostProcess);
  15852. BABYLON.FxaaPostProcess = FxaaPostProcess;
  15853. })(BABYLON || (BABYLON = {}));
  15854. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  15855. var BABYLON;
  15856. (function (BABYLON) {
  15857. var LensFlare = (function () {
  15858. function LensFlare(size, position, color, imgUrl, system) {
  15859. this.size = size;
  15860. this.position = position;
  15861. this.dispose = function () {
  15862. if (this.texture) {
  15863. this.texture.dispose();
  15864. }
  15865. // Remove from scene
  15866. var index = this._system.lensFlares.indexOf(this);
  15867. this._system.lensFlares.splice(index, 1);
  15868. };
  15869. this.color = color || new BABYLON.Color3(1, 1, 1);
  15870. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  15871. this._system = system;
  15872. system.lensFlares.push(this);
  15873. }
  15874. return LensFlare;
  15875. })();
  15876. BABYLON.LensFlare = LensFlare;
  15877. })(BABYLON || (BABYLON = {}));
  15878. //# sourceMappingURL=babylon.lensFlare.js.map
  15879. var BABYLON;
  15880. (function (BABYLON) {
  15881. var LensFlareSystem = (function () {
  15882. function LensFlareSystem(name, emitter, scene) {
  15883. this.name = name;
  15884. this.lensFlares = new Array();
  15885. this.borderLimit = 300;
  15886. this._vertexDeclaration = [2];
  15887. this._vertexStrideSize = 2 * 4;
  15888. this._isEnabled = true;
  15889. this._scene = scene;
  15890. this._emitter = emitter;
  15891. scene.lensFlareSystems.push(this);
  15892. this.meshesSelectionPredicate = function (m) {
  15893. return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0);
  15894. };
  15895. // VBO
  15896. var vertices = [];
  15897. vertices.push(1, 1);
  15898. vertices.push(-1, 1);
  15899. vertices.push(-1, -1);
  15900. vertices.push(1, -1);
  15901. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15902. // Indices
  15903. var indices = [];
  15904. indices.push(0);
  15905. indices.push(1);
  15906. indices.push(2);
  15907. indices.push(0);
  15908. indices.push(2);
  15909. indices.push(3);
  15910. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15911. // Effects
  15912. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  15913. }
  15914. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  15915. get: function () {
  15916. return this._isEnabled;
  15917. },
  15918. set: function (value) {
  15919. this._isEnabled = value;
  15920. },
  15921. enumerable: true,
  15922. configurable: true
  15923. });
  15924. LensFlareSystem.prototype.getScene = function () {
  15925. return this._scene;
  15926. };
  15927. LensFlareSystem.prototype.getEmitter = function () {
  15928. return this._emitter;
  15929. };
  15930. LensFlareSystem.prototype.getEmitterPosition = function () {
  15931. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  15932. };
  15933. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  15934. var position = this.getEmitterPosition();
  15935. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  15936. this._positionX = position.x;
  15937. this._positionY = position.y;
  15938. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  15939. if (position.z > 0) {
  15940. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  15941. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  15942. return true;
  15943. }
  15944. }
  15945. return false;
  15946. };
  15947. LensFlareSystem.prototype._isVisible = function () {
  15948. if (!this._isEnabled) {
  15949. return false;
  15950. }
  15951. var emitterPosition = this.getEmitterPosition();
  15952. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  15953. var distance = direction.length();
  15954. direction.normalize();
  15955. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  15956. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  15957. return !pickInfo.hit || pickInfo.distance > distance;
  15958. };
  15959. LensFlareSystem.prototype.render = function () {
  15960. if (!this._effect.isReady())
  15961. return false;
  15962. var engine = this._scene.getEngine();
  15963. var viewport = this._scene.activeCamera.viewport;
  15964. var globalViewport = viewport.toGlobal(engine);
  15965. // Position
  15966. if (!this.computeEffectivePosition(globalViewport)) {
  15967. return false;
  15968. }
  15969. // Visibility
  15970. if (!this._isVisible()) {
  15971. return false;
  15972. }
  15973. // Intensity
  15974. var awayX;
  15975. var awayY;
  15976. if (this._positionX < this.borderLimit + globalViewport.x) {
  15977. awayX = this.borderLimit + globalViewport.x - this._positionX;
  15978. } else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  15979. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  15980. } else {
  15981. awayX = 0;
  15982. }
  15983. if (this._positionY < this.borderLimit + globalViewport.y) {
  15984. awayY = this.borderLimit + globalViewport.y - this._positionY;
  15985. } else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  15986. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  15987. } else {
  15988. awayY = 0;
  15989. }
  15990. var away = (awayX > awayY) ? awayX : awayY;
  15991. if (away > this.borderLimit) {
  15992. away = this.borderLimit;
  15993. }
  15994. var intensity = 1.0 - (away / this.borderLimit);
  15995. if (intensity < 0) {
  15996. return false;
  15997. }
  15998. if (intensity > 1.0) {
  15999. intensity = 1.0;
  16000. }
  16001. // Position
  16002. var centerX = globalViewport.x + globalViewport.width / 2;
  16003. var centerY = globalViewport.y + globalViewport.height / 2;
  16004. var distX = centerX - this._positionX;
  16005. var distY = centerY - this._positionY;
  16006. // Effects
  16007. engine.enableEffect(this._effect);
  16008. engine.setState(false);
  16009. engine.setDepthBuffer(false);
  16010. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16011. // VBOs
  16012. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16013. for (var index = 0; index < this.lensFlares.length; index++) {
  16014. var flare = this.lensFlares[index];
  16015. var x = centerX - (distX * flare.position);
  16016. var y = centerY - (distY * flare.position);
  16017. var cw = flare.size;
  16018. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16019. var cx = 2 * (x / globalViewport.width) - 1.0;
  16020. var cy = 1.0 - 2 * (y / globalViewport.height);
  16021. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16022. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16023. // Texture
  16024. this._effect.setTexture("textureSampler", flare.texture);
  16025. // Color
  16026. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16027. // Draw order
  16028. engine.draw(true, 0, 6);
  16029. }
  16030. engine.setDepthBuffer(true);
  16031. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16032. return true;
  16033. };
  16034. LensFlareSystem.prototype.dispose = function () {
  16035. if (this._vertexBuffer) {
  16036. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16037. this._vertexBuffer = null;
  16038. }
  16039. if (this._indexBuffer) {
  16040. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16041. this._indexBuffer = null;
  16042. }
  16043. while (this.lensFlares.length) {
  16044. this.lensFlares[0].dispose();
  16045. }
  16046. // Remove from scene
  16047. var index = this._scene.lensFlareSystems.indexOf(this);
  16048. this._scene.lensFlareSystems.splice(index, 1);
  16049. };
  16050. return LensFlareSystem;
  16051. })();
  16052. BABYLON.LensFlareSystem = LensFlareSystem;
  16053. })(BABYLON || (BABYLON = {}));
  16054. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  16055. var BABYLON;
  16056. (function (BABYLON) {
  16057. var IntersectionInfo = (function () {
  16058. function IntersectionInfo(bu, bv, distance) {
  16059. this.bu = bu;
  16060. this.bv = bv;
  16061. this.distance = distance;
  16062. this.faceId = 0;
  16063. }
  16064. return IntersectionInfo;
  16065. })();
  16066. BABYLON.IntersectionInfo = IntersectionInfo;
  16067. var PickingInfo = (function () {
  16068. function PickingInfo() {
  16069. this.hit = false;
  16070. this.distance = 0;
  16071. this.pickedPoint = null;
  16072. this.pickedMesh = null;
  16073. this.bu = 0;
  16074. this.bv = 0;
  16075. this.faceId = -1;
  16076. }
  16077. // Methods
  16078. PickingInfo.prototype.getNormal = function () {
  16079. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16080. return null;
  16081. }
  16082. var indices = this.pickedMesh.getIndices();
  16083. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16084. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16085. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16086. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16087. normal0 = normal0.scale(this.bu);
  16088. normal1 = normal1.scale(this.bv);
  16089. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16090. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16091. };
  16092. PickingInfo.prototype.getTextureCoordinates = function () {
  16093. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16094. return null;
  16095. }
  16096. var indices = this.pickedMesh.getIndices();
  16097. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16098. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16099. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16100. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16101. uv0 = uv0.scale(this.bu);
  16102. uv1 = uv1.scale(this.bv);
  16103. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16104. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16105. };
  16106. return PickingInfo;
  16107. })();
  16108. BABYLON.PickingInfo = PickingInfo;
  16109. })(BABYLON || (BABYLON = {}));
  16110. //# sourceMappingURL=babylon.pickingInfo.js.map
  16111. var BABYLON;
  16112. (function (BABYLON) {
  16113. var FilesInput = (function () {
  16114. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16115. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16116. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16117. this.engine = p_engine;
  16118. this.canvas = p_canvas;
  16119. this.currentScene = p_scene;
  16120. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16121. this.progressCallback = p_progressCallback;
  16122. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16123. this.textureLoadingCallback = p_textureLoadingCallback;
  16124. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16125. }
  16126. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16127. var _this = this;
  16128. if (p_elementToMonitor) {
  16129. this.elementToMonitor = p_elementToMonitor;
  16130. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16131. _this.drag(e);
  16132. }, false);
  16133. this.elementToMonitor.addEventListener("dragover", function (e) {
  16134. _this.drag(e);
  16135. }, false);
  16136. this.elementToMonitor.addEventListener("drop", function (e) {
  16137. _this.drop(e);
  16138. }, false);
  16139. }
  16140. };
  16141. FilesInput.prototype.renderFunction = function () {
  16142. if (this.additionnalRenderLoopLogicCallback) {
  16143. this.additionnalRenderLoopLogicCallback();
  16144. }
  16145. if (this.currentScene) {
  16146. if (this.textureLoadingCallback) {
  16147. var remaining = this.currentScene.getWaitingItemsCount();
  16148. if (remaining > 0) {
  16149. this.textureLoadingCallback(remaining);
  16150. }
  16151. }
  16152. this.currentScene.render();
  16153. }
  16154. };
  16155. FilesInput.prototype.drag = function (e) {
  16156. e.stopPropagation();
  16157. e.preventDefault();
  16158. };
  16159. FilesInput.prototype.drop = function (eventDrop) {
  16160. eventDrop.stopPropagation();
  16161. eventDrop.preventDefault();
  16162. this.loadFiles(eventDrop);
  16163. };
  16164. FilesInput.prototype.loadFiles = function (event) {
  16165. var _this = this;
  16166. var that = this;
  16167. if (this.startingProcessingFilesCallback)
  16168. this.startingProcessingFilesCallback();
  16169. var sceneFileToLoad;
  16170. var filesToLoad;
  16171. // Handling data transfer via drag'n'drop
  16172. if (event && event.dataTransfer && event.dataTransfer.files) {
  16173. filesToLoad = event.dataTransfer.files;
  16174. }
  16175. // Handling files from input files
  16176. if (event && event.target && event.target.files) {
  16177. filesToLoad = event.target.files;
  16178. }
  16179. if (filesToLoad && filesToLoad.length > 0) {
  16180. for (var i = 0; i < filesToLoad.length; i++) {
  16181. switch (filesToLoad[i].type) {
  16182. case "image/jpeg":
  16183. case "image/png":
  16184. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16185. break;
  16186. case "image/targa":
  16187. case "image/vnd.ms-dds":
  16188. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16189. break;
  16190. default:
  16191. 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) {
  16192. sceneFileToLoad = filesToLoad[i];
  16193. }
  16194. break;
  16195. }
  16196. }
  16197. // If a ".babylon" file has been provided
  16198. if (sceneFileToLoad) {
  16199. if (this.currentScene) {
  16200. this.engine.stopRenderLoop();
  16201. this.currentScene.dispose();
  16202. }
  16203. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16204. that.currentScene = newScene;
  16205. // Wait for textures and shaders to be ready
  16206. that.currentScene.executeWhenReady(function () {
  16207. // Attach camera to canvas inputs
  16208. if (that.currentScene.activeCamera) {
  16209. that.currentScene.activeCamera.attachControl(that.canvas);
  16210. }
  16211. if (that.sceneLoadedCallback) {
  16212. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16213. }
  16214. that.engine.runRenderLoop(function () {
  16215. that.renderFunction();
  16216. });
  16217. });
  16218. }, function (progress) {
  16219. if (_this.progressCallback) {
  16220. _this.progressCallback(progress);
  16221. }
  16222. });
  16223. } else {
  16224. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16225. }
  16226. }
  16227. };
  16228. FilesInput.FilesTextures = new Array();
  16229. FilesInput.FilesToLoad = new Array();
  16230. return FilesInput;
  16231. })();
  16232. BABYLON.FilesInput = FilesInput;
  16233. })(BABYLON || (BABYLON = {}));
  16234. //# sourceMappingURL=babylon.filesInput.js.map
  16235. var BABYLON;
  16236. (function (BABYLON) {
  16237. var OimoJSPlugin = (function () {
  16238. function OimoJSPlugin() {
  16239. this._registeredMeshes = [];
  16240. /**
  16241. * Update the body position according to the mesh position
  16242. * @param mesh
  16243. */
  16244. this.updateBodyPosition = function (mesh) {
  16245. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16246. var registeredMesh = this._registeredMeshes[index];
  16247. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16248. var body = registeredMesh.body.body;
  16249. mesh.computeWorldMatrix(true);
  16250. var center = mesh.getBoundingInfo().boundingBox.center;
  16251. body.setPosition(center.x, center.y, center.z);
  16252. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16253. return;
  16254. }
  16255. // Case where the parent has been updated
  16256. if (registeredMesh.mesh.parent === mesh) {
  16257. mesh.computeWorldMatrix(true);
  16258. registeredMesh.mesh.computeWorldMatrix(true);
  16259. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16260. var absoluteRotation = mesh.rotation;
  16261. body = registeredMesh.body.body;
  16262. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16263. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16264. return;
  16265. }
  16266. }
  16267. };
  16268. }
  16269. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16270. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16271. };
  16272. OimoJSPlugin.prototype.initialize = function (iterations) {
  16273. this._world = new OIMO.World();
  16274. this._world.clear();
  16275. };
  16276. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16277. this._world.gravity = gravity;
  16278. };
  16279. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16280. var body = null;
  16281. this.unregisterMesh(mesh);
  16282. mesh.computeWorldMatrix(true);
  16283. switch (impostor) {
  16284. case BABYLON.PhysicsEngine.SphereImpostor:
  16285. var initialRotation = null;
  16286. if (mesh.rotationQuaternion) {
  16287. initialRotation = mesh.rotationQuaternion.clone();
  16288. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16289. mesh.computeWorldMatrix(true);
  16290. }
  16291. var bbox = mesh.getBoundingInfo().boundingBox;
  16292. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16293. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16294. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16295. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16296. // The delta between the mesh position and the mesh bounding box center
  16297. var deltaPosition = mesh.position.subtract(bbox.center);
  16298. // Transform delta position with the rotation
  16299. if (initialRotation) {
  16300. var m = new BABYLON.Matrix();
  16301. initialRotation.toRotationMatrix(m);
  16302. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16303. }
  16304. body = new OIMO.Body({
  16305. type: 'sphere',
  16306. size: [size],
  16307. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16308. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16309. move: options.mass != 0,
  16310. config: [options.mass, options.friction, options.restitution],
  16311. world: this._world
  16312. });
  16313. // Restore rotation
  16314. if (initialRotation) {
  16315. body.setQuaternion(initialRotation);
  16316. }
  16317. this._registeredMeshes.push({
  16318. mesh: mesh,
  16319. body: body,
  16320. delta: deltaPosition
  16321. });
  16322. break;
  16323. case BABYLON.PhysicsEngine.PlaneImpostor:
  16324. case BABYLON.PhysicsEngine.BoxImpostor:
  16325. initialRotation = null;
  16326. if (mesh.rotationQuaternion) {
  16327. initialRotation = mesh.rotationQuaternion.clone();
  16328. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16329. mesh.computeWorldMatrix(true);
  16330. }
  16331. bbox = mesh.getBoundingInfo().boundingBox;
  16332. var min = bbox.minimumWorld;
  16333. var max = bbox.maximumWorld;
  16334. var box = max.subtract(min);
  16335. var sizeX = this._checkWithEpsilon(box.x);
  16336. var sizeY = this._checkWithEpsilon(box.y);
  16337. var sizeZ = this._checkWithEpsilon(box.z);
  16338. // The delta between the mesh position and the mesh boudning box center
  16339. deltaPosition = mesh.position.subtract(bbox.center);
  16340. // Transform delta position with the rotation
  16341. if (initialRotation) {
  16342. m = new BABYLON.Matrix();
  16343. initialRotation.toRotationMatrix(m);
  16344. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16345. }
  16346. body = new OIMO.Body({
  16347. type: 'box',
  16348. size: [sizeX, sizeY, sizeZ],
  16349. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16350. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16351. move: options.mass != 0,
  16352. config: [options.mass, options.friction, options.restitution],
  16353. world: this._world
  16354. });
  16355. if (initialRotation) {
  16356. body.setQuaternion(initialRotation);
  16357. }
  16358. this._registeredMeshes.push({
  16359. mesh: mesh,
  16360. body: body,
  16361. delta: deltaPosition
  16362. });
  16363. break;
  16364. }
  16365. return body;
  16366. };
  16367. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16368. var types = [], sizes = [], positions = [], rotations = [];
  16369. var initialMesh = parts[0].mesh;
  16370. for (var index = 0; index < parts.length; index++) {
  16371. var part = parts[index];
  16372. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16373. types.push(bodyParameters.type);
  16374. sizes.push.apply(sizes, bodyParameters.size);
  16375. positions.push.apply(positions, bodyParameters.pos);
  16376. rotations.push.apply(rotations, bodyParameters.rot);
  16377. }
  16378. var body = new OIMO.Body({
  16379. type: types,
  16380. size: sizes,
  16381. pos: positions,
  16382. rot: rotations,
  16383. move: options.mass != 0,
  16384. config: [options.mass, options.friction, options.restitution],
  16385. world: this._world
  16386. });
  16387. this._registeredMeshes.push({
  16388. mesh: initialMesh,
  16389. body: body
  16390. });
  16391. return body;
  16392. };
  16393. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16394. var bodyParameters = null;
  16395. var mesh = part.mesh;
  16396. switch (part.impostor) {
  16397. case BABYLON.PhysicsEngine.SphereImpostor:
  16398. var bbox = mesh.getBoundingInfo().boundingBox;
  16399. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16400. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16401. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16402. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16403. bodyParameters = {
  16404. type: 'sphere',
  16405. /* bug with oimo : sphere needs 3 sizes in this case */
  16406. size: [size, -1, -1],
  16407. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16408. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16409. };
  16410. break;
  16411. case BABYLON.PhysicsEngine.PlaneImpostor:
  16412. case BABYLON.PhysicsEngine.BoxImpostor:
  16413. bbox = mesh.getBoundingInfo().boundingBox;
  16414. var min = bbox.minimumWorld;
  16415. var max = bbox.maximumWorld;
  16416. var box = max.subtract(min);
  16417. var sizeX = this._checkWithEpsilon(box.x);
  16418. var sizeY = this._checkWithEpsilon(box.y);
  16419. var sizeZ = this._checkWithEpsilon(box.z);
  16420. var relativePosition = mesh.position;
  16421. bodyParameters = {
  16422. type: 'box',
  16423. size: [sizeX, sizeY, sizeZ],
  16424. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16425. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16426. };
  16427. break;
  16428. }
  16429. return bodyParameters;
  16430. };
  16431. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16432. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16433. var registeredMesh = this._registeredMeshes[index];
  16434. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16435. if (registeredMesh.body) {
  16436. this._world.removeRigidBody(registeredMesh.body.body);
  16437. this._unbindBody(registeredMesh.body);
  16438. }
  16439. this._registeredMeshes.splice(index, 1);
  16440. return;
  16441. }
  16442. }
  16443. };
  16444. OimoJSPlugin.prototype._unbindBody = function (body) {
  16445. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16446. var registeredMesh = this._registeredMeshes[index];
  16447. if (registeredMesh.body === body) {
  16448. registeredMesh.body = null;
  16449. }
  16450. }
  16451. };
  16452. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16453. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16454. var registeredMesh = this._registeredMeshes[index];
  16455. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16456. // Get object mass to have a behaviour similar to cannon.js
  16457. var mass = registeredMesh.body.body.massInfo.mass;
  16458. // The force is scaled with the mass of object
  16459. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16460. return;
  16461. }
  16462. }
  16463. };
  16464. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16465. var body1 = null, body2 = null;
  16466. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16467. var registeredMesh = this._registeredMeshes[index];
  16468. if (registeredMesh.mesh === mesh1) {
  16469. body1 = registeredMesh.body.body;
  16470. } else if (registeredMesh.mesh === mesh2) {
  16471. body2 = registeredMesh.body.body;
  16472. }
  16473. }
  16474. if (!body1 || !body2) {
  16475. return false;
  16476. }
  16477. if (!options) {
  16478. options = {};
  16479. }
  16480. new OIMO.Link({
  16481. type: options.type,
  16482. body1: body1,
  16483. body2: body2,
  16484. min: options.min,
  16485. max: options.max,
  16486. axe1: options.axe1,
  16487. axe2: options.axe2,
  16488. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16489. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16490. collision: options.collision,
  16491. spring: options.spring,
  16492. world: this._world
  16493. });
  16494. return true;
  16495. };
  16496. OimoJSPlugin.prototype.dispose = function () {
  16497. this._world.clear();
  16498. while (this._registeredMeshes.length) {
  16499. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16500. }
  16501. };
  16502. OimoJSPlugin.prototype.isSupported = function () {
  16503. return OIMO !== undefined;
  16504. };
  16505. OimoJSPlugin.prototype._getLastShape = function (body) {
  16506. var lastShape = body.shapes;
  16507. while (lastShape.next) {
  16508. lastShape = lastShape.next;
  16509. }
  16510. return lastShape;
  16511. };
  16512. OimoJSPlugin.prototype.runOneStep = function (time) {
  16513. this._world.step();
  16514. // Update the position of all registered meshes
  16515. var i = this._registeredMeshes.length;
  16516. var m;
  16517. while (i--) {
  16518. var body = this._registeredMeshes[i].body.body;
  16519. var mesh = this._registeredMeshes[i].mesh;
  16520. var delta = this._registeredMeshes[i].delta;
  16521. if (!body.sleeping) {
  16522. if (body.shapes.next) {
  16523. var parentShape = this._getLastShape(body);
  16524. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16525. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16526. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16527. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16528. if (!mesh.rotationQuaternion) {
  16529. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16530. }
  16531. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16532. mesh.computeWorldMatrix();
  16533. } else {
  16534. m = body.getMatrix();
  16535. mtx = BABYLON.Matrix.FromArray(m);
  16536. // Body position
  16537. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16538. if (!delta) {
  16539. mesh.position.x = bodyX;
  16540. mesh.position.y = bodyY;
  16541. mesh.position.z = bodyZ;
  16542. } else {
  16543. mesh.position.x = bodyX + delta.x;
  16544. mesh.position.y = bodyY + delta.y;
  16545. mesh.position.z = bodyZ + delta.z;
  16546. }
  16547. if (!mesh.rotationQuaternion) {
  16548. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16549. }
  16550. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16551. mesh.computeWorldMatrix();
  16552. }
  16553. }
  16554. }
  16555. };
  16556. return OimoJSPlugin;
  16557. })();
  16558. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16559. })(BABYLON || (BABYLON = {}));
  16560. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  16561. var BABYLON;
  16562. (function (BABYLON) {
  16563. var PhysicsEngine = (function () {
  16564. function PhysicsEngine(plugin) {
  16565. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16566. }
  16567. PhysicsEngine.prototype._initialize = function (gravity) {
  16568. this._currentPlugin.initialize();
  16569. this._setGravity(gravity);
  16570. };
  16571. PhysicsEngine.prototype._runOneStep = function (delta) {
  16572. if (delta > 0.1) {
  16573. delta = 0.1;
  16574. } else if (delta <= 0) {
  16575. delta = 1.0 / 60.0;
  16576. }
  16577. this._currentPlugin.runOneStep(delta);
  16578. };
  16579. PhysicsEngine.prototype._setGravity = function (gravity) {
  16580. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16581. this._currentPlugin.setGravity(this.gravity);
  16582. };
  16583. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16584. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16585. };
  16586. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16587. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16588. };
  16589. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16590. this._currentPlugin.unregisterMesh(mesh);
  16591. };
  16592. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16593. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16594. };
  16595. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16596. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16597. };
  16598. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16599. this._currentPlugin.updateBodyPosition(mesh);
  16600. };
  16601. PhysicsEngine.prototype.dispose = function () {
  16602. this._currentPlugin.dispose();
  16603. };
  16604. PhysicsEngine.prototype.isSupported = function () {
  16605. return this._currentPlugin.isSupported();
  16606. };
  16607. PhysicsEngine.NoImpostor = 0;
  16608. PhysicsEngine.SphereImpostor = 1;
  16609. PhysicsEngine.BoxImpostor = 2;
  16610. PhysicsEngine.PlaneImpostor = 3;
  16611. PhysicsEngine.MeshImpostor = 4;
  16612. PhysicsEngine.CapsuleImpostor = 5;
  16613. PhysicsEngine.ConeImpostor = 6;
  16614. PhysicsEngine.CylinderImpostor = 7;
  16615. PhysicsEngine.ConvexHullImpostor = 8;
  16616. PhysicsEngine.Epsilon = 0.001;
  16617. return PhysicsEngine;
  16618. })();
  16619. BABYLON.PhysicsEngine = PhysicsEngine;
  16620. })(BABYLON || (BABYLON = {}));
  16621. //# sourceMappingURL=babylon.physicsEngine.js.map
  16622. var BABYLON;
  16623. (function (BABYLON) {
  16624. var serializeLight = function (light) {
  16625. var serializationObject = {};
  16626. serializationObject.name = light.name;
  16627. serializationObject.id = light.id;
  16628. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16629. if (light instanceof BABYLON.PointLight) {
  16630. serializationObject.type = 0;
  16631. serializationObject.position = light.position.asArray();
  16632. } else if (light instanceof BABYLON.DirectionalLight) {
  16633. serializationObject.type = 1;
  16634. var directionalLight = light;
  16635. serializationObject.position = directionalLight.position.asArray();
  16636. serializationObject.direction = directionalLight.direction.asArray();
  16637. } else if (light instanceof BABYLON.SpotLight) {
  16638. serializationObject.type = 2;
  16639. var spotLight = light;
  16640. serializationObject.position = spotLight.position.asArray();
  16641. serializationObject.direction = spotLight.position.asArray();
  16642. serializationObject.angle = spotLight.angle;
  16643. serializationObject.exponent = spotLight.exponent;
  16644. } else if (light instanceof BABYLON.HemisphericLight) {
  16645. serializationObject.type = 3;
  16646. var hemisphericLight = light;
  16647. serializationObject.direction = hemisphericLight.direction.asArray();
  16648. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16649. }
  16650. if (light.intensity) {
  16651. serializationObject.intensity = light.intensity;
  16652. }
  16653. serializationObject.range = light.range;
  16654. serializationObject.diffuse = light.diffuse.asArray();
  16655. serializationObject.specular = light.specular.asArray();
  16656. return serializationObject;
  16657. };
  16658. var serializeFresnelParameter = function (fresnelParameter) {
  16659. var serializationObject = {};
  16660. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16661. serializationObject.leftColor = fresnelParameter.leftColor;
  16662. serializationObject.rightColor = fresnelParameter.rightColor;
  16663. serializationObject.bias = fresnelParameter.bias;
  16664. serializationObject.power = fresnelParameter.power;
  16665. return serializationObject;
  16666. };
  16667. var serializeCamera = function (camera) {
  16668. var serializationObject = {};
  16669. serializationObject.name = camera.name;
  16670. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16671. serializationObject.id = camera.id;
  16672. serializationObject.position = camera.position.asArray();
  16673. // Parent
  16674. if (camera.parent) {
  16675. serializationObject.parentId = camera.parent.id;
  16676. }
  16677. // Target
  16678. serializationObject.rotation = camera.rotation.asArray();
  16679. // Locked target
  16680. if (camera.lockedTarget && camera.lockedTarget.id) {
  16681. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16682. }
  16683. serializationObject.fov = camera.fov;
  16684. serializationObject.minZ = camera.minZ;
  16685. serializationObject.maxZ = camera.maxZ;
  16686. serializationObject.speed = camera.speed;
  16687. serializationObject.inertia = camera.inertia;
  16688. serializationObject.checkCollisions = camera.checkCollisions;
  16689. serializationObject.applyGravity = camera.applyGravity;
  16690. if (camera.ellipsoid) {
  16691. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16692. }
  16693. // Animations
  16694. appendAnimations(camera, serializationObject);
  16695. // Layer mask
  16696. serializationObject.layerMask = camera.layerMask;
  16697. return serializationObject;
  16698. };
  16699. var appendAnimations = function (source, destination) {
  16700. if (source.animations) {
  16701. destination.animations = [];
  16702. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16703. var animation = source.animations[animationIndex];
  16704. destination.animations.push(serializeAnimation(animation));
  16705. }
  16706. }
  16707. };
  16708. var serializeAnimation = function (animation) {
  16709. var serializationObject = {};
  16710. serializationObject.name = animation.name;
  16711. serializationObject.property = animation.targetProperty;
  16712. serializationObject.framePerSecond = animation.framePerSecond;
  16713. serializationObject.dataType = animation.dataType;
  16714. serializationObject.loopBehavior = animation.loopMode;
  16715. var dataType = animation.dataType;
  16716. serializationObject.keys = [];
  16717. var keys = animation.getKeys();
  16718. for (var index = 0; index < keys.length; index++) {
  16719. var animationKey = keys[index];
  16720. var key = {};
  16721. key.frame = animationKey.frame;
  16722. switch (dataType) {
  16723. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16724. key.values = [animationKey.value];
  16725. break;
  16726. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16727. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16728. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16729. key.values = animationKey.value.asArray();
  16730. break;
  16731. }
  16732. serializationObject.keys.push(key);
  16733. }
  16734. return serializationObject;
  16735. };
  16736. var serializeMultiMaterial = function (material) {
  16737. var serializationObject = {};
  16738. serializationObject.name = material.name;
  16739. serializationObject.id = material.id;
  16740. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16741. serializationObject.materials = [];
  16742. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16743. var subMat = material.subMaterials[matIndex];
  16744. if (subMat) {
  16745. serializationObject.materials.push(subMat.id);
  16746. } else {
  16747. serializationObject.materials.push(null);
  16748. }
  16749. }
  16750. return serializationObject;
  16751. };
  16752. var serializeMaterial = function (material) {
  16753. var serializationObject = {};
  16754. serializationObject.name = material.name;
  16755. serializationObject.ambient = material.ambientColor.asArray();
  16756. serializationObject.diffuse = material.diffuseColor.asArray();
  16757. serializationObject.specular = material.specularColor.asArray();
  16758. serializationObject.specularPower = material.specularPower;
  16759. serializationObject.emissive = material.emissiveColor.asArray();
  16760. serializationObject.alpha = material.alpha;
  16761. serializationObject.id = material.id;
  16762. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16763. serializationObject.backFaceCulling = material.backFaceCulling;
  16764. if (material.diffuseTexture) {
  16765. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16766. }
  16767. if (material.diffuseFresnelParameters) {
  16768. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16769. }
  16770. if (material.ambientTexture) {
  16771. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16772. }
  16773. if (material.opacityTexture) {
  16774. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16775. }
  16776. if (material.opacityFresnelParameters) {
  16777. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16778. }
  16779. if (material.reflectionTexture) {
  16780. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16781. }
  16782. if (material.reflectionFresnelParameters) {
  16783. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16784. }
  16785. if (material.emissiveTexture) {
  16786. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16787. }
  16788. if (material.emissiveFresnelParameters) {
  16789. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16790. }
  16791. if (material.specularTexture) {
  16792. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16793. }
  16794. if (material.bumpTexture) {
  16795. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16796. }
  16797. return serializationObject;
  16798. };
  16799. var serializeTexture = function (texture) {
  16800. var serializationObject = {};
  16801. if (!texture.name) {
  16802. return null;
  16803. }
  16804. if (texture instanceof BABYLON.CubeTexture) {
  16805. serializationObject.name = texture.name;
  16806. serializationObject.hasAlpha = texture.hasAlpha;
  16807. serializationObject.level = texture.level;
  16808. serializationObject.coordinatesMode = texture.coordinatesMode;
  16809. return serializationObject;
  16810. }
  16811. if (texture instanceof BABYLON.MirrorTexture) {
  16812. var mirrorTexture = texture;
  16813. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16814. serializationObject.renderList = [];
  16815. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16816. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16817. }
  16818. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16819. } else if (texture instanceof BABYLON.RenderTargetTexture) {
  16820. var renderTargetTexture = texture;
  16821. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  16822. serializationObject.renderList = [];
  16823. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  16824. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  16825. }
  16826. }
  16827. var regularTexture = texture;
  16828. serializationObject.name = texture.name;
  16829. serializationObject.hasAlpha = texture.hasAlpha;
  16830. serializationObject.level = texture.level;
  16831. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  16832. serializationObject.coordinatesMode = texture.coordinatesMode;
  16833. serializationObject.uOffset = regularTexture.uOffset;
  16834. serializationObject.vOffset = regularTexture.vOffset;
  16835. serializationObject.uScale = regularTexture.uScale;
  16836. serializationObject.vScale = regularTexture.vScale;
  16837. serializationObject.uAng = regularTexture.uAng;
  16838. serializationObject.vAng = regularTexture.vAng;
  16839. serializationObject.wAng = regularTexture.wAng;
  16840. serializationObject.wrapU = texture.wrapU;
  16841. serializationObject.wrapV = texture.wrapV;
  16842. // Animations
  16843. appendAnimations(texture, serializationObject);
  16844. return serializationObject;
  16845. };
  16846. var serializeSkeleton = function (skeleton) {
  16847. var serializationObject = {};
  16848. serializationObject.name = skeleton.name;
  16849. serializationObject.id = skeleton.id;
  16850. serializationObject.bones = [];
  16851. for (var index = 0; index < skeleton.bones.length; index++) {
  16852. var bone = skeleton.bones[index];
  16853. var serializedBone = {
  16854. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  16855. name: bone.name,
  16856. matrix: bone.getLocalMatrix().toArray()
  16857. };
  16858. serializationObject.bones.push(serializedBone);
  16859. if (bone.animations && bone.animations.length > 0) {
  16860. serializedBone.animation = serializeAnimation(bone.animations[0]);
  16861. }
  16862. }
  16863. return serializationObject;
  16864. };
  16865. var serializeParticleSystem = function (particleSystem) {
  16866. var serializationObject = {};
  16867. serializationObject.emitterId = particleSystem.emitter.id;
  16868. serializationObject.capacity = particleSystem.getCapacity();
  16869. if (particleSystem.particleTexture) {
  16870. serializationObject.textureName = particleSystem.particleTexture.name;
  16871. }
  16872. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  16873. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  16874. serializationObject.minSize = particleSystem.minSize;
  16875. serializationObject.maxSize = particleSystem.maxSize;
  16876. serializationObject.minLifeTime = particleSystem.minLifeTime;
  16877. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  16878. serializationObject.emitRate = particleSystem.emitRate;
  16879. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  16880. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  16881. serializationObject.gravity = particleSystem.gravity.asArray();
  16882. serializationObject.direction1 = particleSystem.direction1.asArray();
  16883. serializationObject.direction2 = particleSystem.direction2.asArray();
  16884. serializationObject.color1 = particleSystem.color1.asArray();
  16885. serializationObject.color2 = particleSystem.color2.asArray();
  16886. serializationObject.colorDead = particleSystem.colorDead.asArray();
  16887. serializationObject.updateSpeed = particleSystem.updateSpeed;
  16888. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  16889. serializationObject.textureMask = particleSystem.textureMask.asArray();
  16890. serializationObject.blendMode = particleSystem.blendMode;
  16891. return serializationObject;
  16892. };
  16893. var serializeLensFlareSystem = function (lensFlareSystem) {
  16894. var serializationObject = {};
  16895. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  16896. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  16897. serializationObject.flares = [];
  16898. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  16899. var flare = lensFlareSystem.lensFlares[index];
  16900. serializationObject.flares.push({
  16901. size: flare.size,
  16902. position: flare.position,
  16903. color: flare.color.asArray(),
  16904. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  16905. });
  16906. }
  16907. return serializationObject;
  16908. };
  16909. var serializeShadowGenerator = function (light) {
  16910. var serializationObject = {};
  16911. var shadowGenerator = light.getShadowGenerator();
  16912. serializationObject.lightId = light.id;
  16913. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  16914. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  16915. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  16916. serializationObject.renderList = [];
  16917. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  16918. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  16919. serializationObject.renderList.push(mesh.id);
  16920. }
  16921. return serializationObject;
  16922. };
  16923. var serializedGeometries = [];
  16924. var serializeGeometry = function (geometry, serializationGeometries) {
  16925. if (serializedGeometries[geometry.id]) {
  16926. return;
  16927. }
  16928. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  16929. serializationGeometries.boxes.push(serializeBox(geometry));
  16930. } else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  16931. serializationGeometries.spheres.push(serializeSphere(geometry));
  16932. } else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  16933. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  16934. } else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  16935. serializationGeometries.toruses.push(serializeTorus(geometry));
  16936. } else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  16937. serializationGeometries.grounds.push(serializeGround(geometry));
  16938. } else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  16939. serializationGeometries.planes.push(serializePlane(geometry));
  16940. } else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  16941. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  16942. } else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  16943. throw new Error("Unknow primitive type");
  16944. } else {
  16945. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  16946. }
  16947. serializedGeometries[geometry.id] = true;
  16948. };
  16949. var serializeGeometryBase = function (geometry) {
  16950. var serializationObject = {};
  16951. serializationObject.id = geometry.id;
  16952. if (BABYLON.Tags.HasTags(geometry)) {
  16953. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  16954. }
  16955. return serializationObject;
  16956. };
  16957. var serializeVertexData = function (vertexData) {
  16958. var serializationObject = serializeGeometryBase(vertexData);
  16959. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  16960. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  16961. }
  16962. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16963. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16964. }
  16965. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16966. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16967. }
  16968. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  16969. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  16970. }
  16971. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  16972. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  16973. }
  16974. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  16975. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  16976. serializationObject.matricesIndices._isExpanded = true;
  16977. }
  16978. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  16979. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  16980. }
  16981. serializationObject.indices = vertexData.getIndices();
  16982. return serializationObject;
  16983. };
  16984. var serializePrimitive = function (primitive) {
  16985. var serializationObject = serializeGeometryBase(primitive);
  16986. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  16987. return serializationObject;
  16988. };
  16989. var serializeBox = function (box) {
  16990. var serializationObject = serializePrimitive(box);
  16991. serializationObject.size = box.size;
  16992. return serializationObject;
  16993. };
  16994. var serializeSphere = function (sphere) {
  16995. var serializationObject = serializePrimitive(sphere);
  16996. serializationObject.segments = sphere.segments;
  16997. serializationObject.diameter = sphere.diameter;
  16998. return serializationObject;
  16999. };
  17000. var serializeCylinder = function (cylinder) {
  17001. var serializationObject = serializePrimitive(cylinder);
  17002. serializationObject.height = cylinder.height;
  17003. serializationObject.diameterTop = cylinder.diameterTop;
  17004. serializationObject.diameterBottom = cylinder.diameterBottom;
  17005. serializationObject.tessellation = cylinder.tessellation;
  17006. return serializationObject;
  17007. };
  17008. var serializeTorus = function (torus) {
  17009. var serializationObject = serializePrimitive(torus);
  17010. serializationObject.diameter = torus.diameter;
  17011. serializationObject.thickness = torus.thickness;
  17012. serializationObject.tessellation = torus.tessellation;
  17013. return serializationObject;
  17014. };
  17015. var serializeGround = function (ground) {
  17016. var serializationObject = serializePrimitive(ground);
  17017. serializationObject.width = ground.width;
  17018. serializationObject.height = ground.height;
  17019. serializationObject.subdivisions = ground.subdivisions;
  17020. return serializationObject;
  17021. };
  17022. var serializePlane = function (plane) {
  17023. var serializationObject = serializePrimitive(plane);
  17024. serializationObject.size = plane.size;
  17025. return serializationObject;
  17026. };
  17027. var serializeTorusKnot = function (torusKnot) {
  17028. var serializationObject = serializePrimitive(torusKnot);
  17029. serializationObject.radius = torusKnot.radius;
  17030. serializationObject.tube = torusKnot.tube;
  17031. serializationObject.radialSegments = torusKnot.radialSegments;
  17032. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17033. serializationObject.p = torusKnot.p;
  17034. serializationObject.q = torusKnot.q;
  17035. return serializationObject;
  17036. };
  17037. var serializeMesh = function (mesh, serializationScene) {
  17038. var serializationObject = {};
  17039. serializationObject.name = mesh.name;
  17040. serializationObject.id = mesh.id;
  17041. if (BABYLON.Tags.HasTags(mesh)) {
  17042. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17043. }
  17044. serializationObject.position = mesh.position.asArray();
  17045. if (mesh.rotationQuaternion) {
  17046. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17047. } else if (mesh.rotation) {
  17048. serializationObject.rotation = mesh.rotation.asArray();
  17049. }
  17050. serializationObject.scaling = mesh.scaling.asArray();
  17051. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17052. serializationObject.isEnabled = mesh.isEnabled();
  17053. serializationObject.isVisible = mesh.isVisible;
  17054. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17055. serializationObject.pickable = mesh.isPickable;
  17056. serializationObject.receiveShadows = mesh.receiveShadows;
  17057. serializationObject.billboardMode = mesh.billboardMode;
  17058. serializationObject.visibility = mesh.visibility;
  17059. serializationObject.checkCollisions = mesh.checkCollisions;
  17060. // Parent
  17061. if (mesh.parent) {
  17062. serializationObject.parentId = mesh.parent.id;
  17063. }
  17064. // Geometry
  17065. var geometry = mesh._geometry;
  17066. if (geometry) {
  17067. var geometryId = geometry.id;
  17068. serializationObject.geometryId = geometryId;
  17069. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17070. // 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
  17071. serializeGeometry(geometry, serializationScene.geometries);
  17072. }
  17073. // SubMeshes
  17074. serializationObject.subMeshes = [];
  17075. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17076. var subMesh = mesh.subMeshes[subIndex];
  17077. serializationObject.subMeshes.push({
  17078. materialIndex: subMesh.materialIndex,
  17079. verticesStart: subMesh.verticesStart,
  17080. verticesCount: subMesh.verticesCount,
  17081. indexStart: subMesh.indexStart,
  17082. indexCount: subMesh.indexCount
  17083. });
  17084. }
  17085. }
  17086. // Material
  17087. if (mesh.material) {
  17088. serializationObject.materialId = mesh.material.id;
  17089. } else {
  17090. mesh.material = null;
  17091. }
  17092. // Skeleton
  17093. if (mesh.skeleton) {
  17094. serializationObject.skeletonId = mesh.skeleton.id;
  17095. }
  17096. // Physics
  17097. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17098. serializationObject.physicsMass = mesh.getPhysicsMass();
  17099. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17100. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17101. switch (mesh.getPhysicsImpostor()) {
  17102. case BABYLON.PhysicsEngine.BoxImpostor:
  17103. serializationObject.physicsImpostor = 1;
  17104. break;
  17105. case BABYLON.PhysicsEngine.SphereImpostor:
  17106. serializationObject.physicsImpostor = 2;
  17107. break;
  17108. }
  17109. }
  17110. // Instances
  17111. serializationObject.instances = [];
  17112. for (var index = 0; index < mesh.instances.length; index++) {
  17113. var instance = mesh.instances[index];
  17114. var serializationInstance = {
  17115. name: instance.name,
  17116. position: instance.position,
  17117. rotation: instance.rotation,
  17118. rotationQuaternion: instance.rotationQuaternion,
  17119. scaling: instance.scaling
  17120. };
  17121. serializationObject.instances.push(serializationInstance);
  17122. // Animations
  17123. appendAnimations(instance, serializationInstance);
  17124. }
  17125. // Animations
  17126. appendAnimations(mesh, serializationObject);
  17127. // Layer mask
  17128. serializationObject.layerMask = mesh.layerMask;
  17129. return serializationObject;
  17130. };
  17131. var SceneSerializer = (function () {
  17132. function SceneSerializer() {
  17133. }
  17134. SceneSerializer.Serialize = function (scene) {
  17135. var serializationObject = {};
  17136. // Scene
  17137. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17138. serializationObject.autoClear = scene.autoClear;
  17139. serializationObject.clearColor = scene.clearColor.asArray();
  17140. serializationObject.ambientColor = scene.ambientColor.asArray();
  17141. serializationObject.gravity = scene.gravity.asArray();
  17142. // Fog
  17143. if (scene.fogMode && scene.fogMode !== 0) {
  17144. serializationObject.fogMode = scene.fogMode;
  17145. serializationObject.fogColor = scene.fogColor.asArray();
  17146. serializationObject.fogStart = scene.fogStart;
  17147. serializationObject.fogEnd = scene.fogEnd;
  17148. serializationObject.fogDensity = scene.fogDensity;
  17149. }
  17150. // Lights
  17151. serializationObject.lights = [];
  17152. for (var index = 0; index < scene.lights.length; index++) {
  17153. var light = scene.lights[index];
  17154. serializationObject.lights.push(serializeLight(light));
  17155. }
  17156. // Cameras
  17157. serializationObject.cameras = [];
  17158. for (index = 0; index < scene.cameras.length; index++) {
  17159. var camera = scene.cameras[index];
  17160. if (camera instanceof BABYLON.FreeCamera) {
  17161. serializationObject.cameras.push(serializeCamera(camera));
  17162. }
  17163. }
  17164. if (scene.activeCamera) {
  17165. serializationObject.activeCameraID = scene.activeCamera.id;
  17166. }
  17167. // Materials
  17168. serializationObject.materials = [];
  17169. serializationObject.multiMaterials = [];
  17170. for (index = 0; index < scene.materials.length; index++) {
  17171. var material = scene.materials[index];
  17172. if (material instanceof BABYLON.StandardMaterial) {
  17173. serializationObject.materials.push(serializeMaterial(material));
  17174. } else if (material instanceof BABYLON.MultiMaterial) {
  17175. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17176. }
  17177. }
  17178. // Skeletons
  17179. serializationObject.skeletons = [];
  17180. for (index = 0; index < scene.skeletons.length; index++) {
  17181. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17182. }
  17183. // Geometries
  17184. serializationObject.geometries = {};
  17185. serializationObject.geometries.boxes = [];
  17186. serializationObject.geometries.spheres = [];
  17187. serializationObject.geometries.cylinders = [];
  17188. serializationObject.geometries.toruses = [];
  17189. serializationObject.geometries.grounds = [];
  17190. serializationObject.geometries.planes = [];
  17191. serializationObject.geometries.torusKnots = [];
  17192. serializationObject.geometries.vertexData = [];
  17193. serializedGeometries = [];
  17194. var geometries = scene.getGeometries();
  17195. for (var index = 0; index < geometries.length; index++) {
  17196. var geometry = geometries[index];
  17197. if (geometry.isReady()) {
  17198. serializeGeometry(geometry, serializationObject.geometries);
  17199. }
  17200. }
  17201. // Meshes
  17202. serializationObject.meshes = [];
  17203. for (index = 0; index < scene.meshes.length; index++) {
  17204. var abstractMesh = scene.meshes[index];
  17205. if (abstractMesh instanceof BABYLON.Mesh) {
  17206. var mesh = abstractMesh;
  17207. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17208. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17209. }
  17210. }
  17211. }
  17212. // Particles Systems
  17213. serializationObject.particleSystems = [];
  17214. for (index = 0; index < scene.particleSystems.length; index++) {
  17215. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17216. }
  17217. // Lens flares
  17218. serializationObject.lensFlareSystems = [];
  17219. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17220. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17221. }
  17222. // Shadows
  17223. serializationObject.shadowGenerators = [];
  17224. for (index = 0; index < scene.lights.length; index++) {
  17225. light = scene.lights[index];
  17226. if (light.getShadowGenerator()) {
  17227. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17228. }
  17229. }
  17230. return serializationObject;
  17231. };
  17232. return SceneSerializer;
  17233. })();
  17234. BABYLON.SceneSerializer = SceneSerializer;
  17235. })(BABYLON || (BABYLON = {}));
  17236. //# sourceMappingURL=babylon.sceneSerializer.js.map
  17237. var BABYLON;
  17238. (function (BABYLON) {
  17239. var SceneLoader = (function () {
  17240. function SceneLoader() {
  17241. }
  17242. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17243. get: function () {
  17244. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17245. },
  17246. set: function (value) {
  17247. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17248. },
  17249. enumerable: true,
  17250. configurable: true
  17251. });
  17252. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17253. get: function () {
  17254. return SceneLoader._ShowLoadingScreen;
  17255. },
  17256. set: function (value) {
  17257. SceneLoader._ShowLoadingScreen = value;
  17258. },
  17259. enumerable: true,
  17260. configurable: true
  17261. });
  17262. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17263. var dotPosition = sceneFilename.lastIndexOf(".");
  17264. var queryStringPosition = sceneFilename.indexOf("?");
  17265. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17266. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17267. var plugin = this._registeredPlugins[index];
  17268. if (plugin.extensions.indexOf(extension) !== -1) {
  17269. return plugin;
  17270. }
  17271. }
  17272. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17273. };
  17274. // Public functions
  17275. SceneLoader.RegisterPlugin = function (plugin) {
  17276. plugin.extensions = plugin.extensions.toLowerCase();
  17277. SceneLoader._registeredPlugins.push(plugin);
  17278. };
  17279. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17280. var manifestChecked = function (success) {
  17281. scene.database = database;
  17282. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17283. var importMeshFromData = function (data) {
  17284. var meshes = [];
  17285. var particleSystems = [];
  17286. var skeletons = [];
  17287. try {
  17288. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17289. if (onerror) {
  17290. onerror(scene, 'unable to load the scene');
  17291. }
  17292. return;
  17293. }
  17294. } catch (e) {
  17295. if (onerror) {
  17296. onerror(scene, e);
  17297. }
  17298. return;
  17299. }
  17300. if (onsuccess) {
  17301. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17302. onsuccess(meshes, particleSystems, skeletons);
  17303. }
  17304. };
  17305. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17306. // Direct load
  17307. importMeshFromData(sceneFilename.substr(5));
  17308. return;
  17309. }
  17310. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17311. importMeshFromData(data);
  17312. }, progressCallBack, database);
  17313. };
  17314. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17315. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17316. };
  17317. /**
  17318. * Load a scene
  17319. * @param rootUrl a string that defines the root url for scene and resources
  17320. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17321. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17322. */
  17323. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17324. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17325. };
  17326. /**
  17327. * Append a scene
  17328. * @param rootUrl a string that defines the root url for scene and resources
  17329. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17330. * @param scene is the instance of BABYLON.Scene to append to
  17331. */
  17332. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17333. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17334. var database;
  17335. if (SceneLoader.ShowLoadingScreen) {
  17336. scene.getEngine().displayLoadingUI();
  17337. }
  17338. var loadSceneFromData = function (data) {
  17339. scene.database = database;
  17340. if (!plugin.load(scene, data, rootUrl)) {
  17341. if (onerror) {
  17342. onerror(scene);
  17343. }
  17344. scene.getEngine().hideLoadingUI();
  17345. return;
  17346. }
  17347. if (onsuccess) {
  17348. onsuccess(scene);
  17349. }
  17350. if (SceneLoader.ShowLoadingScreen) {
  17351. scene.executeWhenReady(function () {
  17352. scene.getEngine().hideLoadingUI();
  17353. });
  17354. }
  17355. };
  17356. var manifestChecked = function (success) {
  17357. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17358. };
  17359. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17360. // Direct load
  17361. loadSceneFromData(sceneFilename.substr(5));
  17362. return;
  17363. }
  17364. if (rootUrl.indexOf("file:") === -1) {
  17365. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17366. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17367. } else {
  17368. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17369. }
  17370. };
  17371. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17372. SceneLoader._ShowLoadingScreen = true;
  17373. SceneLoader._registeredPlugins = new Array();
  17374. return SceneLoader;
  17375. })();
  17376. BABYLON.SceneLoader = SceneLoader;
  17377. ;
  17378. })(BABYLON || (BABYLON = {}));
  17379. //# sourceMappingURL=babylon.sceneLoader.js.map
  17380. var BABYLON;
  17381. (function (BABYLON) {
  17382. (function (Internals) {
  17383. var checkColors4 = function (colors, count) {
  17384. // Check if color3 was used
  17385. if (colors.length === count * 3) {
  17386. var colors4 = [];
  17387. for (var index = 0; index < colors.length; index += 3) {
  17388. var newIndex = (index / 3) * 4;
  17389. colors4[newIndex] = colors[index];
  17390. colors4[newIndex + 1] = colors[index + 1];
  17391. colors4[newIndex + 2] = colors[index + 2];
  17392. colors4[newIndex + 3] = 1.0;
  17393. }
  17394. return colors4;
  17395. }
  17396. return colors;
  17397. };
  17398. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17399. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17400. texture.name = parsedTexture.name;
  17401. texture.hasAlpha = parsedTexture.hasAlpha;
  17402. texture.level = parsedTexture.level;
  17403. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17404. return texture;
  17405. };
  17406. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17407. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17408. return null;
  17409. }
  17410. if (parsedTexture.isCube) {
  17411. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17412. }
  17413. var texture;
  17414. if (parsedTexture.mirrorPlane) {
  17415. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17416. texture._waitingRenderList = parsedTexture.renderList;
  17417. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17418. } else if (parsedTexture.isRenderTarget) {
  17419. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17420. texture._waitingRenderList = parsedTexture.renderList;
  17421. } else {
  17422. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17423. }
  17424. texture.name = parsedTexture.name;
  17425. texture.hasAlpha = parsedTexture.hasAlpha;
  17426. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17427. texture.level = parsedTexture.level;
  17428. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17429. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17430. texture.uOffset = parsedTexture.uOffset;
  17431. texture.vOffset = parsedTexture.vOffset;
  17432. texture.uScale = parsedTexture.uScale;
  17433. texture.vScale = parsedTexture.vScale;
  17434. texture.uAng = parsedTexture.uAng;
  17435. texture.vAng = parsedTexture.vAng;
  17436. texture.wAng = parsedTexture.wAng;
  17437. texture.wrapU = parsedTexture.wrapU;
  17438. texture.wrapV = parsedTexture.wrapV;
  17439. // Animations
  17440. if (parsedTexture.animations) {
  17441. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17442. var parsedAnimation = parsedTexture.animations[animationIndex];
  17443. texture.animations.push(parseAnimation(parsedAnimation));
  17444. }
  17445. }
  17446. return texture;
  17447. };
  17448. var parseSkeleton = function (parsedSkeleton, scene) {
  17449. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17450. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17451. var parsedBone = parsedSkeleton.bones[index];
  17452. var parentBone = null;
  17453. if (parsedBone.parentBoneIndex > -1) {
  17454. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17455. }
  17456. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17457. if (parsedBone.animation) {
  17458. bone.animations.push(parseAnimation(parsedBone.animation));
  17459. }
  17460. }
  17461. return skeleton;
  17462. };
  17463. var parseFresnelParameters = function (parsedFresnelParameters) {
  17464. var fresnelParameters = new BABYLON.FresnelParameters();
  17465. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17466. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17467. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17468. fresnelParameters.bias = parsedFresnelParameters.bias;
  17469. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17470. return fresnelParameters;
  17471. };
  17472. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17473. var material;
  17474. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17475. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17476. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17477. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17478. material.specularPower = parsedMaterial.specularPower;
  17479. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17480. material.alpha = parsedMaterial.alpha;
  17481. material.id = parsedMaterial.id;
  17482. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17483. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17484. material.wireframe = parsedMaterial.wireframe;
  17485. if (parsedMaterial.diffuseTexture) {
  17486. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17487. }
  17488. if (parsedMaterial.diffuseFresnelParameters) {
  17489. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17490. }
  17491. if (parsedMaterial.ambientTexture) {
  17492. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17493. }
  17494. if (parsedMaterial.opacityTexture) {
  17495. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17496. }
  17497. if (parsedMaterial.opacityFresnelParameters) {
  17498. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17499. }
  17500. if (parsedMaterial.reflectionTexture) {
  17501. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17502. }
  17503. if (parsedMaterial.reflectionFresnelParameters) {
  17504. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17505. }
  17506. if (parsedMaterial.emissiveTexture) {
  17507. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17508. }
  17509. if (parsedMaterial.emissiveFresnelParameters) {
  17510. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17511. }
  17512. if (parsedMaterial.specularTexture) {
  17513. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17514. }
  17515. if (parsedMaterial.bumpTexture) {
  17516. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17517. }
  17518. return material;
  17519. };
  17520. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17521. for (var index = 0; index < parsedData.materials.length; index++) {
  17522. var parsedMaterial = parsedData.materials[index];
  17523. if (parsedMaterial.id === id) {
  17524. return parseMaterial(parsedMaterial, scene, rootUrl);
  17525. }
  17526. }
  17527. return null;
  17528. };
  17529. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17530. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17531. multiMaterial.id = parsedMultiMaterial.id;
  17532. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17533. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17534. var subMatId = parsedMultiMaterial.materials[matIndex];
  17535. if (subMatId) {
  17536. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17537. } else {
  17538. multiMaterial.subMaterials.push(null);
  17539. }
  17540. }
  17541. return multiMaterial;
  17542. };
  17543. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17544. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17545. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17546. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17547. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17548. var parsedFlare = parsedLensFlareSystem.flares[index];
  17549. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17550. }
  17551. return lensFlareSystem;
  17552. };
  17553. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17554. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17555. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17556. if (parsedParticleSystem.textureName) {
  17557. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17558. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17559. }
  17560. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17561. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17562. particleSystem.minSize = parsedParticleSystem.minSize;
  17563. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17564. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17565. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17566. particleSystem.emitter = emitter;
  17567. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17568. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17569. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17570. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17571. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17572. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17573. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17574. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17575. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17576. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17577. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17578. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17579. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17580. particleSystem.start();
  17581. return particleSystem;
  17582. };
  17583. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17584. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17585. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17586. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17587. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17588. shadowGenerator.getShadowMap().renderList.push(mesh);
  17589. }
  17590. if (parsedShadowGenerator.usePoissonSampling) {
  17591. shadowGenerator.usePoissonSampling = true;
  17592. } else {
  17593. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17594. }
  17595. return shadowGenerator;
  17596. };
  17597. var parseAnimation = function (parsedAnimation) {
  17598. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17599. var dataType = parsedAnimation.dataType;
  17600. var keys = [];
  17601. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17602. var key = parsedAnimation.keys[index];
  17603. var data;
  17604. switch (dataType) {
  17605. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17606. data = key.values[0];
  17607. break;
  17608. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17609. data = BABYLON.Quaternion.FromArray(key.values);
  17610. break;
  17611. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17612. data = BABYLON.Matrix.FromArray(key.values);
  17613. break;
  17614. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17615. default:
  17616. data = BABYLON.Vector3.FromArray(key.values);
  17617. break;
  17618. }
  17619. keys.push({
  17620. frame: key.frame,
  17621. value: data
  17622. });
  17623. }
  17624. animation.setKeys(keys);
  17625. return animation;
  17626. };
  17627. var parseLight = function (parsedLight, scene) {
  17628. var light;
  17629. switch (parsedLight.type) {
  17630. case 0:
  17631. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17632. break;
  17633. case 1:
  17634. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17635. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17636. break;
  17637. case 2:
  17638. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17639. break;
  17640. case 3:
  17641. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17642. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17643. break;
  17644. }
  17645. light.id = parsedLight.id;
  17646. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17647. if (parsedLight.intensity !== undefined) {
  17648. light.intensity = parsedLight.intensity;
  17649. }
  17650. if (parsedLight.range) {
  17651. light.range = parsedLight.range;
  17652. }
  17653. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17654. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17655. if (parsedLight.excludedMeshesIds) {
  17656. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17657. }
  17658. // Parent
  17659. if (parsedLight.parentId) {
  17660. light._waitingParentId = parsedLight.parentId;
  17661. }
  17662. if (parsedLight.includedOnlyMeshesIds) {
  17663. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17664. }
  17665. // Actions
  17666. if (parsedLight.actions !== undefined) {
  17667. light._waitingActions = parsedLight.actions;
  17668. }
  17669. // Animations
  17670. if (parsedLight.animations) {
  17671. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17672. var parsedAnimation = parsedLight.animations[animationIndex];
  17673. light.animations.push(parseAnimation(parsedAnimation));
  17674. }
  17675. }
  17676. if (parsedLight.autoAnimate) {
  17677. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17678. }
  17679. };
  17680. var parseCamera = function (parsedCamera, scene) {
  17681. var camera;
  17682. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17683. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17684. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17685. var alpha = parsedCamera.alpha;
  17686. var beta = parsedCamera.beta;
  17687. var radius = parsedCamera.radius;
  17688. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17689. var eye_space = parsedCamera.eye_space;
  17690. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17691. } else {
  17692. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17693. }
  17694. } else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17695. eye_space = parsedCamera.eye_space;
  17696. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17697. } else if (parsedCamera.type === "DeviceOrientationCamera") {
  17698. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17699. } else if (parsedCamera.type === "FollowCamera") {
  17700. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17701. camera.heightOffset = parsedCamera.heightOffset;
  17702. camera.radius = parsedCamera.radius;
  17703. camera.rotationOffset = parsedCamera.rotationOffset;
  17704. if (lockedTargetMesh)
  17705. camera.target = lockedTargetMesh;
  17706. } else if (parsedCamera.type === "GamepadCamera") {
  17707. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17708. } else if (parsedCamera.type === "OculusCamera") {
  17709. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17710. } else if (parsedCamera.type === "OculusGamepadCamera") {
  17711. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17712. } else if (parsedCamera.type === "TouchCamera") {
  17713. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17714. } else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17715. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17716. } else if (parsedCamera.type === "WebVRCamera") {
  17717. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17718. } else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17719. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17720. } else {
  17721. // Free Camera is the default value
  17722. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17723. }
  17724. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17725. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17726. camera.lockedTarget = lockedTargetMesh;
  17727. }
  17728. camera.id = parsedCamera.id;
  17729. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17730. // Parent
  17731. if (parsedCamera.parentId) {
  17732. camera._waitingParentId = parsedCamera.parentId;
  17733. }
  17734. // Actions
  17735. if (parsedCamera.actions !== undefined) {
  17736. camera._waitingActions = parsedCamera.actions;
  17737. }
  17738. // Target
  17739. if (parsedCamera.target) {
  17740. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17741. } else {
  17742. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17743. }
  17744. camera.fov = parsedCamera.fov;
  17745. camera.minZ = parsedCamera.minZ;
  17746. camera.maxZ = parsedCamera.maxZ;
  17747. camera.speed = parsedCamera.speed;
  17748. camera.inertia = parsedCamera.inertia;
  17749. camera.checkCollisions = parsedCamera.checkCollisions;
  17750. camera.applyGravity = parsedCamera.applyGravity;
  17751. if (parsedCamera.ellipsoid) {
  17752. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17753. }
  17754. // Animations
  17755. if (parsedCamera.animations) {
  17756. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17757. var parsedAnimation = parsedCamera.animations[animationIndex];
  17758. camera.animations.push(parseAnimation(parsedAnimation));
  17759. }
  17760. }
  17761. if (parsedCamera.autoAnimate) {
  17762. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17763. }
  17764. // Layer Mask
  17765. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17766. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17767. } else {
  17768. camera.layerMask = 0xFFFFFFFF;
  17769. }
  17770. return camera;
  17771. };
  17772. var parseGeometry = function (parsedGeometry, scene) {
  17773. var id = parsedGeometry.id;
  17774. return scene.getGeometryByID(id);
  17775. };
  17776. var parseBox = function (parsedBox, scene) {
  17777. if (parseGeometry(parsedBox, scene)) {
  17778. return null;
  17779. }
  17780. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17781. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17782. scene.pushGeometry(box, true);
  17783. return box;
  17784. };
  17785. var parseSphere = function (parsedSphere, scene) {
  17786. if (parseGeometry(parsedSphere, scene)) {
  17787. return null;
  17788. }
  17789. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  17790. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  17791. scene.pushGeometry(sphere, true);
  17792. return sphere;
  17793. };
  17794. var parseCylinder = function (parsedCylinder, scene) {
  17795. if (parseGeometry(parsedCylinder, scene)) {
  17796. return null;
  17797. }
  17798. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  17799. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  17800. scene.pushGeometry(cylinder, true);
  17801. return cylinder;
  17802. };
  17803. var parseTorus = function (parsedTorus, scene) {
  17804. if (parseGeometry(parsedTorus, scene)) {
  17805. return null;
  17806. }
  17807. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  17808. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  17809. scene.pushGeometry(torus, true);
  17810. return torus;
  17811. };
  17812. var parseGround = function (parsedGround, scene) {
  17813. if (parseGeometry(parsedGround, scene)) {
  17814. return null;
  17815. }
  17816. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  17817. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  17818. scene.pushGeometry(ground, true);
  17819. return ground;
  17820. };
  17821. var parsePlane = function (parsedPlane, scene) {
  17822. if (parseGeometry(parsedPlane, scene)) {
  17823. return null;
  17824. }
  17825. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  17826. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  17827. scene.pushGeometry(plane, true);
  17828. return plane;
  17829. };
  17830. var parseTorusKnot = function (parsedTorusKnot, scene) {
  17831. if (parseGeometry(parsedTorusKnot, scene)) {
  17832. return null;
  17833. }
  17834. 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);
  17835. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  17836. scene.pushGeometry(torusKnot, true);
  17837. return torusKnot;
  17838. };
  17839. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  17840. if (parseGeometry(parsedVertexData, scene)) {
  17841. return null;
  17842. }
  17843. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  17844. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  17845. if (parsedVertexData.delayLoadingFile) {
  17846. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17847. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  17848. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  17849. geometry._delayInfo = [];
  17850. if (parsedVertexData.hasUVs) {
  17851. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17852. }
  17853. if (parsedVertexData.hasUVs2) {
  17854. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17855. }
  17856. if (parsedVertexData.hasColors) {
  17857. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17858. }
  17859. if (parsedVertexData.hasMatricesIndices) {
  17860. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17861. }
  17862. if (parsedVertexData.hasMatricesWeights) {
  17863. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17864. }
  17865. geometry._delayLoadingFunction = importVertexData;
  17866. } else {
  17867. importVertexData(parsedVertexData, geometry);
  17868. }
  17869. scene.pushGeometry(geometry, true);
  17870. return geometry;
  17871. };
  17872. var parseMesh = function (parsedMesh, scene, rootUrl) {
  17873. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  17874. mesh.id = parsedMesh.id;
  17875. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  17876. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  17877. if (parsedMesh.rotationQuaternion) {
  17878. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  17879. } else if (parsedMesh.rotation) {
  17880. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  17881. }
  17882. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  17883. if (parsedMesh.localMatrix) {
  17884. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  17885. } else if (parsedMesh.pivotMatrix) {
  17886. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  17887. }
  17888. mesh.setEnabled(parsedMesh.isEnabled);
  17889. mesh.isVisible = parsedMesh.isVisible;
  17890. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  17891. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  17892. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  17893. if (parsedMesh.applyFog !== undefined) {
  17894. mesh.applyFog = parsedMesh.applyFog;
  17895. }
  17896. if (parsedMesh.pickable !== undefined) {
  17897. mesh.isPickable = parsedMesh.pickable;
  17898. }
  17899. if (parsedMesh.alphaIndex !== undefined) {
  17900. mesh.alphaIndex = parsedMesh.alphaIndex;
  17901. }
  17902. mesh.receiveShadows = parsedMesh.receiveShadows;
  17903. mesh.billboardMode = parsedMesh.billboardMode;
  17904. if (parsedMesh.visibility !== undefined) {
  17905. mesh.visibility = parsedMesh.visibility;
  17906. }
  17907. mesh.checkCollisions = parsedMesh.checkCollisions;
  17908. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  17909. // Parent
  17910. if (parsedMesh.parentId) {
  17911. mesh._waitingParentId = parsedMesh.parentId;
  17912. }
  17913. // Actions
  17914. if (parsedMesh.actions !== undefined) {
  17915. mesh._waitingActions = parsedMesh.actions;
  17916. }
  17917. // Geometry
  17918. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  17919. if (parsedMesh.delayLoadingFile) {
  17920. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  17921. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  17922. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  17923. if (parsedMesh._binaryInfo) {
  17924. mesh._binaryInfo = parsedMesh._binaryInfo;
  17925. }
  17926. mesh._delayInfo = [];
  17927. if (parsedMesh.hasUVs) {
  17928. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  17929. }
  17930. if (parsedMesh.hasUVs2) {
  17931. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  17932. }
  17933. if (parsedMesh.hasColors) {
  17934. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  17935. }
  17936. if (parsedMesh.hasMatricesIndices) {
  17937. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  17938. }
  17939. if (parsedMesh.hasMatricesWeights) {
  17940. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  17941. }
  17942. mesh._delayLoadingFunction = importGeometry;
  17943. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  17944. mesh._checkDelayState();
  17945. }
  17946. } else {
  17947. importGeometry(parsedMesh, mesh);
  17948. }
  17949. // Material
  17950. if (parsedMesh.materialId) {
  17951. mesh.setMaterialByID(parsedMesh.materialId);
  17952. } else {
  17953. mesh.material = null;
  17954. }
  17955. // Skeleton
  17956. if (parsedMesh.skeletonId > -1) {
  17957. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  17958. }
  17959. // Physics
  17960. if (parsedMesh.physicsImpostor) {
  17961. if (!scene.isPhysicsEnabled()) {
  17962. scene.enablePhysics();
  17963. }
  17964. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  17965. }
  17966. // Animations
  17967. if (parsedMesh.animations) {
  17968. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17969. var parsedAnimation = parsedMesh.animations[animationIndex];
  17970. mesh.animations.push(parseAnimation(parsedAnimation));
  17971. }
  17972. }
  17973. if (parsedMesh.autoAnimate) {
  17974. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  17975. }
  17976. // Layer Mask
  17977. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  17978. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  17979. } else {
  17980. mesh.layerMask = 0xFFFFFFFF;
  17981. }
  17982. // Instances
  17983. if (parsedMesh.instances) {
  17984. for (var index = 0; index < parsedMesh.instances.length; index++) {
  17985. var parsedInstance = parsedMesh.instances[index];
  17986. var instance = mesh.createInstance(parsedInstance.name);
  17987. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  17988. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  17989. if (parsedInstance.rotationQuaternion) {
  17990. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  17991. } else if (parsedInstance.rotation) {
  17992. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  17993. }
  17994. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  17995. instance.checkCollisions = mesh.checkCollisions;
  17996. if (parsedMesh.animations) {
  17997. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  17998. parsedAnimation = parsedMesh.animations[animationIndex];
  17999. instance.animations.push(parseAnimation(parsedAnimation));
  18000. }
  18001. }
  18002. }
  18003. }
  18004. return mesh;
  18005. };
  18006. var parseActions = function (parsedActions, object, scene) {
  18007. object.actionManager = new BABYLON.ActionManager(scene);
  18008. // instanciate a new object
  18009. var instanciate = function (name, params) {
  18010. var newInstance = Object.create(BABYLON[name].prototype);
  18011. newInstance.constructor.apply(newInstance, params);
  18012. return newInstance;
  18013. };
  18014. var parseParameter = function (name, value, target, propertyPath) {
  18015. var split = value.split(",");
  18016. if (split.length == 1) {
  18017. var num = parseFloat(split[0]);
  18018. if (isNaN(num))
  18019. return split[0];
  18020. else
  18021. return num;
  18022. }
  18023. var effectiveTarget = propertyPath.split(".");
  18024. for (var i = 0; i < effectiveTarget.length; i++) {
  18025. target = target[effectiveTarget[i]];
  18026. }
  18027. if (split.length == 3) {
  18028. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2])];
  18029. if (target instanceof BABYLON.Vector3)
  18030. return BABYLON.Vector3.FromArray(values);
  18031. else
  18032. return BABYLON.Color3.FromArray(values);
  18033. }
  18034. if (split.length == 4) {
  18035. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2]), parseFloat(split[3])];
  18036. if (target instanceof BABYLON.Vector4)
  18037. return BABYLON.Vector4.FromArray(values);
  18038. else
  18039. return BABYLON.Color4.FromArray(values);
  18040. }
  18041. };
  18042. // traverse graph per trigger
  18043. var traverse = function (parsedAction, trigger, condition, action, actionManager) {
  18044. var parameters = new Array();
  18045. var target = null;
  18046. var propertyPath = null;
  18047. // Parameters
  18048. if (parsedAction.type == 2)
  18049. parameters.push(actionManager);
  18050. else
  18051. parameters.push(trigger);
  18052. for (var i = 0; i < parsedAction.properties.length; i++) {
  18053. var value = parsedAction.properties[i].value;
  18054. if (parsedAction.properties[i].name === "target") {
  18055. value = target = scene.getNodeByName(value);
  18056. } else if (parsedAction.properties[i].name != "propertyPath") {
  18057. if (value === "false" || value === "true")
  18058. value = value === "true";
  18059. else if (parsedAction.type === 2 && parsedAction.properties[i].name === "operator")
  18060. value = BABYLON.ValueCondition[value];
  18061. else
  18062. value = parseParameter(parsedAction.properties[i].name, value, target, propertyPath);
  18063. } else {
  18064. propertyPath = value;
  18065. }
  18066. parameters.push(value);
  18067. }
  18068. parameters.push(condition);
  18069. // If interpolate value action
  18070. if (parsedAction.name === "InterpolateValueAction") {
  18071. var param = parameters[parameters.length - 2];
  18072. parameters[parameters.length - 1] = param;
  18073. parameters[parameters.length - 2] = condition;
  18074. }
  18075. // Action or condition
  18076. var newAction = instanciate(parsedAction.name, parameters);
  18077. if (newAction instanceof BABYLON.Condition) {
  18078. condition = newAction;
  18079. newAction = action;
  18080. } else {
  18081. condition = null;
  18082. if (action)
  18083. action.then(newAction);
  18084. else
  18085. actionManager.registerAction(newAction);
  18086. }
  18087. for (var i = 0; i < parsedAction.children.length; i++)
  18088. traverse(parsedAction.children[i], trigger, condition, newAction, actionManager);
  18089. };
  18090. for (var i = 0; i < parsedActions.children.length; i++) {
  18091. var triggerParams;
  18092. var trigger = parsedActions.children[i];
  18093. if (trigger.properties.length > 0) {
  18094. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18095. } else
  18096. triggerParams = BABYLON.ActionManager[trigger.name];
  18097. for (var j = 0; j < trigger.children.length; j++)
  18098. traverse(trigger.children[j], triggerParams, null, null, object.actionManager);
  18099. }
  18100. };
  18101. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18102. names = (names instanceof Array) ? names : [names];
  18103. for (var i in names) {
  18104. if (mesh.name === names[i]) {
  18105. hierarchyIds.push(mesh.id);
  18106. return true;
  18107. }
  18108. }
  18109. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18110. hierarchyIds.push(mesh.id);
  18111. return true;
  18112. }
  18113. return false;
  18114. };
  18115. var importVertexData = function (parsedVertexData, geometry) {
  18116. var vertexData = new BABYLON.VertexData();
  18117. // positions
  18118. var positions = parsedVertexData.positions;
  18119. if (positions) {
  18120. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18121. }
  18122. // normals
  18123. var normals = parsedVertexData.normals;
  18124. if (normals) {
  18125. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18126. }
  18127. // uvs
  18128. var uvs = parsedVertexData.uvs;
  18129. if (uvs) {
  18130. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18131. }
  18132. // uv2s
  18133. var uv2s = parsedVertexData.uv2s;
  18134. if (uv2s) {
  18135. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18136. }
  18137. // colors
  18138. var colors = parsedVertexData.colors;
  18139. if (colors) {
  18140. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18141. }
  18142. // matricesIndices
  18143. var matricesIndices = parsedVertexData.matricesIndices;
  18144. if (matricesIndices) {
  18145. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18146. }
  18147. // matricesWeights
  18148. var matricesWeights = parsedVertexData.matricesWeights;
  18149. if (matricesWeights) {
  18150. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18151. }
  18152. // indices
  18153. var indices = parsedVertexData.indices;
  18154. if (indices) {
  18155. vertexData.indices = indices;
  18156. }
  18157. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18158. };
  18159. var importGeometry = function (parsedGeometry, mesh) {
  18160. var scene = mesh.getScene();
  18161. // Geometry
  18162. var geometryId = parsedGeometry.geometryId;
  18163. if (geometryId) {
  18164. var geometry = scene.getGeometryByID(geometryId);
  18165. if (geometry) {
  18166. geometry.applyToMesh(mesh);
  18167. }
  18168. } else if (parsedGeometry instanceof ArrayBuffer) {
  18169. var binaryInfo = mesh._binaryInfo;
  18170. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18171. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18172. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18173. }
  18174. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18175. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18176. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18177. }
  18178. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18179. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18180. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18181. }
  18182. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18183. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18184. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18185. }
  18186. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18187. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18188. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18189. }
  18190. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18191. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18192. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18193. }
  18194. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18195. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18197. }
  18198. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18199. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18200. mesh.setIndices(indicesData);
  18201. }
  18202. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18203. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18204. mesh.subMeshes = [];
  18205. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18206. var materialIndex = subMeshesData[(i * 5) + 0];
  18207. var verticesStart = subMeshesData[(i * 5) + 1];
  18208. var verticesCount = subMeshesData[(i * 5) + 2];
  18209. var indexStart = subMeshesData[(i * 5) + 3];
  18210. var indexCount = subMeshesData[(i * 5) + 4];
  18211. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18212. }
  18213. }
  18214. } else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18215. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18216. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18217. if (parsedGeometry.uvs) {
  18218. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18219. }
  18220. if (parsedGeometry.uvs2) {
  18221. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18222. }
  18223. if (parsedGeometry.colors) {
  18224. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18225. }
  18226. if (parsedGeometry.matricesIndices) {
  18227. if (!parsedGeometry.matricesIndices._isExpanded) {
  18228. var floatIndices = [];
  18229. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18230. var matricesIndex = parsedGeometry.matricesIndices[i];
  18231. floatIndices.push(matricesIndex & 0x000000FF);
  18232. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18233. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18234. floatIndices.push(matricesIndex >> 24);
  18235. }
  18236. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18237. } else {
  18238. delete parsedGeometry.matricesIndices._isExpanded;
  18239. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18240. }
  18241. }
  18242. if (parsedGeometry.matricesWeights) {
  18243. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18244. }
  18245. mesh.setIndices(parsedGeometry.indices);
  18246. // SubMeshes
  18247. if (parsedGeometry.subMeshes) {
  18248. mesh.subMeshes = [];
  18249. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18250. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18251. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18252. }
  18253. }
  18254. }
  18255. // Flat shading
  18256. if (mesh._shouldGenerateFlatShading) {
  18257. mesh.convertToFlatShadedMesh();
  18258. delete mesh._shouldGenerateFlatShading;
  18259. }
  18260. // Update
  18261. mesh.computeWorldMatrix(true);
  18262. // Octree
  18263. if (scene._selectionOctree) {
  18264. scene._selectionOctree.addMesh(mesh);
  18265. }
  18266. };
  18267. BABYLON.SceneLoader.RegisterPlugin({
  18268. extensions: ".babylon",
  18269. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18270. var parsedData = JSON.parse(data);
  18271. var loadedSkeletonsIds = [];
  18272. var loadedMaterialsIds = [];
  18273. var hierarchyIds = [];
  18274. for (var index = 0; index < parsedData.meshes.length; index++) {
  18275. var parsedMesh = parsedData.meshes[index];
  18276. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18277. if (meshesNames instanceof Array) {
  18278. // Remove found mesh name from list.
  18279. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18280. }
  18281. // Material ?
  18282. if (parsedMesh.materialId) {
  18283. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18284. if (!materialFound) {
  18285. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18286. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18287. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18288. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18289. var subMatId = parsedMultiMaterial.materials[matIndex];
  18290. loadedMaterialsIds.push(subMatId);
  18291. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18292. }
  18293. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18294. parseMultiMaterial(parsedMultiMaterial, scene);
  18295. materialFound = true;
  18296. break;
  18297. }
  18298. }
  18299. }
  18300. if (!materialFound) {
  18301. loadedMaterialsIds.push(parsedMesh.materialId);
  18302. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18303. }
  18304. }
  18305. // Skeleton ?
  18306. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18307. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18308. if (!skeletonAlreadyLoaded) {
  18309. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18310. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18311. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18312. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18313. loadedSkeletonsIds.push(parsedSkeleton.id);
  18314. }
  18315. }
  18316. }
  18317. }
  18318. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18319. meshes.push(mesh);
  18320. }
  18321. }
  18322. for (index = 0; index < scene.meshes.length; index++) {
  18323. var currentMesh = scene.meshes[index];
  18324. if (currentMesh._waitingParentId) {
  18325. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18326. currentMesh._waitingParentId = undefined;
  18327. }
  18328. }
  18329. // Particles
  18330. if (parsedData.particleSystems) {
  18331. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18332. var parsedParticleSystem = parsedData.particleSystems[index];
  18333. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18334. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18335. }
  18336. }
  18337. }
  18338. return true;
  18339. },
  18340. load: function (scene, data, rootUrl) {
  18341. var parsedData = JSON.parse(data);
  18342. // Scene
  18343. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18344. scene.autoClear = parsedData.autoClear;
  18345. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18346. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18347. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18348. // Fog
  18349. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18350. scene.fogMode = parsedData.fogMode;
  18351. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18352. scene.fogStart = parsedData.fogStart;
  18353. scene.fogEnd = parsedData.fogEnd;
  18354. scene.fogDensity = parsedData.fogDensity;
  18355. }
  18356. for (var index = 0; index < parsedData.lights.length; index++) {
  18357. var parsedLight = parsedData.lights[index];
  18358. parseLight(parsedLight, scene);
  18359. }
  18360. // Materials
  18361. if (parsedData.materials) {
  18362. for (index = 0; index < parsedData.materials.length; index++) {
  18363. var parsedMaterial = parsedData.materials[index];
  18364. parseMaterial(parsedMaterial, scene, rootUrl);
  18365. }
  18366. }
  18367. if (parsedData.multiMaterials) {
  18368. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18369. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18370. parseMultiMaterial(parsedMultiMaterial, scene);
  18371. }
  18372. }
  18373. // Skeletons
  18374. if (parsedData.skeletons) {
  18375. for (index = 0; index < parsedData.skeletons.length; index++) {
  18376. var parsedSkeleton = parsedData.skeletons[index];
  18377. parseSkeleton(parsedSkeleton, scene);
  18378. }
  18379. }
  18380. // Geometries
  18381. var geometries = parsedData.geometries;
  18382. if (geometries) {
  18383. // Boxes
  18384. var boxes = geometries.boxes;
  18385. if (boxes) {
  18386. for (index = 0; index < boxes.length; index++) {
  18387. var parsedBox = boxes[index];
  18388. parseBox(parsedBox, scene);
  18389. }
  18390. }
  18391. // Spheres
  18392. var spheres = geometries.spheres;
  18393. if (spheres) {
  18394. for (index = 0; index < spheres.length; index++) {
  18395. var parsedSphere = spheres[index];
  18396. parseSphere(parsedSphere, scene);
  18397. }
  18398. }
  18399. // Cylinders
  18400. var cylinders = geometries.cylinders;
  18401. if (cylinders) {
  18402. for (index = 0; index < cylinders.length; index++) {
  18403. var parsedCylinder = cylinders[index];
  18404. parseCylinder(parsedCylinder, scene);
  18405. }
  18406. }
  18407. // Toruses
  18408. var toruses = geometries.toruses;
  18409. if (toruses) {
  18410. for (index = 0; index < toruses.length; index++) {
  18411. var parsedTorus = toruses[index];
  18412. parseTorus(parsedTorus, scene);
  18413. }
  18414. }
  18415. // Grounds
  18416. var grounds = geometries.grounds;
  18417. if (grounds) {
  18418. for (index = 0; index < grounds.length; index++) {
  18419. var parsedGround = grounds[index];
  18420. parseGround(parsedGround, scene);
  18421. }
  18422. }
  18423. // Planes
  18424. var planes = geometries.planes;
  18425. if (planes) {
  18426. for (index = 0; index < planes.length; index++) {
  18427. var parsedPlane = planes[index];
  18428. parsePlane(parsedPlane, scene);
  18429. }
  18430. }
  18431. // TorusKnots
  18432. var torusKnots = geometries.torusKnots;
  18433. if (torusKnots) {
  18434. for (index = 0; index < torusKnots.length; index++) {
  18435. var parsedTorusKnot = torusKnots[index];
  18436. parseTorusKnot(parsedTorusKnot, scene);
  18437. }
  18438. }
  18439. // VertexData
  18440. var vertexData = geometries.vertexData;
  18441. if (vertexData) {
  18442. for (index = 0; index < vertexData.length; index++) {
  18443. var parsedVertexData = vertexData[index];
  18444. parseVertexData(parsedVertexData, scene, rootUrl);
  18445. }
  18446. }
  18447. }
  18448. for (index = 0; index < parsedData.meshes.length; index++) {
  18449. var parsedMesh = parsedData.meshes[index];
  18450. parseMesh(parsedMesh, scene, rootUrl);
  18451. }
  18452. for (index = 0; index < parsedData.cameras.length; index++) {
  18453. var parsedCamera = parsedData.cameras[index];
  18454. parseCamera(parsedCamera, scene);
  18455. }
  18456. if (parsedData.activeCameraID) {
  18457. scene.setActiveCameraByID(parsedData.activeCameraID);
  18458. }
  18459. for (index = 0; index < scene.cameras.length; index++) {
  18460. var camera = scene.cameras[index];
  18461. if (camera._waitingParentId) {
  18462. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18463. camera._waitingParentId = undefined;
  18464. }
  18465. }
  18466. for (index = 0; index < scene.lights.length; index++) {
  18467. var light = scene.lights[index];
  18468. if (light._waitingParentId) {
  18469. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18470. light._waitingParentId = undefined;
  18471. }
  18472. }
  18473. for (index = 0; index < scene.meshes.length; index++) {
  18474. var mesh = scene.meshes[index];
  18475. if (mesh._waitingParentId) {
  18476. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18477. mesh._waitingParentId = undefined;
  18478. }
  18479. if (mesh._waitingActions) {
  18480. parseActions(mesh._waitingActions, mesh, scene);
  18481. mesh._waitingActions = undefined;
  18482. }
  18483. }
  18484. // Particles Systems
  18485. if (parsedData.particleSystems) {
  18486. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18487. var parsedParticleSystem = parsedData.particleSystems[index];
  18488. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18489. }
  18490. }
  18491. // Lens flares
  18492. if (parsedData.lensFlareSystems) {
  18493. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18494. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18495. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18496. }
  18497. }
  18498. // Shadows
  18499. if (parsedData.shadowGenerators) {
  18500. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18501. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18502. parseShadowGenerator(parsedShadowGenerator, scene);
  18503. }
  18504. }
  18505. // Actions (scene)
  18506. if (parsedData.actions) {
  18507. parseActions(parsedData.actions, scene, scene);
  18508. }
  18509. // Finish
  18510. return true;
  18511. }
  18512. });
  18513. })(BABYLON.Internals || (BABYLON.Internals = {}));
  18514. var Internals = BABYLON.Internals;
  18515. })(BABYLON || (BABYLON = {}));
  18516. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  18517. var BABYLON;
  18518. (function (BABYLON) {
  18519. // Unique ID when we import meshes from Babylon to CSG
  18520. var currentCSGMeshId = 0;
  18521. // # class Vertex
  18522. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18523. // one to provide additional features like texture coordinates and vertex
  18524. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18525. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18526. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18527. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18528. // is not used anywhere else.
  18529. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18530. var Vertex = (function () {
  18531. function Vertex(pos, normal, uv) {
  18532. this.pos = pos;
  18533. this.normal = normal;
  18534. this.uv = uv;
  18535. }
  18536. Vertex.prototype.clone = function () {
  18537. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18538. };
  18539. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18540. // orientation of a polygon is flipped.
  18541. Vertex.prototype.flip = function () {
  18542. this.normal = this.normal.scale(-1);
  18543. };
  18544. // Create a new vertex between this vertex and `other` by linearly
  18545. // interpolating all properties using a parameter of `t`. Subclasses should
  18546. // override this to interpolate additional properties.
  18547. Vertex.prototype.interpolate = function (other, t) {
  18548. 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));
  18549. };
  18550. return Vertex;
  18551. })();
  18552. // # class Plane
  18553. // Represents a plane in 3D space.
  18554. var Plane = (function () {
  18555. function Plane(normal, w) {
  18556. this.normal = normal;
  18557. this.w = w;
  18558. }
  18559. Plane.FromPoints = function (a, b, c) {
  18560. var v0 = c.subtract(a);
  18561. var v1 = b.subtract(a);
  18562. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18563. return null;
  18564. }
  18565. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18566. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18567. };
  18568. Plane.prototype.clone = function () {
  18569. return new Plane(this.normal.clone(), this.w);
  18570. };
  18571. Plane.prototype.flip = function () {
  18572. this.normal.scaleInPlace(-1);
  18573. this.w = -this.w;
  18574. };
  18575. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18576. // fragments in the appropriate lists. Coplanar polygons go into either
  18577. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18578. // respect to this plane. Polygons in front or in back of this plane go into
  18579. // either `front` or `back`.
  18580. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18581. var COPLANAR = 0;
  18582. var FRONT = 1;
  18583. var BACK = 2;
  18584. var SPANNING = 3;
  18585. // Classify each point as well as the entire polygon into one of the above
  18586. // four classes.
  18587. var polygonType = 0;
  18588. var types = [];
  18589. for (var i = 0; i < polygon.vertices.length; i++) {
  18590. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18591. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18592. polygonType |= type;
  18593. types.push(type);
  18594. }
  18595. switch (polygonType) {
  18596. case COPLANAR:
  18597. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18598. break;
  18599. case FRONT:
  18600. front.push(polygon);
  18601. break;
  18602. case BACK:
  18603. back.push(polygon);
  18604. break;
  18605. case SPANNING:
  18606. var f = [], b = [];
  18607. for (i = 0; i < polygon.vertices.length; i++) {
  18608. var j = (i + 1) % polygon.vertices.length;
  18609. var ti = types[i], tj = types[j];
  18610. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18611. if (ti != BACK)
  18612. f.push(vi);
  18613. if (ti != FRONT)
  18614. b.push(ti != BACK ? vi.clone() : vi);
  18615. if ((ti | tj) == SPANNING) {
  18616. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18617. var v = vi.interpolate(vj, t);
  18618. f.push(v);
  18619. b.push(v.clone());
  18620. }
  18621. }
  18622. if (f.length >= 3) {
  18623. var poly = new Polygon(f, polygon.shared);
  18624. if (poly.plane)
  18625. front.push(poly);
  18626. }
  18627. if (b.length >= 3) {
  18628. poly = new Polygon(b, polygon.shared);
  18629. if (poly.plane)
  18630. back.push(poly);
  18631. }
  18632. break;
  18633. }
  18634. };
  18635. Plane.EPSILON = 1e-5;
  18636. return Plane;
  18637. })();
  18638. // # class Polygon
  18639. // Represents a convex polygon. The vertices used to initialize a polygon must
  18640. // be coplanar and form a convex loop.
  18641. //
  18642. // Each convex polygon has a `shared` property, which is shared between all
  18643. // polygons that are clones of each other or were split from the same polygon.
  18644. // This can be used to define per-polygon properties (such as surface color).
  18645. var Polygon = (function () {
  18646. function Polygon(vertices, shared) {
  18647. this.vertices = vertices;
  18648. this.shared = shared;
  18649. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18650. }
  18651. Polygon.prototype.clone = function () {
  18652. var vertices = this.vertices.map(function (v) {
  18653. return v.clone();
  18654. });
  18655. return new Polygon(vertices, this.shared);
  18656. };
  18657. Polygon.prototype.flip = function () {
  18658. this.vertices.reverse().map(function (v) {
  18659. v.flip();
  18660. });
  18661. this.plane.flip();
  18662. };
  18663. return Polygon;
  18664. })();
  18665. // # class Node
  18666. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18667. // by picking a polygon to split along. That polygon (and all other coplanar
  18668. // polygons) are added directly to that node and the other polygons are added to
  18669. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18670. // no distinction between internal and leaf nodes.
  18671. var Node = (function () {
  18672. function Node(polygons) {
  18673. this.plane = null;
  18674. this.front = null;
  18675. this.back = null;
  18676. this.polygons = [];
  18677. if (polygons) {
  18678. this.build(polygons);
  18679. }
  18680. }
  18681. Node.prototype.clone = function () {
  18682. var node = new Node();
  18683. node.plane = this.plane && this.plane.clone();
  18684. node.front = this.front && this.front.clone();
  18685. node.back = this.back && this.back.clone();
  18686. node.polygons = this.polygons.map(function (p) {
  18687. return p.clone();
  18688. });
  18689. return node;
  18690. };
  18691. // Convert solid space to empty space and empty space to solid space.
  18692. Node.prototype.invert = function () {
  18693. for (var i = 0; i < this.polygons.length; i++) {
  18694. this.polygons[i].flip();
  18695. }
  18696. if (this.plane) {
  18697. this.plane.flip();
  18698. }
  18699. if (this.front) {
  18700. this.front.invert();
  18701. }
  18702. if (this.back) {
  18703. this.back.invert();
  18704. }
  18705. var temp = this.front;
  18706. this.front = this.back;
  18707. this.back = temp;
  18708. };
  18709. // Recursively remove all polygons in `polygons` that are inside this BSP
  18710. // tree.
  18711. Node.prototype.clipPolygons = function (polygons) {
  18712. if (!this.plane)
  18713. return polygons.slice();
  18714. var front = [], back = [];
  18715. for (var i = 0; i < polygons.length; i++) {
  18716. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18717. }
  18718. if (this.front) {
  18719. front = this.front.clipPolygons(front);
  18720. }
  18721. if (this.back) {
  18722. back = this.back.clipPolygons(back);
  18723. } else {
  18724. back = [];
  18725. }
  18726. return front.concat(back);
  18727. };
  18728. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18729. // `bsp`.
  18730. Node.prototype.clipTo = function (bsp) {
  18731. this.polygons = bsp.clipPolygons(this.polygons);
  18732. if (this.front)
  18733. this.front.clipTo(bsp);
  18734. if (this.back)
  18735. this.back.clipTo(bsp);
  18736. };
  18737. // Return a list of all polygons in this BSP tree.
  18738. Node.prototype.allPolygons = function () {
  18739. var polygons = this.polygons.slice();
  18740. if (this.front)
  18741. polygons = polygons.concat(this.front.allPolygons());
  18742. if (this.back)
  18743. polygons = polygons.concat(this.back.allPolygons());
  18744. return polygons;
  18745. };
  18746. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18747. // new polygons are filtered down to the bottom of the tree and become new
  18748. // nodes there. Each set of polygons is partitioned using the first polygon
  18749. // (no heuristic is used to pick a good split).
  18750. Node.prototype.build = function (polygons) {
  18751. if (!polygons.length)
  18752. return;
  18753. if (!this.plane)
  18754. this.plane = polygons[0].plane.clone();
  18755. var front = [], back = [];
  18756. for (var i = 0; i < polygons.length; i++) {
  18757. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18758. }
  18759. if (front.length) {
  18760. if (!this.front)
  18761. this.front = new Node();
  18762. this.front.build(front);
  18763. }
  18764. if (back.length) {
  18765. if (!this.back)
  18766. this.back = new Node();
  18767. this.back.build(back);
  18768. }
  18769. };
  18770. return Node;
  18771. })();
  18772. var CSG = (function () {
  18773. function CSG() {
  18774. this.polygons = new Array();
  18775. }
  18776. // Convert BABYLON.Mesh to BABYLON.CSG
  18777. CSG.FromMesh = function (mesh) {
  18778. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  18779. if (mesh instanceof BABYLON.Mesh) {
  18780. mesh.computeWorldMatrix(true);
  18781. var matrix = mesh.getWorldMatrix();
  18782. var meshPosition = mesh.position.clone();
  18783. var meshRotation = mesh.rotation.clone();
  18784. var meshScaling = mesh.scaling.clone();
  18785. } else {
  18786. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  18787. }
  18788. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18789. var subMeshes = mesh.subMeshes;
  18790. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  18791. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  18792. vertices = [];
  18793. for (var j = 0; j < 3; j++) {
  18794. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  18795. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  18796. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  18797. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  18798. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  18799. vertex = new Vertex(position, normal, uv);
  18800. vertices.push(vertex);
  18801. }
  18802. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  18803. // To handle the case of degenerated triangle
  18804. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  18805. if (polygon.plane)
  18806. polygons.push(polygon);
  18807. }
  18808. }
  18809. var csg = CSG.FromPolygons(polygons);
  18810. csg.matrix = matrix;
  18811. csg.position = meshPosition;
  18812. csg.rotation = meshRotation;
  18813. csg.scaling = meshScaling;
  18814. currentCSGMeshId++;
  18815. return csg;
  18816. };
  18817. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  18818. CSG.FromPolygons = function (polygons) {
  18819. var csg = new BABYLON.CSG();
  18820. csg.polygons = polygons;
  18821. return csg;
  18822. };
  18823. CSG.prototype.clone = function () {
  18824. var csg = new BABYLON.CSG();
  18825. csg.polygons = this.polygons.map(function (p) {
  18826. return p.clone();
  18827. });
  18828. csg.copyTransformAttributes(this);
  18829. return csg;
  18830. };
  18831. CSG.prototype.toPolygons = function () {
  18832. return this.polygons;
  18833. };
  18834. CSG.prototype.union = function (csg) {
  18835. var a = new Node(this.clone().polygons);
  18836. var b = new Node(csg.clone().polygons);
  18837. a.clipTo(b);
  18838. b.clipTo(a);
  18839. b.invert();
  18840. b.clipTo(a);
  18841. b.invert();
  18842. a.build(b.allPolygons());
  18843. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18844. };
  18845. CSG.prototype.unionInPlace = function (csg) {
  18846. var a = new Node(this.polygons);
  18847. var b = new Node(csg.polygons);
  18848. a.clipTo(b);
  18849. b.clipTo(a);
  18850. b.invert();
  18851. b.clipTo(a);
  18852. b.invert();
  18853. a.build(b.allPolygons());
  18854. this.polygons = a.allPolygons();
  18855. };
  18856. CSG.prototype.subtract = function (csg) {
  18857. var a = new Node(this.clone().polygons);
  18858. var b = new Node(csg.clone().polygons);
  18859. a.invert();
  18860. a.clipTo(b);
  18861. b.clipTo(a);
  18862. b.invert();
  18863. b.clipTo(a);
  18864. b.invert();
  18865. a.build(b.allPolygons());
  18866. a.invert();
  18867. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18868. };
  18869. CSG.prototype.subtractInPlace = function (csg) {
  18870. var a = new Node(this.polygons);
  18871. var b = new Node(csg.polygons);
  18872. a.invert();
  18873. a.clipTo(b);
  18874. b.clipTo(a);
  18875. b.invert();
  18876. b.clipTo(a);
  18877. b.invert();
  18878. a.build(b.allPolygons());
  18879. a.invert();
  18880. this.polygons = a.allPolygons();
  18881. };
  18882. CSG.prototype.intersect = function (csg) {
  18883. var a = new Node(this.clone().polygons);
  18884. var b = new Node(csg.clone().polygons);
  18885. a.invert();
  18886. b.clipTo(a);
  18887. b.invert();
  18888. a.clipTo(b);
  18889. b.clipTo(a);
  18890. a.build(b.allPolygons());
  18891. a.invert();
  18892. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  18893. };
  18894. CSG.prototype.intersectInPlace = function (csg) {
  18895. var a = new Node(this.polygons);
  18896. var b = new Node(csg.polygons);
  18897. a.invert();
  18898. b.clipTo(a);
  18899. b.invert();
  18900. a.clipTo(b);
  18901. b.clipTo(a);
  18902. a.build(b.allPolygons());
  18903. a.invert();
  18904. this.polygons = a.allPolygons();
  18905. };
  18906. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  18907. // not modified.
  18908. CSG.prototype.inverse = function () {
  18909. var csg = this.clone();
  18910. csg.inverseInPlace();
  18911. return csg;
  18912. };
  18913. CSG.prototype.inverseInPlace = function () {
  18914. this.polygons.map(function (p) {
  18915. p.flip();
  18916. });
  18917. };
  18918. // This is used to keep meshes transformations so they can be restored
  18919. // when we build back a Babylon Mesh
  18920. // NB : All CSG operations are performed in world coordinates
  18921. CSG.prototype.copyTransformAttributes = function (csg) {
  18922. this.matrix = csg.matrix;
  18923. this.position = csg.position;
  18924. this.rotation = csg.rotation;
  18925. this.scaling = csg.scaling;
  18926. return this;
  18927. };
  18928. // Build Raw mesh from CSG
  18929. // Coordinates here are in world space
  18930. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  18931. var matrix = this.matrix.clone();
  18932. matrix.invert();
  18933. 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;
  18934. if (keepSubMeshes) {
  18935. // Sort Polygons, since subMeshes are indices range
  18936. polygons.sort(function (a, b) {
  18937. if (a.shared.meshId === b.shared.meshId) {
  18938. return a.shared.subMeshId - b.shared.subMeshId;
  18939. } else {
  18940. return a.shared.meshId - b.shared.meshId;
  18941. }
  18942. });
  18943. }
  18944. for (var i = 0, il = polygons.length; i < il; i++) {
  18945. polygon = polygons[i];
  18946. // Building SubMeshes
  18947. if (!subMesh_dict[polygon.shared.meshId]) {
  18948. subMesh_dict[polygon.shared.meshId] = {};
  18949. }
  18950. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  18951. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  18952. indexStart: +Infinity,
  18953. indexEnd: -Infinity,
  18954. materialIndex: polygon.shared.materialIndex
  18955. };
  18956. }
  18957. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  18958. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  18959. polygonIndices[0] = 0;
  18960. polygonIndices[1] = j - 1;
  18961. polygonIndices[2] = j;
  18962. for (var k = 0; k < 3; k++) {
  18963. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  18964. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  18965. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  18966. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  18967. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  18968. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  18969. // Check if 2 points can be merged
  18970. 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)) {
  18971. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  18972. uvs.push(uv.x, uv.y);
  18973. normals.push(normal.x, normal.y, normal.z);
  18974. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  18975. }
  18976. indices.push(vertex_idx);
  18977. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  18978. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  18979. currentIndex++;
  18980. }
  18981. }
  18982. }
  18983. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  18984. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  18985. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  18986. mesh.setIndices(indices);
  18987. if (keepSubMeshes) {
  18988. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  18989. var materialIndexOffset = 0, materialMaxIndex;
  18990. mesh.subMeshes.length = 0;
  18991. for (var m in subMesh_dict) {
  18992. materialMaxIndex = -1;
  18993. for (var sm in subMesh_dict[m]) {
  18994. subMesh_obj = subMesh_dict[m][sm];
  18995. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  18996. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  18997. }
  18998. materialIndexOffset += ++materialMaxIndex;
  18999. }
  19000. }
  19001. return mesh;
  19002. };
  19003. // Build Mesh from CSG taking material and transforms into account
  19004. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19005. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19006. mesh.material = material;
  19007. mesh.position.copyFrom(this.position);
  19008. mesh.rotation.copyFrom(this.rotation);
  19009. mesh.scaling.copyFrom(this.scaling);
  19010. mesh.computeWorldMatrix(true);
  19011. return mesh;
  19012. };
  19013. return CSG;
  19014. })();
  19015. BABYLON.CSG = CSG;
  19016. })(BABYLON || (BABYLON = {}));
  19017. //# sourceMappingURL=babylon.csg.js.map
  19018. var BABYLON;
  19019. (function (BABYLON) {
  19020. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19021. __extends(OculusDistortionCorrectionPostProcess, _super);
  19022. //ANY
  19023. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19024. var _this = this;
  19025. _super.call(this, name, "oculusDistortionCorrection", [
  19026. 'LensCenter',
  19027. 'Scale',
  19028. 'ScaleIn',
  19029. 'HmdWarpParam'
  19030. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19031. this._isRightEye = isRightEye;
  19032. this._distortionFactors = cameraSettings.DistortionK;
  19033. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19034. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19035. this.onSizeChanged = function () {
  19036. _this.aspectRatio = _this.width * .5 / _this.height;
  19037. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19038. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19039. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19040. };
  19041. this.onApply = function (effect) {
  19042. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19043. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19044. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19045. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19046. };
  19047. }
  19048. return OculusDistortionCorrectionPostProcess;
  19049. })(BABYLON.PostProcess);
  19050. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19051. })(BABYLON || (BABYLON = {}));
  19052. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map
  19053. // Mainly based on these 2 articles :
  19054. // 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
  19055. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19056. var BABYLON;
  19057. (function (BABYLON) {
  19058. (function (JoystickAxis) {
  19059. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19060. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19061. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19062. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19063. var JoystickAxis = BABYLON.JoystickAxis;
  19064. var VirtualJoystick = (function () {
  19065. function VirtualJoystick(leftJoystick) {
  19066. var _this = this;
  19067. if (leftJoystick) {
  19068. this._leftJoystick = true;
  19069. } else {
  19070. this._leftJoystick = false;
  19071. }
  19072. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19073. VirtualJoystick._globalJoystickIndex++;
  19074. // By default left & right arrow keys are moving the X
  19075. // and up & down keys are moving the Y
  19076. this._axisTargetedByLeftAndRight = 0 /* X */;
  19077. this._axisTargetedByUpAndDown = 1 /* Y */;
  19078. this.reverseLeftRight = false;
  19079. this.reverseUpDown = false;
  19080. // collections of pointers
  19081. this._touches = new BABYLON.VirtualJoystick.Collection();
  19082. this.deltaPosition = BABYLON.Vector3.Zero();
  19083. this._joystickSensibility = 25;
  19084. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19085. this._rotationSpeed = 25;
  19086. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19087. this._rotateOnAxisRelativeToMesh = false;
  19088. // injecting a canvas element on top of the canvas 3D game
  19089. if (!VirtualJoystick.vjCanvas) {
  19090. window.addEventListener("resize", function () {
  19091. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19092. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19093. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19094. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19095. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19096. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19097. }, false);
  19098. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19099. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19100. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19101. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19102. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19103. VirtualJoystick.vjCanvas.style.width = "100%";
  19104. VirtualJoystick.vjCanvas.style.height = "100%";
  19105. VirtualJoystick.vjCanvas.style.position = "absolute";
  19106. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19107. VirtualJoystick.vjCanvas.style.top = "0px";
  19108. VirtualJoystick.vjCanvas.style.left = "0px";
  19109. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19110. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19111. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19112. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19113. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19114. document.body.appendChild(VirtualJoystick.vjCanvas);
  19115. }
  19116. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19117. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19118. this.pressed = false;
  19119. // default joystick color
  19120. this._joystickColor = "cyan";
  19121. this._joystickPointerID = -1;
  19122. // current joystick position
  19123. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19124. // origin joystick position
  19125. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19126. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19127. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19128. _this._onPointerDown(evt);
  19129. }, false);
  19130. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19131. _this._onPointerMove(evt);
  19132. }, false);
  19133. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19134. _this._onPointerUp(evt);
  19135. }, false);
  19136. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19137. _this._onPointerUp(evt);
  19138. }, false);
  19139. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19140. evt.preventDefault(); // Disables system menu
  19141. }, false);
  19142. requestAnimationFrame(function () {
  19143. _this._drawVirtualJoystick();
  19144. });
  19145. }
  19146. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19147. this._joystickSensibility = newJoystickSensibility;
  19148. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19149. };
  19150. VirtualJoystick.prototype._onPointerDown = function (e) {
  19151. var positionOnScreenCondition;
  19152. e.preventDefault();
  19153. if (this._leftJoystick === true) {
  19154. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19155. } else {
  19156. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19157. }
  19158. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19159. // First contact will be dedicated to the virtual joystick
  19160. this._joystickPointerID = e.pointerId;
  19161. this._joystickPointerStartPos.x = e.clientX;
  19162. this._joystickPointerStartPos.y = e.clientY;
  19163. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19164. this._deltaJoystickVector.x = 0;
  19165. this._deltaJoystickVector.y = 0;
  19166. this.pressed = true;
  19167. this._touches.add(e.pointerId.toString(), e);
  19168. } else {
  19169. // You can only trigger the action buttons with a joystick declared
  19170. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19171. this._action();
  19172. this._touches.add(e.pointerId.toString(), e);
  19173. }
  19174. }
  19175. };
  19176. VirtualJoystick.prototype._onPointerMove = function (e) {
  19177. // If the current pointer is the one associated to the joystick (first touch contact)
  19178. if (this._joystickPointerID == e.pointerId) {
  19179. this._joystickPointerPos.x = e.clientX;
  19180. this._joystickPointerPos.y = e.clientY;
  19181. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19182. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19183. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19184. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19185. switch (this._axisTargetedByLeftAndRight) {
  19186. case 0 /* X */:
  19187. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19188. break;
  19189. case 1 /* Y */:
  19190. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19191. break;
  19192. case 2 /* Z */:
  19193. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19194. break;
  19195. }
  19196. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19197. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19198. switch (this._axisTargetedByUpAndDown) {
  19199. case 0 /* X */:
  19200. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19201. break;
  19202. case 1 /* Y */:
  19203. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19204. break;
  19205. case 2 /* Z */:
  19206. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19207. break;
  19208. }
  19209. } else {
  19210. if (this._touches.item(e.pointerId.toString())) {
  19211. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19212. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19213. }
  19214. }
  19215. };
  19216. VirtualJoystick.prototype._onPointerUp = function (e) {
  19217. this._clearCanvas();
  19218. if (this._joystickPointerID == e.pointerId) {
  19219. this._joystickPointerID = -1;
  19220. this.pressed = false;
  19221. }
  19222. this._deltaJoystickVector.x = 0;
  19223. this._deltaJoystickVector.y = 0;
  19224. this._touches.remove(e.pointerId.toString());
  19225. };
  19226. /**
  19227. * Change the color of the virtual joystick
  19228. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19229. */
  19230. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19231. this._joystickColor = newColor;
  19232. };
  19233. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19234. this._action = action;
  19235. };
  19236. // Define which axis you'd like to control for left & right
  19237. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19238. switch (axis) {
  19239. case 0 /* X */:
  19240. case 1 /* Y */:
  19241. case 2 /* Z */:
  19242. this._axisTargetedByLeftAndRight = axis;
  19243. break;
  19244. default:
  19245. this._axisTargetedByLeftAndRight = 0 /* X */;
  19246. break;
  19247. }
  19248. };
  19249. // Define which axis you'd like to control for up & down
  19250. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19251. switch (axis) {
  19252. case 0 /* X */:
  19253. case 1 /* Y */:
  19254. case 2 /* Z */:
  19255. this._axisTargetedByUpAndDown = axis;
  19256. break;
  19257. default:
  19258. this._axisTargetedByUpAndDown = 1 /* Y */;
  19259. break;
  19260. }
  19261. };
  19262. VirtualJoystick.prototype._clearCanvas = function () {
  19263. if (this._leftJoystick) {
  19264. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19265. } else {
  19266. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19267. }
  19268. };
  19269. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19270. var _this = this;
  19271. if (this.pressed) {
  19272. this._clearCanvas();
  19273. this._touches.forEach(function (touch) {
  19274. if (touch.pointerId === _this._joystickPointerID) {
  19275. VirtualJoystick.vjCanvasContext.beginPath();
  19276. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19277. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19278. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19279. VirtualJoystick.vjCanvasContext.stroke();
  19280. VirtualJoystick.vjCanvasContext.beginPath();
  19281. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19282. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19283. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19284. VirtualJoystick.vjCanvasContext.stroke();
  19285. VirtualJoystick.vjCanvasContext.beginPath();
  19286. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19287. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19288. VirtualJoystick.vjCanvasContext.stroke();
  19289. } else {
  19290. VirtualJoystick.vjCanvasContext.beginPath();
  19291. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19292. VirtualJoystick.vjCanvasContext.beginPath();
  19293. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19294. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19295. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19296. VirtualJoystick.vjCanvasContext.stroke();
  19297. }
  19298. ;
  19299. });
  19300. }
  19301. requestAnimationFrame(function () {
  19302. _this._drawVirtualJoystick();
  19303. });
  19304. };
  19305. VirtualJoystick.prototype.releaseCanvas = function () {
  19306. if (VirtualJoystick.vjCanvas) {
  19307. document.body.removeChild(VirtualJoystick.vjCanvas);
  19308. VirtualJoystick.vjCanvas = null;
  19309. }
  19310. };
  19311. VirtualJoystick._globalJoystickIndex = 0;
  19312. return VirtualJoystick;
  19313. })();
  19314. BABYLON.VirtualJoystick = VirtualJoystick;
  19315. })(BABYLON || (BABYLON = {}));
  19316. var BABYLON;
  19317. (function (BABYLON) {
  19318. (function (VirtualJoystick) {
  19319. var Collection = (function () {
  19320. function Collection() {
  19321. this._count = 0;
  19322. this._collection = new Array();
  19323. }
  19324. Collection.prototype.Count = function () {
  19325. return this._count;
  19326. };
  19327. Collection.prototype.add = function (key, item) {
  19328. if (this._collection[key] != undefined) {
  19329. return undefined;
  19330. }
  19331. this._collection[key] = item;
  19332. return ++this._count;
  19333. };
  19334. Collection.prototype.remove = function (key) {
  19335. if (this._collection[key] == undefined) {
  19336. return undefined;
  19337. }
  19338. delete this._collection[key];
  19339. return --this._count;
  19340. };
  19341. Collection.prototype.item = function (key) {
  19342. return this._collection[key];
  19343. };
  19344. Collection.prototype.forEach = function (block) {
  19345. var key;
  19346. for (key in this._collection) {
  19347. if (this._collection.hasOwnProperty(key)) {
  19348. block(this._collection[key]);
  19349. }
  19350. }
  19351. };
  19352. return Collection;
  19353. })();
  19354. VirtualJoystick.Collection = Collection;
  19355. })(BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19356. var VirtualJoystick = BABYLON.VirtualJoystick;
  19357. })(BABYLON || (BABYLON = {}));
  19358. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19359. var BABYLON;
  19360. (function (BABYLON) {
  19361. var OculusRiftDevKit2013_Metric = {
  19362. HResolution: 1280,
  19363. VResolution: 800,
  19364. HScreenSize: 0.149759993,
  19365. VScreenSize: 0.0935999975,
  19366. VScreenCenter: 0.0467999987,
  19367. EyeToScreenDistance: 0.0410000011,
  19368. LensSeparationDistance: 0.0635000020,
  19369. InterpupillaryDistance: 0.0640000030,
  19370. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19371. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19372. PostProcessScaleFactor: 1.714605507808412,
  19373. LensCenterOffset: 0.151976421
  19374. };
  19375. var _OculusInnerCamera = (function (_super) {
  19376. __extends(_OculusInnerCamera, _super);
  19377. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19378. _super.call(this, name, position, scene);
  19379. this._workMatrix = new BABYLON.Matrix();
  19380. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19381. // Constants
  19382. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19383. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19384. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19385. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19386. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19387. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19388. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19389. // Postprocess
  19390. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19391. }
  19392. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19393. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19394. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19395. return this._projectionMatrix;
  19396. };
  19397. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19398. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19399. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19400. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19401. // Computing target and final matrix
  19402. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19403. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19404. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19405. return this._viewMatrix;
  19406. };
  19407. return _OculusInnerCamera;
  19408. })(BABYLON.FreeCamera);
  19409. var OculusCamera = (function (_super) {
  19410. __extends(OculusCamera, _super);
  19411. function OculusCamera(name, position, scene) {
  19412. _super.call(this, name, position, scene);
  19413. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19414. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19415. this.subCameras.push(this._leftCamera);
  19416. this.subCameras.push(this._rightCamera);
  19417. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19418. }
  19419. OculusCamera.prototype._update = function () {
  19420. this._leftCamera.position.copyFrom(this.position);
  19421. this._rightCamera.position.copyFrom(this.position);
  19422. this._updateCamera(this._leftCamera);
  19423. this._updateCamera(this._rightCamera);
  19424. _super.prototype._update.call(this);
  19425. };
  19426. OculusCamera.prototype._updateCamera = function (camera) {
  19427. camera.minZ = this.minZ;
  19428. camera.maxZ = this.maxZ;
  19429. camera.rotation.x = this.rotation.x;
  19430. camera.rotation.y = this.rotation.y;
  19431. camera.rotation.z = this.rotation.z;
  19432. };
  19433. // Oculus events
  19434. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19435. var yaw = evt.alpha / 180 * Math.PI;
  19436. var pitch = evt.beta / 180 * Math.PI;
  19437. var roll = evt.gamma / 180 * Math.PI;
  19438. if (!this._offsetOrientation) {
  19439. this._offsetOrientation = {
  19440. yaw: yaw,
  19441. pitch: pitch,
  19442. roll: roll
  19443. };
  19444. return;
  19445. } else {
  19446. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19447. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19448. this.rotation.z += this._offsetOrientation.roll - roll;
  19449. this._offsetOrientation.yaw = yaw;
  19450. this._offsetOrientation.pitch = pitch;
  19451. this._offsetOrientation.roll = roll;
  19452. }
  19453. };
  19454. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19455. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19456. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19457. };
  19458. OculusCamera.prototype.detachControl = function (element) {
  19459. _super.prototype.detachControl.call(this, element);
  19460. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19461. };
  19462. return OculusCamera;
  19463. })(BABYLON.FreeCamera);
  19464. BABYLON.OculusCamera = OculusCamera;
  19465. })(BABYLON || (BABYLON = {}));
  19466. //# sourceMappingURL=babylon.oculusCamera.js.map
  19467. var BABYLON;
  19468. (function (BABYLON) {
  19469. var OculusRiftDevKit2013_Metric = {
  19470. HResolution: 1280,
  19471. VResolution: 800,
  19472. HScreenSize: 0.149759993,
  19473. VScreenSize: 0.0935999975,
  19474. VScreenCenter: 0.0467999987,
  19475. EyeToScreenDistance: 0.0410000011,
  19476. LensSeparationDistance: 0.0635000020,
  19477. InterpupillaryDistance: 0.0640000030,
  19478. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19479. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19480. PostProcessScaleFactor: 1.714605507808412,
  19481. LensCenterOffset: 0.151976421
  19482. };
  19483. var _OculusInnerGamepadCamera = (function (_super) {
  19484. __extends(_OculusInnerGamepadCamera, _super);
  19485. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19486. _super.call(this, name, position, scene);
  19487. this._workMatrix = new BABYLON.Matrix();
  19488. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19489. // Constants
  19490. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19491. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19492. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19493. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19494. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19495. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19496. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19497. // Postprocess
  19498. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19499. }
  19500. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19501. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19502. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19503. return this._projectionMatrix;
  19504. };
  19505. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19506. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19507. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19508. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19509. // Computing target and final matrix
  19510. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19511. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19512. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19513. return this._viewMatrix;
  19514. };
  19515. return _OculusInnerGamepadCamera;
  19516. })(BABYLON.FreeCamera);
  19517. var OculusGamepadCamera = (function (_super) {
  19518. __extends(OculusGamepadCamera, _super);
  19519. function OculusGamepadCamera(name, position, scene) {
  19520. var _this = this;
  19521. _super.call(this, name, position, scene);
  19522. this.angularSensibility = 200;
  19523. this.moveSensibility = 75;
  19524. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19525. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19526. this.subCameras.push(this._leftCamera);
  19527. this.subCameras.push(this._rightCamera);
  19528. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19529. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19530. _this._onNewGameConnected(gamepad);
  19531. });
  19532. }
  19533. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19534. // Only the first gamepad can control the camera
  19535. if (gamepad.index === 0) {
  19536. this._gamepad = gamepad;
  19537. }
  19538. };
  19539. OculusGamepadCamera.prototype._update = function () {
  19540. this._leftCamera.position.copyFrom(this.position);
  19541. this._rightCamera.position.copyFrom(this.position);
  19542. this._updateCamera(this._leftCamera);
  19543. this._updateCamera(this._rightCamera);
  19544. _super.prototype._update.call(this);
  19545. };
  19546. OculusGamepadCamera.prototype._checkInputs = function () {
  19547. if (!this._gamepad) {
  19548. return;
  19549. }
  19550. var LSValues = this._gamepad.leftStick;
  19551. var normalizedLX = LSValues.x / this.moveSensibility;
  19552. var normalizedLY = LSValues.y / this.moveSensibility;
  19553. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19554. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19555. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19556. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19557. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19558. };
  19559. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19560. camera.minZ = this.minZ;
  19561. camera.maxZ = this.maxZ;
  19562. camera.rotation.x = this.rotation.x;
  19563. camera.rotation.y = this.rotation.y;
  19564. camera.rotation.z = this.rotation.z;
  19565. };
  19566. // Oculus events
  19567. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19568. var yaw = evt.alpha / 180 * Math.PI;
  19569. var pitch = evt.beta / 180 * Math.PI;
  19570. var roll = evt.gamma / 180 * Math.PI;
  19571. if (!this._offsetOrientation) {
  19572. this._offsetOrientation = {
  19573. yaw: yaw,
  19574. pitch: pitch,
  19575. roll: roll
  19576. };
  19577. return;
  19578. } else {
  19579. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19580. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19581. this.rotation.z += this._offsetOrientation.roll - roll;
  19582. this._offsetOrientation.yaw = yaw;
  19583. this._offsetOrientation.pitch = pitch;
  19584. this._offsetOrientation.roll = roll;
  19585. }
  19586. };
  19587. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19588. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19589. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19590. };
  19591. OculusGamepadCamera.prototype.detachControl = function (element) {
  19592. _super.prototype.detachControl.call(this, element);
  19593. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19594. };
  19595. OculusGamepadCamera.prototype.dispose = function () {
  19596. this._gamepads.dispose();
  19597. _super.prototype.dispose.call(this);
  19598. };
  19599. return OculusGamepadCamera;
  19600. })(BABYLON.FreeCamera);
  19601. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19602. })(BABYLON || (BABYLON = {}));
  19603. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19604. var BABYLON;
  19605. (function (BABYLON) {
  19606. // We're mainly based on the logic defined into the FreeCamera code
  19607. var VirtualJoysticksCamera = (function (_super) {
  19608. __extends(VirtualJoysticksCamera, _super);
  19609. function VirtualJoysticksCamera(name, position, scene) {
  19610. _super.call(this, name, position, scene);
  19611. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19612. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19613. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19614. this._leftjoystick.setJoystickSensibility(0.15);
  19615. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19616. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19617. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19618. this._rightjoystick.reverseUpDown = true;
  19619. this._rightjoystick.setJoystickSensibility(0.05);
  19620. this._rightjoystick.setJoystickColor("yellow");
  19621. }
  19622. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19623. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19624. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19625. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19626. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19627. if (!this._leftjoystick.pressed) {
  19628. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19629. }
  19630. if (!this._rightjoystick.pressed) {
  19631. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19632. }
  19633. };
  19634. VirtualJoysticksCamera.prototype.dispose = function () {
  19635. this._leftjoystick.releaseCanvas();
  19636. _super.prototype.dispose.call(this);
  19637. };
  19638. return VirtualJoysticksCamera;
  19639. })(BABYLON.FreeCamera);
  19640. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19641. })(BABYLON || (BABYLON = {}));
  19642. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19643. var BABYLON;
  19644. (function (BABYLON) {
  19645. var ShaderMaterial = (function (_super) {
  19646. __extends(ShaderMaterial, _super);
  19647. function ShaderMaterial(name, scene, shaderPath, options) {
  19648. _super.call(this, name, scene);
  19649. this._textures = new Array();
  19650. this._floats = new Array();
  19651. this._floatsArrays = {};
  19652. this._colors3 = new Array();
  19653. this._colors4 = new Array();
  19654. this._vectors2 = new Array();
  19655. this._vectors3 = new Array();
  19656. this._matrices = new Array();
  19657. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19658. this._shaderPath = shaderPath;
  19659. options.needAlphaBlending = options.needAlphaBlending || false;
  19660. options.needAlphaTesting = options.needAlphaTesting || false;
  19661. options.attributes = options.attributes || ["position", "normal", "uv"];
  19662. options.uniforms = options.uniforms || ["worldViewProjection"];
  19663. options.samplers = options.samplers || [];
  19664. this._options = options;
  19665. }
  19666. ShaderMaterial.prototype.needAlphaBlending = function () {
  19667. return this._options.needAlphaBlending;
  19668. };
  19669. ShaderMaterial.prototype.needAlphaTesting = function () {
  19670. return this._options.needAlphaTesting;
  19671. };
  19672. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19673. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19674. this._options.uniforms.push(uniformName);
  19675. }
  19676. };
  19677. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19678. if (this._options.samplers.indexOf(name) === -1) {
  19679. this._options.samplers.push(name);
  19680. }
  19681. this._textures[name] = texture;
  19682. return this;
  19683. };
  19684. ShaderMaterial.prototype.setFloat = function (name, value) {
  19685. this._checkUniform(name);
  19686. this._floats[name] = value;
  19687. return this;
  19688. };
  19689. ShaderMaterial.prototype.setFloats = function (name, value) {
  19690. this._checkUniform(name);
  19691. this._floatsArrays[name] = value;
  19692. return this;
  19693. };
  19694. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19695. this._checkUniform(name);
  19696. this._colors3[name] = value;
  19697. return this;
  19698. };
  19699. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19700. this._checkUniform(name);
  19701. this._colors4[name] = value;
  19702. return this;
  19703. };
  19704. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19705. this._checkUniform(name);
  19706. this._vectors2[name] = value;
  19707. return this;
  19708. };
  19709. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19710. this._checkUniform(name);
  19711. this._vectors3[name] = value;
  19712. return this;
  19713. };
  19714. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19715. this._checkUniform(name);
  19716. this._matrices[name] = value;
  19717. return this;
  19718. };
  19719. ShaderMaterial.prototype.isReady = function () {
  19720. var scene = this.getScene();
  19721. var engine = scene.getEngine();
  19722. if (!this.checkReadyOnEveryCall) {
  19723. if (this._renderId === scene.getRenderId()) {
  19724. return true;
  19725. }
  19726. }
  19727. var previousEffect = this._effect;
  19728. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19729. if (!this._effect.isReady()) {
  19730. return false;
  19731. }
  19732. if (previousEffect !== this._effect) {
  19733. scene.resetCachedMaterial();
  19734. }
  19735. this._renderId = scene.getRenderId();
  19736. return true;
  19737. };
  19738. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19739. var scene = this.getScene();
  19740. if (this._options.uniforms.indexOf("world") !== -1) {
  19741. this._effect.setMatrix("world", world);
  19742. }
  19743. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19744. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19745. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19746. }
  19747. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19748. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19749. }
  19750. };
  19751. ShaderMaterial.prototype.bind = function (world) {
  19752. // Std values
  19753. this.bindOnlyWorldMatrix(world);
  19754. if (this.getScene().getCachedMaterial() !== this) {
  19755. if (this._options.uniforms.indexOf("view") !== -1) {
  19756. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19757. }
  19758. if (this._options.uniforms.indexOf("projection") !== -1) {
  19759. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19760. }
  19761. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19762. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19763. }
  19764. for (var name in this._textures) {
  19765. this._effect.setTexture(name, this._textures[name]);
  19766. }
  19767. for (name in this._floats) {
  19768. this._effect.setFloat(name, this._floats[name]);
  19769. }
  19770. for (name in this._floatsArrays) {
  19771. this._effect.setArray(name, this._floatsArrays[name]);
  19772. }
  19773. for (name in this._colors3) {
  19774. this._effect.setColor3(name, this._colors3[name]);
  19775. }
  19776. for (name in this._colors4) {
  19777. var color = this._colors4[name];
  19778. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  19779. }
  19780. for (name in this._vectors2) {
  19781. this._effect.setVector2(name, this._vectors2[name]);
  19782. }
  19783. for (name in this._vectors3) {
  19784. this._effect.setVector3(name, this._vectors3[name]);
  19785. }
  19786. for (name in this._matrices) {
  19787. this._effect.setMatrix(name, this._matrices[name]);
  19788. }
  19789. }
  19790. _super.prototype.bind.call(this, world, null);
  19791. };
  19792. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  19793. for (var name in this._textures) {
  19794. this._textures[name].dispose();
  19795. }
  19796. this._textures = [];
  19797. _super.prototype.dispose.call(this, forceDisposeEffect);
  19798. };
  19799. return ShaderMaterial;
  19800. })(BABYLON.Material);
  19801. BABYLON.ShaderMaterial = ShaderMaterial;
  19802. })(BABYLON || (BABYLON = {}));
  19803. //# sourceMappingURL=babylon.shaderMaterial.js.map
  19804. var BABYLON;
  19805. (function (BABYLON) {
  19806. var VertexData = (function () {
  19807. function VertexData() {
  19808. }
  19809. VertexData.prototype.set = function (data, kind) {
  19810. switch (kind) {
  19811. case BABYLON.VertexBuffer.PositionKind:
  19812. this.positions = data;
  19813. break;
  19814. case BABYLON.VertexBuffer.NormalKind:
  19815. this.normals = data;
  19816. break;
  19817. case BABYLON.VertexBuffer.UVKind:
  19818. this.uvs = data;
  19819. break;
  19820. case BABYLON.VertexBuffer.UV2Kind:
  19821. this.uv2s = data;
  19822. break;
  19823. case BABYLON.VertexBuffer.ColorKind:
  19824. this.colors = data;
  19825. break;
  19826. case BABYLON.VertexBuffer.MatricesIndicesKind:
  19827. this.matricesIndices = data;
  19828. break;
  19829. case BABYLON.VertexBuffer.MatricesWeightsKind:
  19830. this.matricesWeights = data;
  19831. break;
  19832. }
  19833. };
  19834. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  19835. this._applyTo(mesh, updatable);
  19836. };
  19837. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  19838. this._applyTo(geometry, updatable);
  19839. };
  19840. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  19841. this._update(mesh);
  19842. };
  19843. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  19844. this._update(geometry);
  19845. };
  19846. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  19847. if (this.positions) {
  19848. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  19849. }
  19850. if (this.normals) {
  19851. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  19852. }
  19853. if (this.uvs) {
  19854. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  19855. }
  19856. if (this.uv2s) {
  19857. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  19858. }
  19859. if (this.colors) {
  19860. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  19861. }
  19862. if (this.matricesIndices) {
  19863. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  19864. }
  19865. if (this.matricesWeights) {
  19866. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  19867. }
  19868. if (this.indices) {
  19869. meshOrGeometry.setIndices(this.indices);
  19870. }
  19871. };
  19872. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  19873. if (this.positions) {
  19874. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  19875. }
  19876. if (this.normals) {
  19877. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  19878. }
  19879. if (this.uvs) {
  19880. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  19881. }
  19882. if (this.uv2s) {
  19883. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  19884. }
  19885. if (this.colors) {
  19886. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  19887. }
  19888. if (this.matricesIndices) {
  19889. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  19890. }
  19891. if (this.matricesWeights) {
  19892. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  19893. }
  19894. if (this.indices) {
  19895. meshOrGeometry.setIndices(this.indices);
  19896. }
  19897. };
  19898. VertexData.prototype.transform = function (matrix) {
  19899. var transformed = BABYLON.Vector3.Zero();
  19900. if (this.positions) {
  19901. var position = BABYLON.Vector3.Zero();
  19902. for (var index = 0; index < this.positions.length; index += 3) {
  19903. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  19904. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  19905. this.positions[index] = transformed.x;
  19906. this.positions[index + 1] = transformed.y;
  19907. this.positions[index + 2] = transformed.z;
  19908. }
  19909. }
  19910. if (this.normals) {
  19911. var normal = BABYLON.Vector3.Zero();
  19912. for (index = 0; index < this.normals.length; index += 3) {
  19913. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  19914. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  19915. this.normals[index] = transformed.x;
  19916. this.normals[index + 1] = transformed.y;
  19917. this.normals[index + 2] = transformed.z;
  19918. }
  19919. }
  19920. };
  19921. VertexData.prototype.merge = function (other) {
  19922. if (other.indices) {
  19923. if (!this.indices) {
  19924. this.indices = [];
  19925. }
  19926. var offset = this.positions ? this.positions.length / 3 : 0;
  19927. for (var index = 0; index < other.indices.length; index++) {
  19928. this.indices.push(other.indices[index] + offset);
  19929. }
  19930. }
  19931. if (other.positions) {
  19932. if (!this.positions) {
  19933. this.positions = [];
  19934. }
  19935. for (index = 0; index < other.positions.length; index++) {
  19936. this.positions.push(other.positions[index]);
  19937. }
  19938. }
  19939. if (other.normals) {
  19940. if (!this.normals) {
  19941. this.normals = [];
  19942. }
  19943. for (index = 0; index < other.normals.length; index++) {
  19944. this.normals.push(other.normals[index]);
  19945. }
  19946. }
  19947. if (other.uvs) {
  19948. if (!this.uvs) {
  19949. this.uvs = [];
  19950. }
  19951. for (index = 0; index < other.uvs.length; index++) {
  19952. this.uvs.push(other.uvs[index]);
  19953. }
  19954. }
  19955. if (other.uv2s) {
  19956. if (!this.uv2s) {
  19957. this.uv2s = [];
  19958. }
  19959. for (index = 0; index < other.uv2s.length; index++) {
  19960. this.uv2s.push(other.uv2s[index]);
  19961. }
  19962. }
  19963. if (other.matricesIndices) {
  19964. if (!this.matricesIndices) {
  19965. this.matricesIndices = [];
  19966. }
  19967. for (index = 0; index < other.matricesIndices.length; index++) {
  19968. this.matricesIndices.push(other.matricesIndices[index]);
  19969. }
  19970. }
  19971. if (other.matricesWeights) {
  19972. if (!this.matricesWeights) {
  19973. this.matricesWeights = [];
  19974. }
  19975. for (index = 0; index < other.matricesWeights.length; index++) {
  19976. this.matricesWeights.push(other.matricesWeights[index]);
  19977. }
  19978. }
  19979. if (other.colors) {
  19980. if (!this.colors) {
  19981. this.colors = [];
  19982. }
  19983. for (index = 0; index < other.colors.length; index++) {
  19984. this.colors.push(other.colors[index]);
  19985. }
  19986. }
  19987. };
  19988. // Statics
  19989. VertexData.ExtractFromMesh = function (mesh) {
  19990. return VertexData._ExtractFrom(mesh);
  19991. };
  19992. VertexData.ExtractFromGeometry = function (geometry) {
  19993. return VertexData._ExtractFrom(geometry);
  19994. };
  19995. VertexData._ExtractFrom = function (meshOrGeometry) {
  19996. var result = new BABYLON.VertexData();
  19997. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  19998. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19999. }
  20000. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20001. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20002. }
  20003. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20004. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20005. }
  20006. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20007. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20008. }
  20009. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20010. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20011. }
  20012. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20013. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20014. }
  20015. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20016. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20017. }
  20018. result.indices = meshOrGeometry.getIndices();
  20019. return result;
  20020. };
  20021. VertexData.CreateBox = function (size) {
  20022. var normalsSource = [
  20023. new BABYLON.Vector3(0, 0, 1),
  20024. new BABYLON.Vector3(0, 0, -1),
  20025. new BABYLON.Vector3(1, 0, 0),
  20026. new BABYLON.Vector3(-1, 0, 0),
  20027. new BABYLON.Vector3(0, 1, 0),
  20028. new BABYLON.Vector3(0, -1, 0)
  20029. ];
  20030. var indices = [];
  20031. var positions = [];
  20032. var normals = [];
  20033. var uvs = [];
  20034. size = size || 1;
  20035. for (var index = 0; index < normalsSource.length; index++) {
  20036. var normal = normalsSource[index];
  20037. // Get two vectors perpendicular to the face normal and to each other.
  20038. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20039. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20040. // Six indices (two triangles) per face.
  20041. var verticesLength = positions.length / 3;
  20042. indices.push(verticesLength);
  20043. indices.push(verticesLength + 1);
  20044. indices.push(verticesLength + 2);
  20045. indices.push(verticesLength);
  20046. indices.push(verticesLength + 2);
  20047. indices.push(verticesLength + 3);
  20048. // Four vertices per face.
  20049. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20050. positions.push(vertex.x, vertex.y, vertex.z);
  20051. normals.push(normal.x, normal.y, normal.z);
  20052. uvs.push(1.0, 1.0);
  20053. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20054. positions.push(vertex.x, vertex.y, vertex.z);
  20055. normals.push(normal.x, normal.y, normal.z);
  20056. uvs.push(0.0, 1.0);
  20057. vertex = normal.add(side1).add(side2).scale(size / 2);
  20058. positions.push(vertex.x, vertex.y, vertex.z);
  20059. normals.push(normal.x, normal.y, normal.z);
  20060. uvs.push(0.0, 0.0);
  20061. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20062. positions.push(vertex.x, vertex.y, vertex.z);
  20063. normals.push(normal.x, normal.y, normal.z);
  20064. uvs.push(1.0, 0.0);
  20065. }
  20066. // Result
  20067. var vertexData = new BABYLON.VertexData();
  20068. vertexData.indices = indices;
  20069. vertexData.positions = positions;
  20070. vertexData.normals = normals;
  20071. vertexData.uvs = uvs;
  20072. return vertexData;
  20073. };
  20074. VertexData.CreateSphere = function (segments, diameter) {
  20075. segments = segments || 32;
  20076. diameter = diameter || 1;
  20077. var radius = diameter / 2;
  20078. var totalZRotationSteps = 2 + segments;
  20079. var totalYRotationSteps = 2 * totalZRotationSteps;
  20080. var indices = [];
  20081. var positions = [];
  20082. var normals = [];
  20083. var uvs = [];
  20084. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20085. var normalizedZ = zRotationStep / totalZRotationSteps;
  20086. var angleZ = (normalizedZ * Math.PI);
  20087. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20088. var normalizedY = yRotationStep / totalYRotationSteps;
  20089. var angleY = normalizedY * Math.PI * 2;
  20090. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20091. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20092. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20093. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20094. var vertex = complete.scale(radius);
  20095. var normal = BABYLON.Vector3.Normalize(vertex);
  20096. positions.push(vertex.x, vertex.y, vertex.z);
  20097. normals.push(normal.x, normal.y, normal.z);
  20098. uvs.push(normalizedZ, normalizedY);
  20099. }
  20100. if (zRotationStep > 0) {
  20101. var verticesCount = positions.length / 3;
  20102. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20103. indices.push((firstIndex));
  20104. indices.push((firstIndex + 1));
  20105. indices.push(firstIndex + totalYRotationSteps + 1);
  20106. indices.push((firstIndex + totalYRotationSteps + 1));
  20107. indices.push((firstIndex + 1));
  20108. indices.push((firstIndex + totalYRotationSteps + 2));
  20109. }
  20110. }
  20111. }
  20112. // Result
  20113. var vertexData = new BABYLON.VertexData();
  20114. vertexData.indices = indices;
  20115. vertexData.positions = positions;
  20116. vertexData.normals = normals;
  20117. vertexData.uvs = uvs;
  20118. return vertexData;
  20119. };
  20120. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20121. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  20122. var radiusTop = diameterTop / 2;
  20123. var radiusBottom = diameterBottom / 2;
  20124. var indices = [];
  20125. var positions = [];
  20126. var normals = [];
  20127. var uvs = [];
  20128. height = height || 1;
  20129. diameterTop = diameterTop || 0.5;
  20130. diameterBottom = diameterBottom || 1;
  20131. tessellation = tessellation || 16;
  20132. subdivisions = subdivisions || 1;
  20133. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20134. var getCircleVector = function (i) {
  20135. var angle = (i * 2.0 * Math.PI / tessellation);
  20136. var dx = Math.cos(angle);
  20137. var dz = Math.sin(angle);
  20138. return new BABYLON.Vector3(dx, 0, dz);
  20139. };
  20140. var createCylinderCap = function (isTop) {
  20141. var radius = isTop ? radiusTop : radiusBottom;
  20142. if (radius == 0) {
  20143. return;
  20144. }
  20145. var vbase = positions.length / 3;
  20146. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20147. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20148. if (!isTop) {
  20149. offset.scaleInPlace(-1);
  20150. textureScale.x = -textureScale.x;
  20151. }
  20152. for (i = 0; i < tessellation; i++) {
  20153. var circleVector = getCircleVector(i);
  20154. var position = circleVector.scale(radius).add(offset);
  20155. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20156. positions.push(position.x, position.y, position.z);
  20157. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20158. }
  20159. for (var i = 0; i < tessellation - 2; i++) {
  20160. if (!isTop) {
  20161. indices.push(vbase);
  20162. indices.push(vbase + (i + 2) % tessellation);
  20163. indices.push(vbase + (i + 1) % tessellation);
  20164. } else {
  20165. indices.push(vbase);
  20166. indices.push(vbase + (i + 1) % tessellation);
  20167. indices.push(vbase + (i + 2) % tessellation);
  20168. }
  20169. }
  20170. };
  20171. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20172. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20173. var stride = tessellation + 1;
  20174. for (var i = 0; i <= tessellation; i++) {
  20175. var circleVector = getCircleVector(i);
  20176. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20177. var position, radius = radiusBottom;
  20178. for (var s = 0; s <= subdivisions; s++) {
  20179. // Update variables
  20180. position = circleVector.scale(radius);
  20181. position.addInPlace(base.add(offset.scale(s)));
  20182. textureCoordinate.y += 1 / subdivisions;
  20183. radius += (radiusTop - radiusBottom) / subdivisions;
  20184. // Push in arrays
  20185. positions.push(position.x, position.y, position.z);
  20186. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20187. }
  20188. }
  20189. subdivisions += 1;
  20190. for (var s = 0; s < subdivisions - 1; s++) {
  20191. for (var i = 0; i <= tessellation; i++) {
  20192. indices.push(i * subdivisions + s);
  20193. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20194. indices.push(i * subdivisions + (s + 1));
  20195. indices.push(i * subdivisions + (s + 1));
  20196. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20197. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20198. }
  20199. }
  20200. // Create flat triangle fan caps to seal the top and bottom.
  20201. createCylinderCap(true);
  20202. createCylinderCap(false);
  20203. // Normals
  20204. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20205. // Result
  20206. var vertexData = new BABYLON.VertexData();
  20207. vertexData.indices = indices;
  20208. vertexData.positions = positions;
  20209. vertexData.normals = normals;
  20210. vertexData.uvs = uvs;
  20211. return vertexData;
  20212. };
  20213. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20214. var indices = [];
  20215. var positions = [];
  20216. var normals = [];
  20217. var uvs = [];
  20218. diameter = diameter || 1;
  20219. thickness = thickness || 0.5;
  20220. tessellation = tessellation || 16;
  20221. var stride = tessellation + 1;
  20222. for (var i = 0; i <= tessellation; i++) {
  20223. var u = i / tessellation;
  20224. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20225. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20226. for (var j = 0; j <= tessellation; j++) {
  20227. var v = 1 - j / tessellation;
  20228. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20229. var dx = Math.cos(innerAngle);
  20230. var dy = Math.sin(innerAngle);
  20231. // Create a vertex.
  20232. var normal = new BABYLON.Vector3(dx, dy, 0);
  20233. var position = normal.scale(thickness / 2);
  20234. var textureCoordinate = new BABYLON.Vector2(u, v);
  20235. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20236. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20237. positions.push(position.x, position.y, position.z);
  20238. normals.push(normal.x, normal.y, normal.z);
  20239. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20240. // And create indices for two triangles.
  20241. var nextI = (i + 1) % stride;
  20242. var nextJ = (j + 1) % stride;
  20243. indices.push(i * stride + j);
  20244. indices.push(i * stride + nextJ);
  20245. indices.push(nextI * stride + j);
  20246. indices.push(i * stride + nextJ);
  20247. indices.push(nextI * stride + nextJ);
  20248. indices.push(nextI * stride + j);
  20249. }
  20250. }
  20251. // Result
  20252. var vertexData = new BABYLON.VertexData();
  20253. vertexData.indices = indices;
  20254. vertexData.positions = positions;
  20255. vertexData.normals = normals;
  20256. vertexData.uvs = uvs;
  20257. return vertexData;
  20258. };
  20259. VertexData.CreateLines = function (points) {
  20260. var indices = [];
  20261. var positions = [];
  20262. for (var index = 0; index < points.length; index++) {
  20263. positions.push(points[index].x, points[index].y, points[index].z);
  20264. if (index > 0) {
  20265. indices.push(index - 1);
  20266. indices.push(index);
  20267. }
  20268. }
  20269. // Result
  20270. var vertexData = new BABYLON.VertexData();
  20271. vertexData.indices = indices;
  20272. vertexData.positions = positions;
  20273. return vertexData;
  20274. };
  20275. VertexData.CreateGround = function (width, height, subdivisions) {
  20276. var indices = [];
  20277. var positions = [];
  20278. var normals = [];
  20279. var uvs = [];
  20280. var row, col;
  20281. width = width || 1;
  20282. height = height || 1;
  20283. subdivisions = subdivisions || 1;
  20284. for (row = 0; row <= subdivisions; row++) {
  20285. for (col = 0; col <= subdivisions; col++) {
  20286. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20287. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20288. positions.push(position.x, position.y, position.z);
  20289. normals.push(normal.x, normal.y, normal.z);
  20290. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20291. }
  20292. }
  20293. for (row = 0; row < subdivisions; row++) {
  20294. for (col = 0; col < subdivisions; col++) {
  20295. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20296. indices.push(col + 1 + row * (subdivisions + 1));
  20297. indices.push(col + row * (subdivisions + 1));
  20298. indices.push(col + (row + 1) * (subdivisions + 1));
  20299. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20300. indices.push(col + row * (subdivisions + 1));
  20301. }
  20302. }
  20303. // Result
  20304. var vertexData = new BABYLON.VertexData();
  20305. vertexData.indices = indices;
  20306. vertexData.positions = positions;
  20307. vertexData.normals = normals;
  20308. vertexData.uvs = uvs;
  20309. return vertexData;
  20310. };
  20311. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20312. if (typeof subdivisions === "undefined") { subdivisions = { w: 1, h: 1 }; }
  20313. if (typeof precision === "undefined") { precision = { w: 1, h: 1 }; }
  20314. var indices = [];
  20315. var positions = [];
  20316. var normals = [];
  20317. var uvs = [];
  20318. var row, col, tileRow, tileCol;
  20319. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20320. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20321. precision.w = (precision.w < 1) ? 1 : precision.w;
  20322. precision.h = (precision.h < 1) ? 1 : precision.h;
  20323. var tileSize = {
  20324. 'w': (xmax - xmin) / subdivisions.w,
  20325. 'h': (zmax - zmin) / subdivisions.h
  20326. };
  20327. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20328. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20329. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20330. }
  20331. }
  20332. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20333. // Indices
  20334. var base = positions.length / 3;
  20335. var rowLength = precision.w + 1;
  20336. for (row = 0; row < precision.h; row++) {
  20337. for (col = 0; col < precision.w; col++) {
  20338. var square = [
  20339. base + col + row * rowLength,
  20340. base + (col + 1) + row * rowLength,
  20341. base + (col + 1) + (row + 1) * rowLength,
  20342. base + col + (row + 1) * rowLength
  20343. ];
  20344. indices.push(square[1]);
  20345. indices.push(square[2]);
  20346. indices.push(square[3]);
  20347. indices.push(square[0]);
  20348. indices.push(square[1]);
  20349. indices.push(square[3]);
  20350. }
  20351. }
  20352. // Position, normals and uvs
  20353. var position = BABYLON.Vector3.Zero();
  20354. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20355. for (row = 0; row <= precision.h; row++) {
  20356. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20357. for (col = 0; col <= precision.w; col++) {
  20358. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20359. position.y = 0;
  20360. positions.push(position.x, position.y, position.z);
  20361. normals.push(normal.x, normal.y, normal.z);
  20362. uvs.push(col / precision.w, row / precision.h);
  20363. }
  20364. }
  20365. }
  20366. // Result
  20367. var vertexData = new BABYLON.VertexData();
  20368. vertexData.indices = indices;
  20369. vertexData.positions = positions;
  20370. vertexData.normals = normals;
  20371. vertexData.uvs = uvs;
  20372. return vertexData;
  20373. };
  20374. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20375. var indices = [];
  20376. var positions = [];
  20377. var normals = [];
  20378. var uvs = [];
  20379. var row, col;
  20380. for (row = 0; row <= subdivisions; row++) {
  20381. for (col = 0; col <= subdivisions; col++) {
  20382. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20383. // Compute height
  20384. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20385. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20386. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20387. var r = buffer[pos] / 255.0;
  20388. var g = buffer[pos + 1] / 255.0;
  20389. var b = buffer[pos + 2] / 255.0;
  20390. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20391. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20392. // Add vertex
  20393. positions.push(position.x, position.y, position.z);
  20394. normals.push(0, 0, 0);
  20395. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20396. }
  20397. }
  20398. for (row = 0; row < subdivisions; row++) {
  20399. for (col = 0; col < subdivisions; col++) {
  20400. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20401. indices.push(col + 1 + row * (subdivisions + 1));
  20402. indices.push(col + row * (subdivisions + 1));
  20403. indices.push(col + (row + 1) * (subdivisions + 1));
  20404. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20405. indices.push(col + row * (subdivisions + 1));
  20406. }
  20407. }
  20408. // Normals
  20409. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20410. // Result
  20411. var vertexData = new BABYLON.VertexData();
  20412. vertexData.indices = indices;
  20413. vertexData.positions = positions;
  20414. vertexData.normals = normals;
  20415. vertexData.uvs = uvs;
  20416. return vertexData;
  20417. };
  20418. VertexData.CreatePlane = function (size) {
  20419. var indices = [];
  20420. var positions = [];
  20421. var normals = [];
  20422. var uvs = [];
  20423. size = size || 1;
  20424. // Vertices
  20425. var halfSize = size / 2.0;
  20426. positions.push(-halfSize, -halfSize, 0);
  20427. normals.push(0, 0, -1.0);
  20428. uvs.push(0.0, 0.0);
  20429. positions.push(halfSize, -halfSize, 0);
  20430. normals.push(0, 0, -1.0);
  20431. uvs.push(1.0, 0.0);
  20432. positions.push(halfSize, halfSize, 0);
  20433. normals.push(0, 0, -1.0);
  20434. uvs.push(1.0, 1.0);
  20435. positions.push(-halfSize, halfSize, 0);
  20436. normals.push(0, 0, -1.0);
  20437. uvs.push(0.0, 1.0);
  20438. // Indices
  20439. indices.push(0);
  20440. indices.push(1);
  20441. indices.push(2);
  20442. indices.push(0);
  20443. indices.push(2);
  20444. indices.push(3);
  20445. // Result
  20446. var vertexData = new BABYLON.VertexData();
  20447. vertexData.indices = indices;
  20448. vertexData.positions = positions;
  20449. vertexData.normals = normals;
  20450. vertexData.uvs = uvs;
  20451. return vertexData;
  20452. };
  20453. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20454. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20455. var indices = [];
  20456. var positions = [];
  20457. var normals = [];
  20458. var uvs = [];
  20459. radius = radius || 2;
  20460. tube = tube || 0.5;
  20461. radialSegments = radialSegments || 32;
  20462. tubularSegments = tubularSegments || 32;
  20463. p = p || 2;
  20464. q = q || 3;
  20465. // Helper
  20466. var getPos = function (angle) {
  20467. var cu = Math.cos(angle);
  20468. var su = Math.sin(angle);
  20469. var quOverP = q / p * angle;
  20470. var cs = Math.cos(quOverP);
  20471. var tx = radius * (2 + cs) * 0.5 * cu;
  20472. var ty = radius * (2 + cs) * su * 0.5;
  20473. var tz = radius * Math.sin(quOverP) * 0.5;
  20474. return new BABYLON.Vector3(tx, ty, tz);
  20475. };
  20476. for (var i = 0; i <= radialSegments; i++) {
  20477. var modI = i % radialSegments;
  20478. var u = modI / radialSegments * 2 * p * Math.PI;
  20479. var p1 = getPos(u);
  20480. var p2 = getPos(u + 0.01);
  20481. var tang = p2.subtract(p1);
  20482. var n = p2.add(p1);
  20483. var bitan = BABYLON.Vector3.Cross(tang, n);
  20484. n = BABYLON.Vector3.Cross(bitan, tang);
  20485. bitan.normalize();
  20486. n.normalize();
  20487. for (var j = 0; j < tubularSegments; j++) {
  20488. var modJ = j % tubularSegments;
  20489. var v = modJ / tubularSegments * 2 * Math.PI;
  20490. var cx = -tube * Math.cos(v);
  20491. var cy = tube * Math.sin(v);
  20492. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20493. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20494. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20495. uvs.push(i / radialSegments);
  20496. uvs.push(j / tubularSegments);
  20497. }
  20498. }
  20499. for (i = 0; i < radialSegments; i++) {
  20500. for (j = 0; j < tubularSegments; j++) {
  20501. var jNext = (j + 1) % tubularSegments;
  20502. var a = i * tubularSegments + j;
  20503. var b = (i + 1) * tubularSegments + j;
  20504. var c = (i + 1) * tubularSegments + jNext;
  20505. var d = i * tubularSegments + jNext;
  20506. indices.push(d);
  20507. indices.push(b);
  20508. indices.push(a);
  20509. indices.push(d);
  20510. indices.push(c);
  20511. indices.push(b);
  20512. }
  20513. }
  20514. // Normals
  20515. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20516. // Result
  20517. var vertexData = new BABYLON.VertexData();
  20518. vertexData.indices = indices;
  20519. vertexData.positions = positions;
  20520. vertexData.normals = normals;
  20521. vertexData.uvs = uvs;
  20522. return vertexData;
  20523. };
  20524. // Tools
  20525. VertexData.ComputeNormals = function (positions, indices, normals) {
  20526. var positionVectors = [];
  20527. var facesOfVertices = [];
  20528. var index;
  20529. for (index = 0; index < positions.length; index += 3) {
  20530. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20531. positionVectors.push(vector3);
  20532. facesOfVertices.push([]);
  20533. }
  20534. // Compute normals
  20535. var facesNormals = [];
  20536. for (index = 0; index < indices.length / 3; index++) {
  20537. var i1 = indices[index * 3];
  20538. var i2 = indices[index * 3 + 1];
  20539. var i3 = indices[index * 3 + 2];
  20540. var p1 = positionVectors[i1];
  20541. var p2 = positionVectors[i2];
  20542. var p3 = positionVectors[i3];
  20543. var p1p2 = p1.subtract(p2);
  20544. var p3p2 = p3.subtract(p2);
  20545. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20546. facesOfVertices[i1].push(index);
  20547. facesOfVertices[i2].push(index);
  20548. facesOfVertices[i3].push(index);
  20549. }
  20550. for (index = 0; index < positionVectors.length; index++) {
  20551. var faces = facesOfVertices[index];
  20552. var normal = BABYLON.Vector3.Zero();
  20553. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20554. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20555. }
  20556. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20557. normals[index * 3] = normal.x;
  20558. normals[index * 3 + 1] = normal.y;
  20559. normals[index * 3 + 2] = normal.z;
  20560. }
  20561. };
  20562. return VertexData;
  20563. })();
  20564. BABYLON.VertexData = VertexData;
  20565. })(BABYLON || (BABYLON = {}));
  20566. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20567. var BABYLON;
  20568. (function (BABYLON) {
  20569. var buildCamera = function (that, name) {
  20570. that._leftCamera.isIntermediate = true;
  20571. that.subCameras.push(that._leftCamera);
  20572. that.subCameras.push(that._rightCamera);
  20573. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20574. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20575. that._anaglyphPostProcess.onApply = function (effect) {
  20576. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20577. };
  20578. that._update();
  20579. };
  20580. var AnaglyphArcRotateCamera = (function (_super) {
  20581. __extends(AnaglyphArcRotateCamera, _super);
  20582. // ANY
  20583. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20584. _super.call(this, name, alpha, beta, radius, target, scene);
  20585. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20586. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20587. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20588. buildCamera(this, name);
  20589. }
  20590. AnaglyphArcRotateCamera.prototype._update = function () {
  20591. this._updateCamera(this._leftCamera);
  20592. this._updateCamera(this._rightCamera);
  20593. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20594. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20595. _super.prototype._update.call(this);
  20596. };
  20597. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20598. camera.beta = this.beta;
  20599. camera.radius = this.radius;
  20600. camera.minZ = this.minZ;
  20601. camera.maxZ = this.maxZ;
  20602. camera.fov = this.fov;
  20603. camera.target = this.target;
  20604. };
  20605. return AnaglyphArcRotateCamera;
  20606. })(BABYLON.ArcRotateCamera);
  20607. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20608. var AnaglyphFreeCamera = (function (_super) {
  20609. __extends(AnaglyphFreeCamera, _super);
  20610. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20611. _super.call(this, name, position, scene);
  20612. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20613. this._transformMatrix = new BABYLON.Matrix();
  20614. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20615. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20616. buildCamera(this, name);
  20617. }
  20618. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20619. var target = this.getTarget();
  20620. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20621. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20622. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20623. };
  20624. AnaglyphFreeCamera.prototype._update = function () {
  20625. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20626. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20627. this._updateCamera(this._leftCamera);
  20628. this._updateCamera(this._rightCamera);
  20629. _super.prototype._update.call(this);
  20630. };
  20631. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20632. camera.minZ = this.minZ;
  20633. camera.maxZ = this.maxZ;
  20634. camera.fov = this.fov;
  20635. camera.viewport = this.viewport;
  20636. camera.setTarget(this.getTarget());
  20637. };
  20638. return AnaglyphFreeCamera;
  20639. })(BABYLON.FreeCamera);
  20640. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20641. })(BABYLON || (BABYLON = {}));
  20642. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20643. var BABYLON;
  20644. (function (BABYLON) {
  20645. var AnaglyphPostProcess = (function (_super) {
  20646. __extends(AnaglyphPostProcess, _super);
  20647. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20648. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20649. }
  20650. return AnaglyphPostProcess;
  20651. })(BABYLON.PostProcess);
  20652. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20653. })(BABYLON || (BABYLON = {}));
  20654. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  20655. var BABYLON;
  20656. (function (BABYLON) {
  20657. var Tags = (function () {
  20658. function Tags() {
  20659. }
  20660. Tags.EnableFor = function (obj) {
  20661. obj._tags = obj._tags || {};
  20662. obj.hasTags = function () {
  20663. return Tags.HasTags(obj);
  20664. };
  20665. obj.addTags = function (tagsString) {
  20666. return Tags.AddTagsTo(obj, tagsString);
  20667. };
  20668. obj.removeTags = function (tagsString) {
  20669. return Tags.RemoveTagsFrom(obj, tagsString);
  20670. };
  20671. obj.matchesTagsQuery = function (tagsQuery) {
  20672. return Tags.MatchesQuery(obj, tagsQuery);
  20673. };
  20674. };
  20675. Tags.DisableFor = function (obj) {
  20676. delete obj._tags;
  20677. delete obj.hasTags;
  20678. delete obj.addTags;
  20679. delete obj.removeTags;
  20680. delete obj.matchesTagsQuery;
  20681. };
  20682. Tags.HasTags = function (obj) {
  20683. if (!obj._tags) {
  20684. return false;
  20685. }
  20686. return !BABYLON.Tools.IsEmpty(obj._tags);
  20687. };
  20688. Tags.GetTags = function (obj) {
  20689. if (!obj._tags) {
  20690. return null;
  20691. }
  20692. return obj._tags;
  20693. };
  20694. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20695. // a tag cannot start with '||', '&&', and '!'
  20696. // it cannot contain whitespaces
  20697. Tags.AddTagsTo = function (obj, tagsString) {
  20698. if (!tagsString) {
  20699. return;
  20700. }
  20701. var tags = tagsString.split(" ");
  20702. for (var t in tags) {
  20703. Tags._AddTagTo(obj, tags[t]);
  20704. }
  20705. };
  20706. Tags._AddTagTo = function (obj, tag) {
  20707. tag = tag.trim();
  20708. if (tag === "" || tag === "true" || tag === "false") {
  20709. return;
  20710. }
  20711. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20712. return;
  20713. }
  20714. Tags.EnableFor(obj);
  20715. obj._tags[tag] = true;
  20716. };
  20717. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20718. if (!Tags.HasTags(obj)) {
  20719. return;
  20720. }
  20721. var tags = tagsString.split(" ");
  20722. for (var t in tags) {
  20723. Tags._RemoveTagFrom(obj, tags[t]);
  20724. }
  20725. };
  20726. Tags._RemoveTagFrom = function (obj, tag) {
  20727. delete obj._tags[tag];
  20728. };
  20729. Tags.MatchesQuery = function (obj, tagsQuery) {
  20730. if (tagsQuery === undefined) {
  20731. return true;
  20732. }
  20733. if (tagsQuery === "") {
  20734. return Tags.HasTags(obj);
  20735. }
  20736. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) {
  20737. return Tags.HasTags(obj) && obj._tags[r];
  20738. });
  20739. };
  20740. return Tags;
  20741. })();
  20742. BABYLON.Tags = Tags;
  20743. })(BABYLON || (BABYLON = {}));
  20744. //# sourceMappingURL=babylon.tags.js.map
  20745. var BABYLON;
  20746. (function (BABYLON) {
  20747. (function (Internals) {
  20748. var AndOrNotEvaluator = (function () {
  20749. function AndOrNotEvaluator() {
  20750. }
  20751. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20752. if (!query.match(/\([^\(\)]*\)/g)) {
  20753. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20754. } else {
  20755. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20756. // remove parenthesis
  20757. r = r.slice(1, r.length - 1);
  20758. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20759. });
  20760. }
  20761. if (query === "true") {
  20762. return true;
  20763. }
  20764. if (query === "false") {
  20765. return false;
  20766. }
  20767. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20768. };
  20769. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20770. evaluateCallback = evaluateCallback || (function (r) {
  20771. return r === "true" ? true : false;
  20772. });
  20773. var result;
  20774. var or = parenthesisContent.split("||");
  20775. for (var i in or) {
  20776. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  20777. var and = ori.split("&&");
  20778. if (and.length > 1) {
  20779. for (var j = 0; j < and.length; ++j) {
  20780. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  20781. if (andj !== "true" && andj !== "false") {
  20782. if (andj[0] === "!") {
  20783. result = !evaluateCallback(andj.substring(1));
  20784. } else {
  20785. result = evaluateCallback(andj);
  20786. }
  20787. } else {
  20788. result = andj === "true" ? true : false;
  20789. }
  20790. if (!result) {
  20791. ori = "false";
  20792. break;
  20793. }
  20794. }
  20795. }
  20796. if (result || ori === "true") {
  20797. result = true;
  20798. break;
  20799. }
  20800. // result equals false (or undefined)
  20801. if (ori !== "true" && ori !== "false") {
  20802. if (ori[0] === "!") {
  20803. result = !evaluateCallback(ori.substring(1));
  20804. } else {
  20805. result = evaluateCallback(ori);
  20806. }
  20807. } else {
  20808. result = ori === "true" ? true : false;
  20809. }
  20810. }
  20811. // the whole parenthesis scope is replaced by 'true' or 'false'
  20812. return result ? "true" : "false";
  20813. };
  20814. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  20815. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  20816. // remove whitespaces
  20817. r = r.replace(/[\s]/g, function () {
  20818. return "";
  20819. });
  20820. return r.length % 2 ? "!" : "";
  20821. });
  20822. booleanString = booleanString.trim();
  20823. if (booleanString === "!true") {
  20824. booleanString = "false";
  20825. } else if (booleanString === "!false") {
  20826. booleanString = "true";
  20827. }
  20828. return booleanString;
  20829. };
  20830. return AndOrNotEvaluator;
  20831. })();
  20832. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  20833. })(BABYLON.Internals || (BABYLON.Internals = {}));
  20834. var Internals = BABYLON.Internals;
  20835. })(BABYLON || (BABYLON = {}));
  20836. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  20837. var BABYLON;
  20838. (function (BABYLON) {
  20839. var PostProcessRenderPass = (function () {
  20840. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  20841. this._enabled = true;
  20842. this._refCount = 0;
  20843. this._name = name;
  20844. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  20845. this.setRenderList(renderList);
  20846. this._renderTexture.onBeforeRender = beforeRender;
  20847. this._renderTexture.onAfterRender = afterRender;
  20848. this._scene = scene;
  20849. this._renderList = renderList;
  20850. }
  20851. // private
  20852. PostProcessRenderPass.prototype._incRefCount = function () {
  20853. if (this._refCount === 0) {
  20854. this._scene.customRenderTargets.push(this._renderTexture);
  20855. }
  20856. return ++this._refCount;
  20857. };
  20858. PostProcessRenderPass.prototype._decRefCount = function () {
  20859. this._refCount--;
  20860. if (this._refCount <= 0) {
  20861. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  20862. }
  20863. return this._refCount;
  20864. };
  20865. PostProcessRenderPass.prototype._update = function () {
  20866. this.setRenderList(this._renderList);
  20867. };
  20868. // public
  20869. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  20870. this._renderTexture.renderList = renderList;
  20871. };
  20872. PostProcessRenderPass.prototype.getRenderTexture = function () {
  20873. return this._renderTexture;
  20874. };
  20875. return PostProcessRenderPass;
  20876. })();
  20877. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  20878. })(BABYLON || (BABYLON = {}));
  20879. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  20880. var BABYLON;
  20881. (function (BABYLON) {
  20882. var PostProcessRenderEffect = (function () {
  20883. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  20884. this._engine = engine;
  20885. this._name = name;
  20886. this._singleInstance = singleInstance || true;
  20887. this._getPostProcess = getPostProcess;
  20888. this._cameras = [];
  20889. this._indicesForCamera = [];
  20890. this._postProcesses = {};
  20891. this._renderPasses = {};
  20892. this._renderEffectAsPasses = {};
  20893. }
  20894. PostProcessRenderEffect.prototype._update = function () {
  20895. for (var renderPassName in this._renderPasses) {
  20896. this._renderPasses[renderPassName]._update();
  20897. }
  20898. };
  20899. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  20900. this._renderPasses[renderPass._name] = renderPass;
  20901. this._linkParameters();
  20902. };
  20903. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  20904. delete this._renderPasses[renderPass._name];
  20905. this._linkParameters();
  20906. };
  20907. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  20908. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  20909. this._linkParameters();
  20910. };
  20911. PostProcessRenderEffect.prototype.getPass = function (passName) {
  20912. for (var renderPassName in this._renderPasses) {
  20913. if (renderPassName === passName) {
  20914. return this._renderPasses[passName];
  20915. }
  20916. }
  20917. };
  20918. PostProcessRenderEffect.prototype.emptyPasses = function () {
  20919. this._renderPasses = {};
  20920. this._linkParameters();
  20921. };
  20922. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  20923. var cameraKey;
  20924. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20925. for (var i = 0; i < _cam.length; i++) {
  20926. var camera = _cam[i];
  20927. var cameraName = camera.name;
  20928. if (this._singleInstance) {
  20929. cameraKey = 0;
  20930. } else {
  20931. cameraKey = cameraName;
  20932. }
  20933. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  20934. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  20935. if (!this._indicesForCamera[cameraName]) {
  20936. this._indicesForCamera[cameraName] = [];
  20937. }
  20938. this._indicesForCamera[cameraName].push(index);
  20939. if (this._cameras.indexOf(camera) === -1) {
  20940. this._cameras[cameraName] = camera;
  20941. }
  20942. for (var passName in this._renderPasses) {
  20943. this._renderPasses[passName]._incRefCount();
  20944. }
  20945. }
  20946. this._linkParameters();
  20947. };
  20948. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  20949. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20950. for (var i = 0; i < _cam.length; i++) {
  20951. var camera = _cam[i];
  20952. var cameraName = camera.name;
  20953. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20954. var index = this._cameras.indexOf(cameraName);
  20955. this._indicesForCamera.splice(index, 1);
  20956. this._cameras.splice(index, 1);
  20957. for (var passName in this._renderPasses) {
  20958. this._renderPasses[passName]._decRefCount();
  20959. }
  20960. }
  20961. };
  20962. PostProcessRenderEffect.prototype._enable = function (cameras) {
  20963. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20964. for (var i = 0; i < _cam.length; i++) {
  20965. var camera = _cam[i];
  20966. var cameraName = camera.name;
  20967. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  20968. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  20969. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  20970. }
  20971. }
  20972. for (var passName in this._renderPasses) {
  20973. this._renderPasses[passName]._incRefCount();
  20974. }
  20975. }
  20976. };
  20977. PostProcessRenderEffect.prototype._disable = function (cameras) {
  20978. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  20979. for (var i = 0; i < _cam.length; i++) {
  20980. var camera = _cam[i];
  20981. var cameraName = camera.Name;
  20982. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  20983. for (var passName in this._renderPasses) {
  20984. this._renderPasses[passName]._decRefCount();
  20985. }
  20986. }
  20987. };
  20988. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  20989. if (this._singleInstance) {
  20990. return this._postProcesses[0];
  20991. } else {
  20992. return this._postProcesses[camera.name];
  20993. }
  20994. };
  20995. PostProcessRenderEffect.prototype._linkParameters = function () {
  20996. var _this = this;
  20997. for (var index in this._postProcesses) {
  20998. if (this.applyParameters) {
  20999. this.applyParameters(this._postProcesses[index]);
  21000. }
  21001. this._postProcesses[index].onBeforeRender = function (effect) {
  21002. _this._linkTextures(effect);
  21003. };
  21004. }
  21005. };
  21006. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21007. for (var renderPassName in this._renderPasses) {
  21008. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21009. }
  21010. for (var renderEffectName in this._renderEffectAsPasses) {
  21011. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21012. }
  21013. };
  21014. return PostProcessRenderEffect;
  21015. })();
  21016. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21017. })(BABYLON || (BABYLON = {}));
  21018. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  21019. var BABYLON;
  21020. (function (BABYLON) {
  21021. var PostProcessRenderPipeline = (function () {
  21022. function PostProcessRenderPipeline(engine, name) {
  21023. this._engine = engine;
  21024. this._name = name;
  21025. this._renderEffects = {};
  21026. this._renderEffectsForIsolatedPass = {};
  21027. this._cameras = [];
  21028. }
  21029. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21030. this._renderEffects[renderEffect._name] = renderEffect;
  21031. };
  21032. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21033. var renderEffects = this._renderEffects[renderEffectName];
  21034. if (!renderEffects) {
  21035. return;
  21036. }
  21037. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21038. };
  21039. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21040. var renderEffects = this._renderEffects[renderEffectName];
  21041. if (!renderEffects) {
  21042. return;
  21043. }
  21044. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21045. };
  21046. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21047. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21048. var indicesToDelete = [];
  21049. for (var i = 0; i < _cam.length; i++) {
  21050. var camera = _cam[i];
  21051. var cameraName = camera.name;
  21052. if (this._cameras.indexOf(camera) === -1) {
  21053. this._cameras[cameraName] = camera;
  21054. } else if (unique) {
  21055. indicesToDelete.push(i);
  21056. }
  21057. }
  21058. for (var i = 0; i < indicesToDelete.length; i++) {
  21059. cameras.splice(indicesToDelete[i], 1);
  21060. }
  21061. for (var renderEffectName in this._renderEffects) {
  21062. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21063. }
  21064. };
  21065. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21066. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21067. for (var renderEffectName in this._renderEffects) {
  21068. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21069. }
  21070. for (var i = 0; i < _cam.length; i++) {
  21071. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21072. }
  21073. };
  21074. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21075. var _this = this;
  21076. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21077. var pass = null;
  21078. for (var renderEffectName in this._renderEffects) {
  21079. pass = this._renderEffects[renderEffectName].getPass(passName);
  21080. if (pass != null) {
  21081. break;
  21082. }
  21083. }
  21084. if (pass === null) {
  21085. return;
  21086. }
  21087. for (var renderEffectName in this._renderEffects) {
  21088. this._renderEffects[renderEffectName]._disable(_cam);
  21089. }
  21090. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21091. for (var i = 0; i < _cam.length; i++) {
  21092. var camera = _cam[i];
  21093. var cameraName = camera.name;
  21094. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21095. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21096. });
  21097. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21098. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21099. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21100. }
  21101. };
  21102. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21103. var _this = this;
  21104. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21105. for (var i = 0; i < _cam.length; i++) {
  21106. var camera = _cam[i];
  21107. var cameraName = camera.name;
  21108. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21109. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21110. });
  21111. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21112. }
  21113. for (var renderEffectName in this._renderEffects) {
  21114. this._renderEffects[renderEffectName]._enable(_cam);
  21115. }
  21116. };
  21117. PostProcessRenderPipeline.prototype._update = function () {
  21118. for (var renderEffectName in this._renderEffects) {
  21119. this._renderEffects[renderEffectName]._update();
  21120. }
  21121. for (var i = 0; i < this._cameras.length; i++) {
  21122. var cameraName = this._cameras[i].name;
  21123. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21124. this._renderEffectsForIsolatedPass[cameraName]._update();
  21125. }
  21126. }
  21127. };
  21128. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21129. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21130. return PostProcessRenderPipeline;
  21131. })();
  21132. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21133. })(BABYLON || (BABYLON = {}));
  21134. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  21135. var BABYLON;
  21136. (function (BABYLON) {
  21137. var PostProcessRenderPipelineManager = (function () {
  21138. function PostProcessRenderPipelineManager() {
  21139. this._renderPipelines = {};
  21140. }
  21141. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21142. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21143. };
  21144. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21145. var renderPipeline = this._renderPipelines[renderPipelineName];
  21146. if (!renderPipeline) {
  21147. return;
  21148. }
  21149. renderPipeline._attachCameras(cameras, unique);
  21150. };
  21151. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21152. var renderPipeline = this._renderPipelines[renderPipelineName];
  21153. if (!renderPipeline) {
  21154. return;
  21155. }
  21156. renderPipeline._detachCameras(cameras);
  21157. };
  21158. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21159. var renderPipeline = this._renderPipelines[renderPipelineName];
  21160. if (!renderPipeline) {
  21161. return;
  21162. }
  21163. renderPipeline._enableEffect(renderEffectName, cameras);
  21164. };
  21165. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21166. var renderPipeline = this._renderPipelines[renderPipelineName];
  21167. if (!renderPipeline) {
  21168. return;
  21169. }
  21170. renderPipeline._disableEffect(renderEffectName, cameras);
  21171. };
  21172. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21173. var renderPipeline = this._renderPipelines[renderPipelineName];
  21174. if (!renderPipeline) {
  21175. return;
  21176. }
  21177. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21178. };
  21179. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21180. var renderPipeline = this._renderPipelines[renderPipelineName];
  21181. if (!renderPipeline) {
  21182. return;
  21183. }
  21184. renderPipeline._disableDisplayOnlyPass(cameras);
  21185. };
  21186. PostProcessRenderPipelineManager.prototype.update = function () {
  21187. for (var renderPipelineName in this._renderPipelines) {
  21188. this._renderPipelines[renderPipelineName]._update();
  21189. }
  21190. };
  21191. return PostProcessRenderPipelineManager;
  21192. })();
  21193. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21194. })(BABYLON || (BABYLON = {}));
  21195. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21196. var BABYLON;
  21197. (function (BABYLON) {
  21198. var DisplayPassPostProcess = (function (_super) {
  21199. __extends(DisplayPassPostProcess, _super);
  21200. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21201. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21202. }
  21203. return DisplayPassPostProcess;
  21204. })(BABYLON.PostProcess);
  21205. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21206. })(BABYLON || (BABYLON = {}));
  21207. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. var BoundingBoxRenderer = (function () {
  21211. function BoundingBoxRenderer(scene) {
  21212. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21213. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21214. this.showBackLines = true;
  21215. this.renderList = new BABYLON.SmartArray(32);
  21216. this._scene = scene;
  21217. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21218. attributes: ["position"],
  21219. uniforms: ["worldViewProjection", "color"]
  21220. });
  21221. var engine = this._scene.getEngine();
  21222. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21223. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21224. 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]);
  21225. }
  21226. BoundingBoxRenderer.prototype.reset = function () {
  21227. this.renderList.reset();
  21228. };
  21229. BoundingBoxRenderer.prototype.render = function () {
  21230. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21231. return;
  21232. }
  21233. var engine = this._scene.getEngine();
  21234. engine.setDepthWrite(false);
  21235. this._colorShader._preBind();
  21236. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21237. var boundingBox = this.renderList.data[boundingBoxIndex];
  21238. var min = boundingBox.minimum;
  21239. var max = boundingBox.maximum;
  21240. var diff = max.subtract(min);
  21241. var median = min.add(diff.scale(0.5));
  21242. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21243. // VBOs
  21244. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21245. if (this.showBackLines) {
  21246. // Back
  21247. engine.setDepthFunctionToGreaterOrEqual();
  21248. this._scene.resetCachedMaterial();
  21249. this._colorShader.setColor4("color", this.backColor.toColor4());
  21250. this._colorShader.bind(worldMatrix);
  21251. // Draw order
  21252. engine.draw(false, 0, 24);
  21253. }
  21254. // Front
  21255. engine.setDepthFunctionToLess();
  21256. this._scene.resetCachedMaterial();
  21257. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21258. this._colorShader.bind(worldMatrix);
  21259. // Draw order
  21260. engine.draw(false, 0, 24);
  21261. }
  21262. this._colorShader.unbind();
  21263. engine.setDepthFunctionToLessOrEqual();
  21264. engine.setDepthWrite(true);
  21265. };
  21266. BoundingBoxRenderer.prototype.dispose = function () {
  21267. this._colorShader.dispose();
  21268. this._vb.dispose();
  21269. this._scene.getEngine()._releaseBuffer(this._ib);
  21270. };
  21271. return BoundingBoxRenderer;
  21272. })();
  21273. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21274. })(BABYLON || (BABYLON = {}));
  21275. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  21276. /**
  21277. * Based on jsTGALoader - Javascript loader for TGA file
  21278. * By Vincent Thibault
  21279. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21280. */
  21281. var BABYLON;
  21282. (function (BABYLON) {
  21283. (function (Internals) {
  21284. var TGATools = (function () {
  21285. function TGATools() {
  21286. }
  21287. TGATools.GetTGAHeader = function (data) {
  21288. var offset = 0;
  21289. var header = {
  21290. id_length: data[offset++],
  21291. colormap_type: data[offset++],
  21292. image_type: data[offset++],
  21293. colormap_index: data[offset++] | data[offset++] << 8,
  21294. colormap_length: data[offset++] | data[offset++] << 8,
  21295. colormap_size: data[offset++],
  21296. origin: [
  21297. data[offset++] | data[offset++] << 8,
  21298. data[offset++] | data[offset++] << 8
  21299. ],
  21300. width: data[offset++] | data[offset++] << 8,
  21301. height: data[offset++] | data[offset++] << 8,
  21302. pixel_size: data[offset++],
  21303. flags: data[offset++]
  21304. };
  21305. return header;
  21306. };
  21307. TGATools.UploadContent = function (gl, data) {
  21308. // Not enough data to contain header ?
  21309. if (data.length < 19) {
  21310. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21311. return;
  21312. }
  21313. // Read Header
  21314. var offset = 18;
  21315. var header = TGATools.GetTGAHeader(data);
  21316. // Assume it's a valid Targa file.
  21317. if (header.id_length + offset > data.length) {
  21318. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21319. return;
  21320. }
  21321. // Skip not needed data
  21322. offset += header.id_length;
  21323. var use_rle = false;
  21324. var use_pal = false;
  21325. var use_rgb = false;
  21326. var use_grey = false;
  21327. switch (header.image_type) {
  21328. case TGATools._TYPE_RLE_INDEXED:
  21329. use_rle = true;
  21330. case TGATools._TYPE_INDEXED:
  21331. use_pal = true;
  21332. break;
  21333. case TGATools._TYPE_RLE_RGB:
  21334. use_rle = true;
  21335. case TGATools._TYPE_RGB:
  21336. use_rgb = true;
  21337. break;
  21338. case TGATools._TYPE_RLE_GREY:
  21339. use_rle = true;
  21340. case TGATools._TYPE_GREY:
  21341. use_grey = true;
  21342. break;
  21343. }
  21344. var pixel_data;
  21345. var numAlphaBits = header.flags & 0xf;
  21346. var pixel_size = header.pixel_size >> 3;
  21347. var pixel_total = header.width * header.height * pixel_size;
  21348. // Read palettes
  21349. var palettes;
  21350. if (use_pal) {
  21351. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21352. }
  21353. // Read LRE
  21354. if (use_rle) {
  21355. pixel_data = new Uint8Array(pixel_total);
  21356. var c, count, i;
  21357. var localOffset = 0;
  21358. var pixels = new Uint8Array(pixel_size);
  21359. while (offset < pixel_total && localOffset < pixel_total) {
  21360. c = data[offset++];
  21361. count = (c & 0x7f) + 1;
  21362. // RLE pixels
  21363. if (c & 0x80) {
  21364. for (i = 0; i < pixel_size; ++i) {
  21365. pixels[i] = data[offset++];
  21366. }
  21367. for (i = 0; i < count; ++i) {
  21368. pixel_data.set(pixels, localOffset + i * pixel_size);
  21369. }
  21370. localOffset += pixel_size * count;
  21371. } else {
  21372. count *= pixel_size;
  21373. for (i = 0; i < count; ++i) {
  21374. pixel_data[localOffset + i] = data[offset++];
  21375. }
  21376. localOffset += count;
  21377. }
  21378. }
  21379. } else {
  21380. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21381. }
  21382. // Load to texture
  21383. var x_start, y_start, x_step, y_step, y_end, x_end;
  21384. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21385. default:
  21386. case TGATools._ORIGIN_UL:
  21387. x_start = 0;
  21388. x_step = 1;
  21389. x_end = header.width;
  21390. y_start = 0;
  21391. y_step = 1;
  21392. y_end = header.height;
  21393. break;
  21394. case TGATools._ORIGIN_BL:
  21395. x_start = 0;
  21396. x_step = 1;
  21397. x_end = header.width;
  21398. y_start = header.height - 1;
  21399. y_step = -1;
  21400. y_end = -1;
  21401. break;
  21402. case TGATools._ORIGIN_UR:
  21403. x_start = header.width - 1;
  21404. x_step = -1;
  21405. x_end = -1;
  21406. y_start = 0;
  21407. y_step = 1;
  21408. y_end = header.height;
  21409. break;
  21410. case TGATools._ORIGIN_BR:
  21411. x_start = header.width - 1;
  21412. x_step = -1;
  21413. x_end = -1;
  21414. y_start = header.height - 1;
  21415. y_step = -1;
  21416. y_end = -1;
  21417. break;
  21418. }
  21419. // Load the specify method
  21420. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21421. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21422. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21423. };
  21424. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21425. var image = pixel_data, colormap = palettes;
  21426. var width = header.width, height = header.height;
  21427. var color, i = 0, x, y;
  21428. var imageData = new Uint8Array(width * height * 4);
  21429. for (y = y_start; y !== y_end; y += y_step) {
  21430. for (x = x_start; x !== x_end; x += x_step, i++) {
  21431. color = image[i];
  21432. imageData[(x + width * y) * 4 + 3] = 255;
  21433. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21434. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21435. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21436. }
  21437. }
  21438. return imageData;
  21439. };
  21440. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21441. var image = pixel_data;
  21442. var width = header.width, height = header.height;
  21443. var color, i = 0, x, y;
  21444. var imageData = new Uint8Array(width * height * 4);
  21445. for (y = y_start; y !== y_end; y += y_step) {
  21446. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21447. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21448. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21449. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21450. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21451. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21452. }
  21453. }
  21454. return imageData;
  21455. };
  21456. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21457. var image = pixel_data;
  21458. var width = header.width, height = header.height;
  21459. var i = 0, x, y;
  21460. var imageData = new Uint8Array(width * height * 4);
  21461. for (y = y_start; y !== y_end; y += y_step) {
  21462. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21463. imageData[(x + width * y) * 4 + 3] = 255;
  21464. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21465. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21466. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21467. }
  21468. }
  21469. return imageData;
  21470. };
  21471. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21472. var image = pixel_data;
  21473. var width = header.width, height = header.height;
  21474. var i = 0, x, y;
  21475. var imageData = new Uint8Array(width * height * 4);
  21476. for (y = y_start; y !== y_end; y += y_step) {
  21477. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21478. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21479. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21480. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21481. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21482. }
  21483. }
  21484. return imageData;
  21485. };
  21486. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21487. var image = pixel_data;
  21488. var width = header.width, height = header.height;
  21489. var color, i = 0, x, y;
  21490. var imageData = new Uint8Array(width * height * 4);
  21491. for (y = y_start; y !== y_end; y += y_step) {
  21492. for (x = x_start; x !== x_end; x += x_step, i++) {
  21493. color = image[i];
  21494. imageData[(x + width * y) * 4 + 0] = color;
  21495. imageData[(x + width * y) * 4 + 1] = color;
  21496. imageData[(x + width * y) * 4 + 2] = color;
  21497. imageData[(x + width * y) * 4 + 3] = 255;
  21498. }
  21499. }
  21500. return imageData;
  21501. };
  21502. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21503. var image = pixel_data;
  21504. var width = header.width, height = header.height;
  21505. var i = 0, x, y;
  21506. var imageData = new Uint8Array(width * height * 4);
  21507. for (y = y_start; y !== y_end; y += y_step) {
  21508. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21509. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21510. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21511. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21512. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21513. }
  21514. }
  21515. return imageData;
  21516. };
  21517. TGATools._TYPE_NO_DATA = 0;
  21518. TGATools._TYPE_INDEXED = 1;
  21519. TGATools._TYPE_RGB = 2;
  21520. TGATools._TYPE_GREY = 3;
  21521. TGATools._TYPE_RLE_INDEXED = 9;
  21522. TGATools._TYPE_RLE_RGB = 10;
  21523. TGATools._TYPE_RLE_GREY = 11;
  21524. TGATools._ORIGIN_MASK = 0x30;
  21525. TGATools._ORIGIN_SHIFT = 0x04;
  21526. TGATools._ORIGIN_BL = 0x00;
  21527. TGATools._ORIGIN_BR = 0x01;
  21528. TGATools._ORIGIN_UL = 0x02;
  21529. TGATools._ORIGIN_UR = 0x03;
  21530. return TGATools;
  21531. })();
  21532. Internals.TGATools = TGATools;
  21533. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21534. var Internals = BABYLON.Internals;
  21535. })(BABYLON || (BABYLON = {}));
  21536. //# sourceMappingURL=babylon.tools.tga.js.map
  21537. var BABYLON;
  21538. (function (BABYLON) {
  21539. (function (Internals) {
  21540. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21541. // All values and structures referenced from:
  21542. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21543. var DDS_MAGIC = 0x20534444;
  21544. 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;
  21545. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21546. 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;
  21547. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21548. function FourCCToInt32(value) {
  21549. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21550. }
  21551. function Int32ToFourCC(value) {
  21552. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21553. }
  21554. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21555. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21556. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21557. var headerLengthInt = 31;
  21558. // Offsets into the header array
  21559. var off_magic = 0;
  21560. var off_size = 1;
  21561. var off_flags = 2;
  21562. var off_height = 3;
  21563. var off_width = 4;
  21564. var off_mipmapCount = 7;
  21565. var off_pfFlags = 20;
  21566. var off_pfFourCC = 21;
  21567. var off_RGBbpp = 22;
  21568. var off_RMask = 23;
  21569. var off_GMask = 24;
  21570. var off_BMask = 25;
  21571. var off_AMask = 26;
  21572. var off_caps1 = 27;
  21573. var off_caps2 = 28;
  21574. ;
  21575. var DDSTools = (function () {
  21576. function DDSTools() {
  21577. }
  21578. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21579. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21580. var mipmapCount = 1;
  21581. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21582. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21583. }
  21584. return {
  21585. width: header[off_width],
  21586. height: header[off_height],
  21587. mipmapCount: mipmapCount,
  21588. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21589. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21590. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21591. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21592. };
  21593. };
  21594. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21595. var byteArray = new Uint8Array(dataLength);
  21596. var srcData = new Uint8Array(arrayBuffer);
  21597. var index = 0;
  21598. for (var y = height - 1; y >= 0; y--) {
  21599. for (var x = 0; x < width; x++) {
  21600. var srcPos = dataOffset + (x + y * width) * 4;
  21601. byteArray[index + 2] = srcData[srcPos];
  21602. byteArray[index + 1] = srcData[srcPos + 1];
  21603. byteArray[index] = srcData[srcPos + 2];
  21604. byteArray[index + 3] = srcData[srcPos + 3];
  21605. index += 4;
  21606. }
  21607. }
  21608. return byteArray;
  21609. };
  21610. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21611. var byteArray = new Uint8Array(dataLength);
  21612. var srcData = new Uint8Array(arrayBuffer);
  21613. var index = 0;
  21614. for (var y = height - 1; y >= 0; y--) {
  21615. for (var x = 0; x < width; x++) {
  21616. var srcPos = dataOffset + (x + y * width) * 3;
  21617. byteArray[index + 2] = srcData[srcPos];
  21618. byteArray[index + 1] = srcData[srcPos + 1];
  21619. byteArray[index] = srcData[srcPos + 2];
  21620. index += 3;
  21621. }
  21622. }
  21623. return byteArray;
  21624. };
  21625. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21626. var byteArray = new Uint8Array(dataLength);
  21627. var srcData = new Uint8Array(arrayBuffer);
  21628. var index = 0;
  21629. for (var y = height - 1; y >= 0; y--) {
  21630. for (var x = 0; x < width; x++) {
  21631. var srcPos = dataOffset + (x + y * width);
  21632. byteArray[index] = srcData[srcPos];
  21633. index++;
  21634. }
  21635. }
  21636. return byteArray;
  21637. };
  21638. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21639. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21640. if (header[off_magic] != DDS_MAGIC) {
  21641. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21642. return;
  21643. }
  21644. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21645. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21646. return;
  21647. }
  21648. if (info.isFourCC) {
  21649. fourCC = header[off_pfFourCC];
  21650. switch (fourCC) {
  21651. case FOURCC_DXT1:
  21652. blockBytes = 8;
  21653. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21654. break;
  21655. case FOURCC_DXT3:
  21656. blockBytes = 16;
  21657. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21658. break;
  21659. case FOURCC_DXT5:
  21660. blockBytes = 16;
  21661. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21662. break;
  21663. default:
  21664. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21665. return;
  21666. }
  21667. }
  21668. mipmapCount = 1;
  21669. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21670. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21671. }
  21672. var bpp = header[off_RGBbpp];
  21673. for (var face = 0; face < faces; face++) {
  21674. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21675. width = header[off_width];
  21676. height = header[off_height];
  21677. dataOffset = header[off_size] + 4;
  21678. for (i = 0; i < mipmapCount; ++i) {
  21679. if (info.isRGB) {
  21680. if (bpp == 24) {
  21681. dataLength = width * height * 3;
  21682. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21683. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21684. } else {
  21685. dataLength = width * height * 4;
  21686. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21687. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21688. }
  21689. } else if (info.isLuminance) {
  21690. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21691. var unpaddedRowSize = width;
  21692. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21693. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21694. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21695. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21696. } else {
  21697. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21698. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21699. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21700. }
  21701. dataOffset += dataLength;
  21702. width *= 0.5;
  21703. height *= 0.5;
  21704. width = Math.max(1.0, width);
  21705. height = Math.max(1.0, height);
  21706. }
  21707. }
  21708. };
  21709. return DDSTools;
  21710. })();
  21711. Internals.DDSTools = DDSTools;
  21712. })(BABYLON.Internals || (BABYLON.Internals = {}));
  21713. var Internals = BABYLON.Internals;
  21714. })(BABYLON || (BABYLON = {}));
  21715. //# sourceMappingURL=babylon.tools.dds.js.map
  21716. var BABYLON;
  21717. (function (BABYLON) {
  21718. var SmartArray = (function () {
  21719. function SmartArray(capacity) {
  21720. this.length = 0;
  21721. this._duplicateId = 0;
  21722. this.data = new Array(capacity);
  21723. this._id = SmartArray._GlobalId++;
  21724. }
  21725. SmartArray.prototype.push = function (value) {
  21726. this.data[this.length++] = value;
  21727. if (this.length > this.data.length) {
  21728. this.data.length *= 2;
  21729. }
  21730. if (!value.__smartArrayFlags) {
  21731. value.__smartArrayFlags = {};
  21732. }
  21733. value.__smartArrayFlags[this._id] = this._duplicateId;
  21734. };
  21735. SmartArray.prototype.pushNoDuplicate = function (value) {
  21736. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21737. return;
  21738. }
  21739. this.push(value);
  21740. };
  21741. SmartArray.prototype.sort = function (compareFn) {
  21742. this.data.sort(compareFn);
  21743. };
  21744. SmartArray.prototype.reset = function () {
  21745. this.length = 0;
  21746. this._duplicateId++;
  21747. };
  21748. SmartArray.prototype.concat = function (array) {
  21749. if (array.length === 0) {
  21750. return;
  21751. }
  21752. if (this.length + array.length > this.data.length) {
  21753. this.data.length = (this.length + array.length) * 2;
  21754. }
  21755. for (var index = 0; index < array.length; index++) {
  21756. this.data[this.length++] = (array.data || array)[index];
  21757. }
  21758. };
  21759. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21760. if (array.length === 0) {
  21761. return;
  21762. }
  21763. if (this.length + array.length > this.data.length) {
  21764. this.data.length = (this.length + array.length) * 2;
  21765. }
  21766. for (var index = 0; index < array.length; index++) {
  21767. var item = (array.data || array)[index];
  21768. this.pushNoDuplicate(item);
  21769. }
  21770. };
  21771. SmartArray.prototype.indexOf = function (value) {
  21772. var position = this.data.indexOf(value);
  21773. if (position >= this.length) {
  21774. return -1;
  21775. }
  21776. return position;
  21777. };
  21778. SmartArray._GlobalId = 0;
  21779. return SmartArray;
  21780. })();
  21781. BABYLON.SmartArray = SmartArray;
  21782. })(BABYLON || (BABYLON = {}));
  21783. //# sourceMappingURL=babylon.smartArray.js.map
  21784. var BABYLON;
  21785. (function (BABYLON) {
  21786. var CannonJSPlugin = (function () {
  21787. function CannonJSPlugin() {
  21788. this._registeredMeshes = [];
  21789. this._physicsMaterials = [];
  21790. this.updateBodyPosition = function (mesh) {
  21791. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21792. var registeredMesh = this._registeredMeshes[index];
  21793. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  21794. var body = registeredMesh.body;
  21795. var center = mesh.getBoundingInfo().boundingBox.center;
  21796. body.position.set(center.x, center.z, center.y);
  21797. body.quaternion.x = mesh.rotationQuaternion.x;
  21798. body.quaternion.z = mesh.rotationQuaternion.y;
  21799. body.quaternion.y = mesh.rotationQuaternion.z;
  21800. body.quaternion.w = -mesh.rotationQuaternion.w;
  21801. return;
  21802. }
  21803. }
  21804. };
  21805. }
  21806. CannonJSPlugin.prototype.initialize = function (iterations) {
  21807. if (typeof iterations === "undefined") { iterations = 10; }
  21808. this._world = new CANNON.World();
  21809. this._world.broadphase = new CANNON.NaiveBroadphase();
  21810. this._world.solver.iterations = iterations;
  21811. };
  21812. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  21813. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  21814. };
  21815. CannonJSPlugin.prototype.runOneStep = function (delta) {
  21816. this._world.step(delta);
  21817. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21818. var registeredMesh = this._registeredMeshes[index];
  21819. if (registeredMesh.isChild) {
  21820. continue;
  21821. }
  21822. // Body position
  21823. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  21824. var deltaPos = registeredMesh.delta;
  21825. if (deltaPos) {
  21826. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  21827. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  21828. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  21829. } else {
  21830. registeredMesh.mesh.position.x = bodyX;
  21831. registeredMesh.mesh.position.y = bodyZ;
  21832. registeredMesh.mesh.position.z = bodyY;
  21833. }
  21834. if (!registeredMesh.mesh.rotationQuaternion) {
  21835. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21836. }
  21837. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  21838. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  21839. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  21840. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  21841. }
  21842. };
  21843. CannonJSPlugin.prototype.setGravity = function (gravity) {
  21844. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  21845. };
  21846. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  21847. this.unregisterMesh(mesh);
  21848. mesh.computeWorldMatrix(true);
  21849. switch (impostor) {
  21850. case BABYLON.PhysicsEngine.SphereImpostor:
  21851. var bbox = mesh.getBoundingInfo().boundingBox;
  21852. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  21853. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  21854. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  21855. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  21856. case BABYLON.PhysicsEngine.BoxImpostor:
  21857. bbox = mesh.getBoundingInfo().boundingBox;
  21858. var min = bbox.minimumWorld;
  21859. var max = bbox.maximumWorld;
  21860. var box = max.subtract(min).scale(0.5);
  21861. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  21862. case BABYLON.PhysicsEngine.PlaneImpostor:
  21863. return this._createPlane(mesh, options);
  21864. case BABYLON.PhysicsEngine.MeshImpostor:
  21865. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21866. var rawFaces = mesh.getIndices();
  21867. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  21868. }
  21869. return null;
  21870. };
  21871. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  21872. var shape = new CANNON.Sphere(radius);
  21873. if (!options) {
  21874. return shape;
  21875. }
  21876. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21877. };
  21878. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  21879. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  21880. if (!options) {
  21881. return shape;
  21882. }
  21883. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21884. };
  21885. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  21886. var shape = new CANNON.Plane();
  21887. if (!options) {
  21888. return shape;
  21889. }
  21890. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21891. };
  21892. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  21893. var verts = [], faces = [];
  21894. mesh.computeWorldMatrix(true);
  21895. for (var i = 0; i < rawVerts.length; i += 3) {
  21896. var transformed = BABYLON.Vector3.Zero();
  21897. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  21898. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  21899. }
  21900. for (var j = 0; j < rawFaces.length; j += 3) {
  21901. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  21902. }
  21903. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  21904. if (!options) {
  21905. return shape;
  21906. }
  21907. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  21908. };
  21909. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  21910. var index;
  21911. var mat;
  21912. for (index = 0; index < this._physicsMaterials.length; index++) {
  21913. mat = this._physicsMaterials[index];
  21914. if (mat.friction === friction && mat.restitution === restitution) {
  21915. return mat;
  21916. }
  21917. }
  21918. var currentMat = new CANNON.Material();
  21919. currentMat.friction = friction;
  21920. currentMat.restitution = restitution;
  21921. this._physicsMaterials.push(currentMat);
  21922. for (index = 0; index < this._physicsMaterials.length; index++) {
  21923. mat = this._physicsMaterials[index];
  21924. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  21925. contactMaterial.contactEquationStiffness = 1e10;
  21926. contactMaterial.contactEquationRegularizationTime = 10;
  21927. this._world.addContactMaterial(contactMaterial);
  21928. }
  21929. return currentMat;
  21930. };
  21931. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  21932. var initialRotation = null;
  21933. if (mesh.rotationQuaternion) {
  21934. initialRotation = mesh.rotationQuaternion.clone();
  21935. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  21936. }
  21937. // The delta between the mesh position and the mesh bounding box center
  21938. var bbox = mesh.getBoundingInfo().boundingBox;
  21939. var deltaPosition = mesh.position.subtract(bbox.center);
  21940. var material = this._addMaterial(friction, restitution);
  21941. var body = new CANNON.RigidBody(mass, shape, material);
  21942. if (initialRotation) {
  21943. body.quaternion.x = initialRotation.x;
  21944. body.quaternion.z = initialRotation.y;
  21945. body.quaternion.y = initialRotation.z;
  21946. body.quaternion.w = -initialRotation.w;
  21947. }
  21948. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  21949. this._world.add(body);
  21950. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  21951. return body;
  21952. };
  21953. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  21954. var compoundShape = new CANNON.Compound();
  21955. for (var index = 0; index < parts.length; index++) {
  21956. var mesh = parts[index].mesh;
  21957. var shape = this.registerMesh(mesh, parts[index].impostor);
  21958. if (index == 0) {
  21959. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  21960. } else {
  21961. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  21962. }
  21963. }
  21964. var initialMesh = parts[0].mesh;
  21965. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  21966. body.parts = parts;
  21967. return body;
  21968. };
  21969. CannonJSPlugin.prototype._unbindBody = function (body) {
  21970. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21971. var registeredMesh = this._registeredMeshes[index];
  21972. if (registeredMesh.body === body) {
  21973. registeredMesh.body = null;
  21974. registeredMesh.delta = 0;
  21975. }
  21976. }
  21977. };
  21978. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  21979. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21980. var registeredMesh = this._registeredMeshes[index];
  21981. if (registeredMesh.mesh === mesh) {
  21982. // Remove body
  21983. if (registeredMesh.body) {
  21984. this._world.remove(registeredMesh.body);
  21985. this._unbindBody(registeredMesh.body);
  21986. }
  21987. this._registeredMeshes.splice(index, 1);
  21988. return;
  21989. }
  21990. }
  21991. };
  21992. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  21993. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  21994. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  21995. for (var index = 0; index < this._registeredMeshes.length; index++) {
  21996. var registeredMesh = this._registeredMeshes[index];
  21997. if (registeredMesh.mesh === mesh) {
  21998. registeredMesh.body.applyImpulse(impulse, worldPoint);
  21999. return;
  22000. }
  22001. }
  22002. };
  22003. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22004. var body1 = null, body2 = null;
  22005. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22006. var registeredMesh = this._registeredMeshes[index];
  22007. if (registeredMesh.mesh === mesh1) {
  22008. body1 = registeredMesh.body;
  22009. } else if (registeredMesh.mesh === mesh2) {
  22010. body2 = registeredMesh.body;
  22011. }
  22012. }
  22013. if (!body1 || !body2) {
  22014. return false;
  22015. }
  22016. 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));
  22017. this._world.addConstraint(constraint);
  22018. return true;
  22019. };
  22020. CannonJSPlugin.prototype.dispose = function () {
  22021. while (this._registeredMeshes.length) {
  22022. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22023. }
  22024. };
  22025. CannonJSPlugin.prototype.isSupported = function () {
  22026. return window.CANNON !== undefined;
  22027. };
  22028. return CannonJSPlugin;
  22029. })();
  22030. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22031. })(BABYLON || (BABYLON = {}));
  22032. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22033. var BABYLON;
  22034. (function (BABYLON) {
  22035. var Condition = (function () {
  22036. function Condition(actionManager) {
  22037. this._actionManager = actionManager;
  22038. }
  22039. Condition.prototype.isValid = function () {
  22040. return true;
  22041. };
  22042. Condition.prototype._getProperty = function (propertyPath) {
  22043. return this._actionManager._getProperty(propertyPath);
  22044. };
  22045. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22046. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22047. };
  22048. return Condition;
  22049. })();
  22050. BABYLON.Condition = Condition;
  22051. var ValueCondition = (function (_super) {
  22052. __extends(ValueCondition, _super);
  22053. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22054. if (typeof operator === "undefined") { operator = ValueCondition.IsEqual; }
  22055. _super.call(this, actionManager);
  22056. this.propertyPath = propertyPath;
  22057. this.value = value;
  22058. this.operator = operator;
  22059. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22060. this._property = this._getProperty(this.propertyPath);
  22061. }
  22062. Object.defineProperty(ValueCondition, "IsEqual", {
  22063. get: function () {
  22064. return ValueCondition._IsEqual;
  22065. },
  22066. enumerable: true,
  22067. configurable: true
  22068. });
  22069. Object.defineProperty(ValueCondition, "IsDifferent", {
  22070. get: function () {
  22071. return ValueCondition._IsDifferent;
  22072. },
  22073. enumerable: true,
  22074. configurable: true
  22075. });
  22076. Object.defineProperty(ValueCondition, "IsGreater", {
  22077. get: function () {
  22078. return ValueCondition._IsGreater;
  22079. },
  22080. enumerable: true,
  22081. configurable: true
  22082. });
  22083. Object.defineProperty(ValueCondition, "IsLesser", {
  22084. get: function () {
  22085. return ValueCondition._IsLesser;
  22086. },
  22087. enumerable: true,
  22088. configurable: true
  22089. });
  22090. // Methods
  22091. ValueCondition.prototype.isValid = function () {
  22092. switch (this.operator) {
  22093. case ValueCondition.IsGreater:
  22094. return this._target[this._property] > this.value;
  22095. case ValueCondition.IsLesser:
  22096. return this._target[this._property] < this.value;
  22097. case ValueCondition.IsEqual:
  22098. case ValueCondition.IsDifferent:
  22099. var check;
  22100. if (this.value.equals) {
  22101. check = this.value.equals(this._target[this._property]);
  22102. } else {
  22103. check = this.value === this._target[this._property];
  22104. }
  22105. return this.operator === ValueCondition.IsEqual ? check : !check;
  22106. }
  22107. return false;
  22108. };
  22109. ValueCondition._IsEqual = 0;
  22110. ValueCondition._IsDifferent = 1;
  22111. ValueCondition._IsGreater = 2;
  22112. ValueCondition._IsLesser = 3;
  22113. return ValueCondition;
  22114. })(Condition);
  22115. BABYLON.ValueCondition = ValueCondition;
  22116. var PredicateCondition = (function (_super) {
  22117. __extends(PredicateCondition, _super);
  22118. function PredicateCondition(actionManager, predicate) {
  22119. _super.call(this, actionManager);
  22120. this.predicate = predicate;
  22121. }
  22122. PredicateCondition.prototype.isValid = function () {
  22123. return this.predicate();
  22124. };
  22125. return PredicateCondition;
  22126. })(Condition);
  22127. BABYLON.PredicateCondition = PredicateCondition;
  22128. var StateCondition = (function (_super) {
  22129. __extends(StateCondition, _super);
  22130. function StateCondition(actionManager, target, value) {
  22131. _super.call(this, actionManager);
  22132. this.value = value;
  22133. this._target = target;
  22134. }
  22135. // Methods
  22136. StateCondition.prototype.isValid = function () {
  22137. return this._target.state === this.value;
  22138. };
  22139. return StateCondition;
  22140. })(Condition);
  22141. BABYLON.StateCondition = StateCondition;
  22142. })(BABYLON || (BABYLON = {}));
  22143. //# sourceMappingURL=babylon.condition.js.map
  22144. var BABYLON;
  22145. (function (BABYLON) {
  22146. var Action = (function () {
  22147. function Action(triggerOptions, condition) {
  22148. this.triggerOptions = triggerOptions;
  22149. if (triggerOptions.parameter) {
  22150. this.trigger = triggerOptions.trigger;
  22151. this._triggerParameter = triggerOptions.parameter;
  22152. } else {
  22153. this.trigger = triggerOptions;
  22154. }
  22155. this._nextActiveAction = this;
  22156. this._condition = condition;
  22157. }
  22158. // Methods
  22159. Action.prototype._prepare = function () {
  22160. };
  22161. Action.prototype.getTriggerParameter = function () {
  22162. return this._triggerParameter;
  22163. };
  22164. Action.prototype._executeCurrent = function (evt) {
  22165. if (this._condition) {
  22166. var currentRenderId = this._actionManager.getScene().getRenderId();
  22167. // We cache the current evaluation for the current frame
  22168. if (this._condition._evaluationId === currentRenderId) {
  22169. if (!this._condition._currentResult) {
  22170. return;
  22171. }
  22172. } else {
  22173. this._condition._evaluationId = currentRenderId;
  22174. if (!this._condition.isValid()) {
  22175. this._condition._currentResult = false;
  22176. return;
  22177. }
  22178. this._condition._currentResult = true;
  22179. }
  22180. }
  22181. this._nextActiveAction.execute(evt);
  22182. if (this._nextActiveAction._child) {
  22183. if (!this._nextActiveAction._child._actionManager) {
  22184. this._nextActiveAction._child._actionManager = this._actionManager;
  22185. }
  22186. this._nextActiveAction = this._nextActiveAction._child;
  22187. } else {
  22188. this._nextActiveAction = this;
  22189. }
  22190. };
  22191. Action.prototype.execute = function (evt) {
  22192. };
  22193. Action.prototype.then = function (action) {
  22194. this._child = action;
  22195. action._actionManager = this._actionManager;
  22196. action._prepare();
  22197. return action;
  22198. };
  22199. Action.prototype._getProperty = function (propertyPath) {
  22200. return this._actionManager._getProperty(propertyPath);
  22201. };
  22202. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22203. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22204. };
  22205. return Action;
  22206. })();
  22207. BABYLON.Action = Action;
  22208. })(BABYLON || (BABYLON = {}));
  22209. //# sourceMappingURL=babylon.action.js.map
  22210. var BABYLON;
  22211. (function (BABYLON) {
  22212. var ActionEvent = (function () {
  22213. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22214. this.source = source;
  22215. this.pointerX = pointerX;
  22216. this.pointerY = pointerY;
  22217. this.meshUnderPointer = meshUnderPointer;
  22218. this.sourceEvent = sourceEvent;
  22219. }
  22220. ActionEvent.CreateNew = function (source, evt) {
  22221. var scene = source.getScene();
  22222. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22223. };
  22224. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22225. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22226. };
  22227. return ActionEvent;
  22228. })();
  22229. BABYLON.ActionEvent = ActionEvent;
  22230. var ActionManager = (function () {
  22231. function ActionManager(scene) {
  22232. // Members
  22233. this.actions = new Array();
  22234. this._scene = scene;
  22235. scene._actionManagers.push(this);
  22236. }
  22237. Object.defineProperty(ActionManager, "NothingTrigger", {
  22238. get: function () {
  22239. return ActionManager._NothingTrigger;
  22240. },
  22241. enumerable: true,
  22242. configurable: true
  22243. });
  22244. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22245. get: function () {
  22246. return ActionManager._OnPickTrigger;
  22247. },
  22248. enumerable: true,
  22249. configurable: true
  22250. });
  22251. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22252. get: function () {
  22253. return ActionManager._OnLeftPickTrigger;
  22254. },
  22255. enumerable: true,
  22256. configurable: true
  22257. });
  22258. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22259. get: function () {
  22260. return ActionManager._OnRightPickTrigger;
  22261. },
  22262. enumerable: true,
  22263. configurable: true
  22264. });
  22265. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22266. get: function () {
  22267. return ActionManager._OnCenterPickTrigger;
  22268. },
  22269. enumerable: true,
  22270. configurable: true
  22271. });
  22272. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22273. get: function () {
  22274. return ActionManager._OnPointerOverTrigger;
  22275. },
  22276. enumerable: true,
  22277. configurable: true
  22278. });
  22279. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22280. get: function () {
  22281. return ActionManager._OnPointerOutTrigger;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22287. get: function () {
  22288. return ActionManager._OnEveryFrameTrigger;
  22289. },
  22290. enumerable: true,
  22291. configurable: true
  22292. });
  22293. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22294. get: function () {
  22295. return ActionManager._OnIntersectionEnterTrigger;
  22296. },
  22297. enumerable: true,
  22298. configurable: true
  22299. });
  22300. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22301. get: function () {
  22302. return ActionManager._OnIntersectionExitTrigger;
  22303. },
  22304. enumerable: true,
  22305. configurable: true
  22306. });
  22307. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22308. get: function () {
  22309. return ActionManager._OnKeyDownTrigger;
  22310. },
  22311. enumerable: true,
  22312. configurable: true
  22313. });
  22314. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22315. get: function () {
  22316. return ActionManager._OnKeyUpTrigger;
  22317. },
  22318. enumerable: true,
  22319. configurable: true
  22320. });
  22321. // Methods
  22322. ActionManager.prototype.dispose = function () {
  22323. var index = this._scene._actionManagers.indexOf(this);
  22324. if (index > -1) {
  22325. this._scene._actionManagers.splice(index, 1);
  22326. }
  22327. };
  22328. ActionManager.prototype.getScene = function () {
  22329. return this._scene;
  22330. };
  22331. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22332. for (var index = 0; index < this.actions.length; index++) {
  22333. var action = this.actions[index];
  22334. if (triggers.indexOf(action.trigger) > -1) {
  22335. return true;
  22336. }
  22337. }
  22338. return false;
  22339. };
  22340. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22341. get: function () {
  22342. for (var index = 0; index < this.actions.length; index++) {
  22343. var action = this.actions[index];
  22344. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22345. return true;
  22346. }
  22347. }
  22348. return false;
  22349. },
  22350. enumerable: true,
  22351. configurable: true
  22352. });
  22353. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22354. get: function () {
  22355. for (var index = 0; index < this.actions.length; index++) {
  22356. var action = this.actions[index];
  22357. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22358. return true;
  22359. }
  22360. }
  22361. return false;
  22362. },
  22363. enumerable: true,
  22364. configurable: true
  22365. });
  22366. ActionManager.prototype.registerAction = function (action) {
  22367. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22368. if (this.getScene().actionManager !== this) {
  22369. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22370. return null;
  22371. }
  22372. }
  22373. this.actions.push(action);
  22374. action._actionManager = this;
  22375. action._prepare();
  22376. return action;
  22377. };
  22378. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22379. for (var index = 0; index < this.actions.length; index++) {
  22380. var action = this.actions[index];
  22381. if (action.trigger === trigger) {
  22382. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22383. var parameter = action.getTriggerParameter();
  22384. if (parameter) {
  22385. if (evt.sourceEvent.key !== parameter) {
  22386. continue;
  22387. }
  22388. }
  22389. }
  22390. action._executeCurrent(evt);
  22391. }
  22392. }
  22393. };
  22394. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22395. var properties = propertyPath.split(".");
  22396. for (var index = 0; index < properties.length - 1; index++) {
  22397. target = target[properties[index]];
  22398. }
  22399. return target;
  22400. };
  22401. ActionManager.prototype._getProperty = function (propertyPath) {
  22402. var properties = propertyPath.split(".");
  22403. return properties[properties.length - 1];
  22404. };
  22405. ActionManager._NothingTrigger = 0;
  22406. ActionManager._OnPickTrigger = 1;
  22407. ActionManager._OnLeftPickTrigger = 2;
  22408. ActionManager._OnRightPickTrigger = 3;
  22409. ActionManager._OnCenterPickTrigger = 4;
  22410. ActionManager._OnPointerOverTrigger = 5;
  22411. ActionManager._OnPointerOutTrigger = 6;
  22412. ActionManager._OnEveryFrameTrigger = 7;
  22413. ActionManager._OnIntersectionEnterTrigger = 8;
  22414. ActionManager._OnIntersectionExitTrigger = 9;
  22415. ActionManager._OnKeyDownTrigger = 10;
  22416. ActionManager._OnKeyUpTrigger = 11;
  22417. return ActionManager;
  22418. })();
  22419. BABYLON.ActionManager = ActionManager;
  22420. })(BABYLON || (BABYLON = {}));
  22421. //# sourceMappingURL=babylon.actionManager.js.map
  22422. var BABYLON;
  22423. (function (BABYLON) {
  22424. var InterpolateValueAction = (function (_super) {
  22425. __extends(InterpolateValueAction, _super);
  22426. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22427. if (typeof duration === "undefined") { duration = 1000; }
  22428. _super.call(this, triggerOptions, condition);
  22429. this.propertyPath = propertyPath;
  22430. this.value = value;
  22431. this.duration = duration;
  22432. this.stopOtherAnimations = stopOtherAnimations;
  22433. this._target = target;
  22434. }
  22435. InterpolateValueAction.prototype._prepare = function () {
  22436. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22437. this._property = this._getProperty(this.propertyPath);
  22438. };
  22439. InterpolateValueAction.prototype.execute = function () {
  22440. var scene = this._actionManager.getScene();
  22441. var keys = [
  22442. {
  22443. frame: 0,
  22444. value: this._target[this._property]
  22445. }, {
  22446. frame: 100,
  22447. value: this.value
  22448. }
  22449. ];
  22450. var dataType;
  22451. if (typeof this.value === "number") {
  22452. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22453. } else if (this.value instanceof BABYLON.Color3) {
  22454. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22455. } else if (this.value instanceof BABYLON.Vector3) {
  22456. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22457. } else if (this.value instanceof BABYLON.Matrix) {
  22458. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22459. } else if (this.value instanceof BABYLON.Quaternion) {
  22460. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22461. } else {
  22462. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22463. return;
  22464. }
  22465. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22466. animation.setKeys(keys);
  22467. if (this.stopOtherAnimations) {
  22468. scene.stopAnimation(this._target);
  22469. }
  22470. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22471. };
  22472. return InterpolateValueAction;
  22473. })(BABYLON.Action);
  22474. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22475. })(BABYLON || (BABYLON = {}));
  22476. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22477. var BABYLON;
  22478. (function (BABYLON) {
  22479. var SwitchBooleanAction = (function (_super) {
  22480. __extends(SwitchBooleanAction, _super);
  22481. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22482. _super.call(this, triggerOptions, condition);
  22483. this.propertyPath = propertyPath;
  22484. this._target = target;
  22485. }
  22486. SwitchBooleanAction.prototype._prepare = function () {
  22487. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22488. this._property = this._getProperty(this.propertyPath);
  22489. };
  22490. SwitchBooleanAction.prototype.execute = function () {
  22491. this._target[this._property] = !this._target[this._property];
  22492. };
  22493. return SwitchBooleanAction;
  22494. })(BABYLON.Action);
  22495. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22496. var SetStateAction = (function (_super) {
  22497. __extends(SetStateAction, _super);
  22498. function SetStateAction(triggerOptions, target, value, condition) {
  22499. _super.call(this, triggerOptions, condition);
  22500. this.value = value;
  22501. this._target = target;
  22502. }
  22503. SetStateAction.prototype.execute = function () {
  22504. this._target.state = this.value;
  22505. };
  22506. return SetStateAction;
  22507. })(BABYLON.Action);
  22508. BABYLON.SetStateAction = SetStateAction;
  22509. var SetValueAction = (function (_super) {
  22510. __extends(SetValueAction, _super);
  22511. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22512. _super.call(this, triggerOptions, condition);
  22513. this.propertyPath = propertyPath;
  22514. this.value = value;
  22515. this._target = target;
  22516. }
  22517. SetValueAction.prototype._prepare = function () {
  22518. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22519. this._property = this._getProperty(this.propertyPath);
  22520. };
  22521. SetValueAction.prototype.execute = function () {
  22522. this._target[this._property] = this.value;
  22523. };
  22524. return SetValueAction;
  22525. })(BABYLON.Action);
  22526. BABYLON.SetValueAction = SetValueAction;
  22527. var IncrementValueAction = (function (_super) {
  22528. __extends(IncrementValueAction, _super);
  22529. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22530. _super.call(this, triggerOptions, condition);
  22531. this.propertyPath = propertyPath;
  22532. this.value = value;
  22533. this._target = target;
  22534. }
  22535. IncrementValueAction.prototype._prepare = function () {
  22536. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22537. this._property = this._getProperty(this.propertyPath);
  22538. if (typeof this._target[this._property] !== "number") {
  22539. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22540. }
  22541. };
  22542. IncrementValueAction.prototype.execute = function () {
  22543. this._target[this._property] += this.value;
  22544. };
  22545. return IncrementValueAction;
  22546. })(BABYLON.Action);
  22547. BABYLON.IncrementValueAction = IncrementValueAction;
  22548. var PlayAnimationAction = (function (_super) {
  22549. __extends(PlayAnimationAction, _super);
  22550. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22551. _super.call(this, triggerOptions, condition);
  22552. this.from = from;
  22553. this.to = to;
  22554. this.loop = loop;
  22555. this._target = target;
  22556. }
  22557. PlayAnimationAction.prototype._prepare = function () {
  22558. };
  22559. PlayAnimationAction.prototype.execute = function () {
  22560. var scene = this._actionManager.getScene();
  22561. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22562. };
  22563. return PlayAnimationAction;
  22564. })(BABYLON.Action);
  22565. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22566. var StopAnimationAction = (function (_super) {
  22567. __extends(StopAnimationAction, _super);
  22568. function StopAnimationAction(triggerOptions, target, condition) {
  22569. _super.call(this, triggerOptions, condition);
  22570. this._target = target;
  22571. }
  22572. StopAnimationAction.prototype._prepare = function () {
  22573. };
  22574. StopAnimationAction.prototype.execute = function () {
  22575. var scene = this._actionManager.getScene();
  22576. scene.stopAnimation(this._target);
  22577. };
  22578. return StopAnimationAction;
  22579. })(BABYLON.Action);
  22580. BABYLON.StopAnimationAction = StopAnimationAction;
  22581. var DoNothingAction = (function (_super) {
  22582. __extends(DoNothingAction, _super);
  22583. function DoNothingAction(triggerOptions, condition) {
  22584. if (typeof triggerOptions === "undefined") { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22585. _super.call(this, triggerOptions, condition);
  22586. }
  22587. DoNothingAction.prototype.execute = function () {
  22588. };
  22589. return DoNothingAction;
  22590. })(BABYLON.Action);
  22591. BABYLON.DoNothingAction = DoNothingAction;
  22592. var CombineAction = (function (_super) {
  22593. __extends(CombineAction, _super);
  22594. function CombineAction(triggerOptions, children, condition) {
  22595. _super.call(this, triggerOptions, condition);
  22596. this.children = children;
  22597. }
  22598. CombineAction.prototype._prepare = function () {
  22599. for (var index = 0; index < this.children.length; index++) {
  22600. this.children[index]._actionManager = this._actionManager;
  22601. this.children[index]._prepare();
  22602. }
  22603. };
  22604. CombineAction.prototype.execute = function (evt) {
  22605. for (var index = 0; index < this.children.length; index++) {
  22606. this.children[index].execute(evt);
  22607. }
  22608. };
  22609. return CombineAction;
  22610. })(BABYLON.Action);
  22611. BABYLON.CombineAction = CombineAction;
  22612. var ExecuteCodeAction = (function (_super) {
  22613. __extends(ExecuteCodeAction, _super);
  22614. function ExecuteCodeAction(triggerOptions, func, condition) {
  22615. _super.call(this, triggerOptions, condition);
  22616. this.func = func;
  22617. }
  22618. ExecuteCodeAction.prototype.execute = function (evt) {
  22619. this.func(evt);
  22620. };
  22621. return ExecuteCodeAction;
  22622. })(BABYLON.Action);
  22623. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22624. var SetParentAction = (function (_super) {
  22625. __extends(SetParentAction, _super);
  22626. function SetParentAction(triggerOptions, target, parent, condition) {
  22627. _super.call(this, triggerOptions, condition);
  22628. this._target = target;
  22629. this._parent = parent;
  22630. }
  22631. SetParentAction.prototype._prepare = function () {
  22632. };
  22633. SetParentAction.prototype.execute = function () {
  22634. if (this._target.parent === this._parent) {
  22635. return;
  22636. }
  22637. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22638. invertParentWorldMatrix.invert();
  22639. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22640. this._target.parent = this._parent;
  22641. };
  22642. return SetParentAction;
  22643. })(BABYLON.Action);
  22644. BABYLON.SetParentAction = SetParentAction;
  22645. })(BABYLON || (BABYLON = {}));
  22646. //# sourceMappingURL=babylon.directActions.js.map
  22647. var BABYLON;
  22648. (function (BABYLON) {
  22649. var Geometry = (function () {
  22650. function Geometry(id, scene, vertexData, updatable, mesh) {
  22651. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22652. this._totalVertices = 0;
  22653. this._indices = [];
  22654. this.id = id;
  22655. this._engine = scene.getEngine();
  22656. this._meshes = [];
  22657. this._scene = scene;
  22658. // vertexData
  22659. if (vertexData) {
  22660. this.setAllVerticesData(vertexData, updatable);
  22661. } else {
  22662. this._totalVertices = 0;
  22663. this._indices = [];
  22664. }
  22665. // applyToMesh
  22666. if (mesh) {
  22667. this.applyToMesh(mesh);
  22668. }
  22669. }
  22670. Geometry.prototype.getScene = function () {
  22671. return this._scene;
  22672. };
  22673. Geometry.prototype.getEngine = function () {
  22674. return this._engine;
  22675. };
  22676. Geometry.prototype.isReady = function () {
  22677. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22678. };
  22679. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22680. vertexData.applyToGeometry(this, updatable);
  22681. };
  22682. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22683. this._vertexBuffers = this._vertexBuffers || {};
  22684. if (this._vertexBuffers[kind]) {
  22685. this._vertexBuffers[kind].dispose();
  22686. }
  22687. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22688. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22689. stride = this._vertexBuffers[kind].getStrideSize();
  22690. this._totalVertices = data.length / stride;
  22691. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22692. var meshes = this._meshes;
  22693. var numOfMeshes = meshes.length;
  22694. for (var index = 0; index < numOfMeshes; index++) {
  22695. var mesh = meshes[index];
  22696. mesh._resetPointsArrayCache();
  22697. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22698. mesh._createGlobalSubMesh();
  22699. mesh.computeWorldMatrix(true);
  22700. }
  22701. }
  22702. };
  22703. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22704. var vertexBuffer = this.getVertexBuffer(kind);
  22705. if (!vertexBuffer) {
  22706. return;
  22707. }
  22708. vertexBuffer.updateDirectly(data, offset);
  22709. };
  22710. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22711. var vertexBuffer = this.getVertexBuffer(kind);
  22712. if (!vertexBuffer) {
  22713. return;
  22714. }
  22715. vertexBuffer.update(data);
  22716. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22717. var extend;
  22718. var stride = vertexBuffer.getStrideSize();
  22719. this._totalVertices = data.length / stride;
  22720. if (updateExtends) {
  22721. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22722. }
  22723. var meshes = this._meshes;
  22724. var numOfMeshes = meshes.length;
  22725. for (var index = 0; index < numOfMeshes; index++) {
  22726. var mesh = meshes[index];
  22727. mesh._resetPointsArrayCache();
  22728. if (updateExtends) {
  22729. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22730. }
  22731. }
  22732. }
  22733. };
  22734. Geometry.prototype.getTotalVertices = function () {
  22735. if (!this.isReady()) {
  22736. return 0;
  22737. }
  22738. return this._totalVertices;
  22739. };
  22740. Geometry.prototype.getVerticesData = function (kind) {
  22741. var vertexBuffer = this.getVertexBuffer(kind);
  22742. if (!vertexBuffer) {
  22743. return null;
  22744. }
  22745. return vertexBuffer.getData();
  22746. };
  22747. Geometry.prototype.getVertexBuffer = function (kind) {
  22748. if (!this.isReady()) {
  22749. return null;
  22750. }
  22751. return this._vertexBuffers[kind];
  22752. };
  22753. Geometry.prototype.getVertexBuffers = function () {
  22754. if (!this.isReady()) {
  22755. return null;
  22756. }
  22757. return this._vertexBuffers;
  22758. };
  22759. Geometry.prototype.isVerticesDataPresent = function (kind) {
  22760. if (!this._vertexBuffers) {
  22761. if (this._delayInfo) {
  22762. return this._delayInfo.indexOf(kind) !== -1;
  22763. }
  22764. return false;
  22765. }
  22766. return this._vertexBuffers[kind] !== undefined;
  22767. };
  22768. Geometry.prototype.getVerticesDataKinds = function () {
  22769. var result = [];
  22770. if (!this._vertexBuffers && this._delayInfo) {
  22771. for (var kind in this._delayInfo) {
  22772. result.push(kind);
  22773. }
  22774. } else {
  22775. for (kind in this._vertexBuffers) {
  22776. result.push(kind);
  22777. }
  22778. }
  22779. return result;
  22780. };
  22781. Geometry.prototype.setIndices = function (indices, totalVertices) {
  22782. if (this._indexBuffer) {
  22783. this._engine._releaseBuffer(this._indexBuffer);
  22784. }
  22785. this._indices = indices;
  22786. if (this._meshes.length !== 0 && this._indices) {
  22787. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22788. }
  22789. if (totalVertices !== undefined) {
  22790. this._totalVertices = totalVertices;
  22791. }
  22792. var meshes = this._meshes;
  22793. var numOfMeshes = meshes.length;
  22794. for (var index = 0; index < numOfMeshes; index++) {
  22795. meshes[index]._createGlobalSubMesh();
  22796. }
  22797. };
  22798. Geometry.prototype.getTotalIndices = function () {
  22799. if (!this.isReady()) {
  22800. return 0;
  22801. }
  22802. return this._indices.length;
  22803. };
  22804. Geometry.prototype.getIndices = function () {
  22805. if (!this.isReady()) {
  22806. return null;
  22807. }
  22808. return this._indices;
  22809. };
  22810. Geometry.prototype.getIndexBuffer = function () {
  22811. if (!this.isReady()) {
  22812. return null;
  22813. }
  22814. return this._indexBuffer;
  22815. };
  22816. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  22817. var meshes = this._meshes;
  22818. var index = meshes.indexOf(mesh);
  22819. if (index === -1) {
  22820. return;
  22821. }
  22822. for (var kind in this._vertexBuffers) {
  22823. this._vertexBuffers[kind].dispose();
  22824. }
  22825. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  22826. this._indexBuffer = null;
  22827. }
  22828. meshes.splice(index, 1);
  22829. mesh._geometry = null;
  22830. if (meshes.length === 0 && shouldDispose) {
  22831. this.dispose();
  22832. }
  22833. };
  22834. Geometry.prototype.applyToMesh = function (mesh) {
  22835. if (mesh._geometry === this) {
  22836. return;
  22837. }
  22838. var previousGeometry = mesh._geometry;
  22839. if (previousGeometry) {
  22840. previousGeometry.releaseForMesh(mesh);
  22841. }
  22842. var meshes = this._meshes;
  22843. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  22844. mesh._geometry = this;
  22845. this._scene.pushGeometry(this);
  22846. meshes.push(mesh);
  22847. if (this.isReady()) {
  22848. this._applyToMesh(mesh);
  22849. } else {
  22850. mesh._boundingInfo = this._boundingInfo;
  22851. }
  22852. };
  22853. Geometry.prototype._applyToMesh = function (mesh) {
  22854. var numOfMeshes = this._meshes.length;
  22855. for (var kind in this._vertexBuffers) {
  22856. if (numOfMeshes === 1) {
  22857. this._vertexBuffers[kind].create();
  22858. }
  22859. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  22860. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22861. mesh._resetPointsArrayCache();
  22862. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  22863. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22864. mesh._createGlobalSubMesh();
  22865. //bounding info was just created again, world matrix should be applied again.
  22866. mesh._updateBoundingInfo();
  22867. }
  22868. }
  22869. // indexBuffer
  22870. if (numOfMeshes === 1 && this._indices) {
  22871. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  22872. }
  22873. if (this._indexBuffer) {
  22874. this._indexBuffer.references = numOfMeshes;
  22875. }
  22876. };
  22877. Geometry.prototype.load = function (scene, onLoaded) {
  22878. var _this = this;
  22879. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  22880. return;
  22881. }
  22882. if (this.isReady()) {
  22883. if (onLoaded) {
  22884. onLoaded();
  22885. }
  22886. return;
  22887. }
  22888. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  22889. scene._addPendingData(this);
  22890. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  22891. _this._delayLoadingFunction(JSON.parse(data), _this);
  22892. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  22893. _this._delayInfo = [];
  22894. scene._removePendingData(_this);
  22895. var meshes = _this._meshes;
  22896. var numOfMeshes = meshes.length;
  22897. for (var index = 0; index < numOfMeshes; index++) {
  22898. _this._applyToMesh(meshes[index]);
  22899. }
  22900. if (onLoaded) {
  22901. onLoaded();
  22902. }
  22903. }, function () {
  22904. }, scene.database);
  22905. };
  22906. Geometry.prototype.dispose = function () {
  22907. var meshes = this._meshes;
  22908. var numOfMeshes = meshes.length;
  22909. var index;
  22910. for (index = 0; index < numOfMeshes; index++) {
  22911. this.releaseForMesh(meshes[index]);
  22912. }
  22913. this._meshes = [];
  22914. for (var kind in this._vertexBuffers) {
  22915. this._vertexBuffers[kind].dispose();
  22916. }
  22917. this._vertexBuffers = [];
  22918. this._totalVertices = 0;
  22919. if (this._indexBuffer) {
  22920. this._engine._releaseBuffer(this._indexBuffer);
  22921. }
  22922. this._indexBuffer = null;
  22923. this._indices = [];
  22924. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22925. this.delayLoadingFile = null;
  22926. this._delayLoadingFunction = null;
  22927. this._delayInfo = [];
  22928. this._boundingInfo = null; // todo: .dispose()
  22929. var geometries = this._scene.getGeometries();
  22930. index = geometries.indexOf(this);
  22931. if (index > -1) {
  22932. geometries.splice(index, 1);
  22933. }
  22934. };
  22935. Geometry.prototype.copy = function (id) {
  22936. var vertexData = new BABYLON.VertexData();
  22937. vertexData.indices = [];
  22938. var indices = this.getIndices();
  22939. for (var index = 0; index < indices.length; index++) {
  22940. vertexData.indices.push(indices[index]);
  22941. }
  22942. var updatable = false;
  22943. var stopChecking = false;
  22944. for (var kind in this._vertexBuffers) {
  22945. vertexData.set(this.getVerticesData(kind), kind);
  22946. if (!stopChecking) {
  22947. updatable = this.getVertexBuffer(kind).isUpdatable();
  22948. stopChecking = !updatable;
  22949. }
  22950. }
  22951. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  22952. geometry.delayLoadState = this.delayLoadState;
  22953. geometry.delayLoadingFile = this.delayLoadingFile;
  22954. geometry._delayLoadingFunction = this._delayLoadingFunction;
  22955. for (kind in this._delayInfo) {
  22956. geometry._delayInfo = geometry._delayInfo || [];
  22957. geometry._delayInfo.push(kind);
  22958. }
  22959. // Bounding info
  22960. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  22961. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22962. return geometry;
  22963. };
  22964. // Statics
  22965. Geometry.ExtractFromMesh = function (mesh, id) {
  22966. var geometry = mesh._geometry;
  22967. if (!geometry) {
  22968. return null;
  22969. }
  22970. return geometry.copy(id);
  22971. };
  22972. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  22973. // be aware Math.random() could cause collisions
  22974. Geometry.RandomId = function () {
  22975. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  22976. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  22977. return v.toString(16);
  22978. });
  22979. };
  22980. return Geometry;
  22981. })();
  22982. BABYLON.Geometry = Geometry;
  22983. (function (Geometry) {
  22984. /////// Primitives //////////////////////////////////////////////
  22985. (function (Primitives) {
  22986. /// Abstract class
  22987. var _Primitive = (function (_super) {
  22988. __extends(_Primitive, _super);
  22989. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  22990. this._beingRegenerated = true;
  22991. this._canBeRegenerated = canBeRegenerated;
  22992. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  22993. this._beingRegenerated = false;
  22994. }
  22995. _Primitive.prototype.canBeRegenerated = function () {
  22996. return this._canBeRegenerated;
  22997. };
  22998. _Primitive.prototype.regenerate = function () {
  22999. if (!this._canBeRegenerated) {
  23000. return;
  23001. }
  23002. this._beingRegenerated = true;
  23003. this.setAllVerticesData(this._regenerateVertexData(), false);
  23004. this._beingRegenerated = false;
  23005. };
  23006. _Primitive.prototype.asNewGeometry = function (id) {
  23007. return _super.prototype.copy.call(this, id);
  23008. };
  23009. // overrides
  23010. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23011. if (!this._beingRegenerated) {
  23012. return;
  23013. }
  23014. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23015. };
  23016. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23017. if (!this._beingRegenerated) {
  23018. return;
  23019. }
  23020. _super.prototype.setVerticesData.call(this, kind, data, false);
  23021. };
  23022. // to override
  23023. // protected
  23024. _Primitive.prototype._regenerateVertexData = function () {
  23025. throw new Error("Abstract method");
  23026. };
  23027. _Primitive.prototype.copy = function (id) {
  23028. throw new Error("Must be overriden in sub-classes.");
  23029. };
  23030. return _Primitive;
  23031. })(Geometry);
  23032. Primitives._Primitive = _Primitive;
  23033. var Box = (function (_super) {
  23034. __extends(Box, _super);
  23035. function Box(id, scene, size, canBeRegenerated, mesh) {
  23036. this.size = size;
  23037. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23038. }
  23039. Box.prototype._regenerateVertexData = function () {
  23040. return BABYLON.VertexData.CreateBox(this.size);
  23041. };
  23042. Box.prototype.copy = function (id) {
  23043. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23044. };
  23045. return Box;
  23046. })(_Primitive);
  23047. Primitives.Box = Box;
  23048. var Sphere = (function (_super) {
  23049. __extends(Sphere, _super);
  23050. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23051. this.segments = segments;
  23052. this.diameter = diameter;
  23053. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23054. }
  23055. Sphere.prototype._regenerateVertexData = function () {
  23056. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23057. };
  23058. Sphere.prototype.copy = function (id) {
  23059. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23060. };
  23061. return Sphere;
  23062. })(_Primitive);
  23063. Primitives.Sphere = Sphere;
  23064. var Cylinder = (function (_super) {
  23065. __extends(Cylinder, _super);
  23066. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23067. if (typeof subdivisions === "undefined") { subdivisions = 1; }
  23068. this.height = height;
  23069. this.diameterTop = diameterTop;
  23070. this.diameterBottom = diameterBottom;
  23071. this.tessellation = tessellation;
  23072. this.subdivisions = subdivisions;
  23073. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23074. }
  23075. Cylinder.prototype._regenerateVertexData = function () {
  23076. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23077. };
  23078. Cylinder.prototype.copy = function (id) {
  23079. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23080. };
  23081. return Cylinder;
  23082. })(_Primitive);
  23083. Primitives.Cylinder = Cylinder;
  23084. var Torus = (function (_super) {
  23085. __extends(Torus, _super);
  23086. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23087. this.diameter = diameter;
  23088. this.thickness = thickness;
  23089. this.tessellation = tessellation;
  23090. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23091. }
  23092. Torus.prototype._regenerateVertexData = function () {
  23093. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23094. };
  23095. Torus.prototype.copy = function (id) {
  23096. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23097. };
  23098. return Torus;
  23099. })(_Primitive);
  23100. Primitives.Torus = Torus;
  23101. var Ground = (function (_super) {
  23102. __extends(Ground, _super);
  23103. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23104. this.width = width;
  23105. this.height = height;
  23106. this.subdivisions = subdivisions;
  23107. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23108. }
  23109. Ground.prototype._regenerateVertexData = function () {
  23110. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23111. };
  23112. Ground.prototype.copy = function (id) {
  23113. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23114. };
  23115. return Ground;
  23116. })(_Primitive);
  23117. Primitives.Ground = Ground;
  23118. var TiledGround = (function (_super) {
  23119. __extends(TiledGround, _super);
  23120. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23121. this.xmin = xmin;
  23122. this.zmin = zmin;
  23123. this.xmax = xmax;
  23124. this.zmax = zmax;
  23125. this.subdivisions = subdivisions;
  23126. this.precision = precision;
  23127. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23128. }
  23129. TiledGround.prototype._regenerateVertexData = function () {
  23130. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23131. };
  23132. TiledGround.prototype.copy = function (id) {
  23133. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23134. };
  23135. return TiledGround;
  23136. })(_Primitive);
  23137. Primitives.TiledGround = TiledGround;
  23138. var Plane = (function (_super) {
  23139. __extends(Plane, _super);
  23140. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23141. this.size = size;
  23142. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23143. }
  23144. Plane.prototype._regenerateVertexData = function () {
  23145. return BABYLON.VertexData.CreatePlane(this.size);
  23146. };
  23147. Plane.prototype.copy = function (id) {
  23148. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23149. };
  23150. return Plane;
  23151. })(_Primitive);
  23152. Primitives.Plane = Plane;
  23153. var TorusKnot = (function (_super) {
  23154. __extends(TorusKnot, _super);
  23155. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23156. this.radius = radius;
  23157. this.tube = tube;
  23158. this.radialSegments = radialSegments;
  23159. this.tubularSegments = tubularSegments;
  23160. this.p = p;
  23161. this.q = q;
  23162. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23163. }
  23164. TorusKnot.prototype._regenerateVertexData = function () {
  23165. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23166. };
  23167. TorusKnot.prototype.copy = function (id) {
  23168. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23169. };
  23170. return TorusKnot;
  23171. })(_Primitive);
  23172. Primitives.TorusKnot = TorusKnot;
  23173. })(Geometry.Primitives || (Geometry.Primitives = {}));
  23174. var Primitives = Geometry.Primitives;
  23175. })(BABYLON.Geometry || (BABYLON.Geometry = {}));
  23176. var Geometry = BABYLON.Geometry;
  23177. })(BABYLON || (BABYLON = {}));
  23178. //# sourceMappingURL=babylon.geometry.js.map
  23179. var BABYLON;
  23180. (function (BABYLON) {
  23181. var Gamepads = (function () {
  23182. function Gamepads(ongamedpadconnected) {
  23183. var _this = this;
  23184. this.babylonGamepads = [];
  23185. this.oneGamepadConnected = false;
  23186. this.isMonitoring = false;
  23187. this.gamepadEventSupported = 'GamepadEvent' in window;
  23188. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23189. 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=";
  23190. this._callbackGamepadConnected = ongamedpadconnected;
  23191. if (this.gamepadSupportAvailable) {
  23192. // Checking if the gamepad connected event is supported (like in Firefox)
  23193. if (this.gamepadEventSupported) {
  23194. window.addEventListener('gamepadconnected', function (evt) {
  23195. _this._onGamepadConnected(evt);
  23196. }, false);
  23197. window.addEventListener('gamepaddisconnected', function (evt) {
  23198. _this._onGamepadDisconnected(evt);
  23199. }, false);
  23200. } else {
  23201. this._startMonitoringGamepads();
  23202. }
  23203. if (!this.oneGamepadConnected) {
  23204. this._insertGamepadDOMInstructions();
  23205. }
  23206. } else {
  23207. this._insertGamepadDOMNotSupported();
  23208. }
  23209. }
  23210. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23211. Gamepads.gamepadDOMInfo = document.createElement("div");
  23212. var buttonAImage = document.createElement("img");
  23213. buttonAImage.src = this.buttonADataURL;
  23214. var spanMessage = document.createElement("span");
  23215. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23216. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23217. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23218. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23219. Gamepads.gamepadDOMInfo.style.width = "100%";
  23220. Gamepads.gamepadDOMInfo.style.height = "48px";
  23221. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23222. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23223. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23224. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23225. buttonAImage.style.position = "relative";
  23226. buttonAImage.style.bottom = "8px";
  23227. spanMessage.style.position = "relative";
  23228. spanMessage.style.fontSize = "32px";
  23229. spanMessage.style.bottom = "32px";
  23230. spanMessage.style.color = "green";
  23231. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23232. };
  23233. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23234. Gamepads.gamepadDOMInfo = document.createElement("div");
  23235. var spanMessage = document.createElement("span");
  23236. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23237. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23238. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23239. Gamepads.gamepadDOMInfo.style.width = "100%";
  23240. Gamepads.gamepadDOMInfo.style.height = "40px";
  23241. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23242. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23243. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23244. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23245. spanMessage.style.position = "relative";
  23246. spanMessage.style.fontSize = "32px";
  23247. spanMessage.style.color = "red";
  23248. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23249. };
  23250. Gamepads.prototype.dispose = function () {
  23251. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23252. };
  23253. Gamepads.prototype._onGamepadConnected = function (evt) {
  23254. var newGamepad = this._addNewGamepad(evt.gamepad);
  23255. if (this._callbackGamepadConnected)
  23256. this._callbackGamepadConnected(newGamepad);
  23257. this._startMonitoringGamepads();
  23258. };
  23259. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23260. if (!this.oneGamepadConnected) {
  23261. this.oneGamepadConnected = true;
  23262. if (Gamepads.gamepadDOMInfo) {
  23263. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23264. Gamepads.gamepadDOMInfo = null;
  23265. }
  23266. }
  23267. var newGamepad;
  23268. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23269. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23270. } else {
  23271. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23272. }
  23273. this.babylonGamepads.push(newGamepad);
  23274. return newGamepad;
  23275. };
  23276. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23277. for (var i in this.babylonGamepads) {
  23278. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23279. this.babylonGamepads.splice(i, 1);
  23280. break;
  23281. }
  23282. }
  23283. // If no gamepads are left, stop the polling loop.
  23284. if (this.babylonGamepads.length == 0) {
  23285. this._stopMonitoringGamepads();
  23286. }
  23287. };
  23288. Gamepads.prototype._startMonitoringGamepads = function () {
  23289. if (!this.isMonitoring) {
  23290. this.isMonitoring = true;
  23291. this._checkGamepadsStatus();
  23292. }
  23293. };
  23294. Gamepads.prototype._stopMonitoringGamepads = function () {
  23295. this.isMonitoring = false;
  23296. };
  23297. Gamepads.prototype._checkGamepadsStatus = function () {
  23298. var _this = this;
  23299. // updating gamepad objects
  23300. this._updateGamepadObjects();
  23301. for (var i in this.babylonGamepads) {
  23302. this.babylonGamepads[i].update();
  23303. }
  23304. if (this.isMonitoring) {
  23305. if (window.requestAnimationFrame) {
  23306. window.requestAnimationFrame(function () {
  23307. _this._checkGamepadsStatus();
  23308. });
  23309. } else if (window.mozRequestAnimationFrame) {
  23310. window.mozRequestAnimationFrame(function () {
  23311. _this._checkGamepadsStatus();
  23312. });
  23313. } else if (window.webkitRequestAnimationFrame) {
  23314. window.webkitRequestAnimationFrame(function () {
  23315. _this._checkGamepadsStatus();
  23316. });
  23317. }
  23318. }
  23319. };
  23320. // This function is called only on Chrome, which does not yet support
  23321. // connection/disconnection events, but requires you to monitor
  23322. // an array for changes.
  23323. Gamepads.prototype._updateGamepadObjects = function () {
  23324. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23325. for (var i = 0; i < gamepads.length; i++) {
  23326. if (gamepads[i]) {
  23327. if (!(gamepads[i].index in this.babylonGamepads)) {
  23328. var newGamepad = this._addNewGamepad(gamepads[i]);
  23329. if (this._callbackGamepadConnected) {
  23330. this._callbackGamepadConnected(newGamepad);
  23331. }
  23332. } else {
  23333. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23334. }
  23335. }
  23336. }
  23337. };
  23338. return Gamepads;
  23339. })();
  23340. BABYLON.Gamepads = Gamepads;
  23341. var StickValues = (function () {
  23342. function StickValues(x, y) {
  23343. this.x = x;
  23344. this.y = y;
  23345. }
  23346. return StickValues;
  23347. })();
  23348. BABYLON.StickValues = StickValues;
  23349. var Gamepad = (function () {
  23350. function Gamepad(id, index, browserGamepad) {
  23351. this.id = id;
  23352. this.index = index;
  23353. this.browserGamepad = browserGamepad;
  23354. if (this.browserGamepad.axes.length >= 2) {
  23355. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23356. }
  23357. if (this.browserGamepad.axes.length >= 4) {
  23358. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23359. }
  23360. }
  23361. Gamepad.prototype.onleftstickchanged = function (callback) {
  23362. this._onleftstickchanged = callback;
  23363. };
  23364. Gamepad.prototype.onrightstickchanged = function (callback) {
  23365. this._onrightstickchanged = callback;
  23366. };
  23367. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23368. get: function () {
  23369. return this._leftStick;
  23370. },
  23371. set: function (newValues) {
  23372. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23373. this._onleftstickchanged(newValues);
  23374. }
  23375. this._leftStick = newValues;
  23376. },
  23377. enumerable: true,
  23378. configurable: true
  23379. });
  23380. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23381. get: function () {
  23382. return this._rightStick;
  23383. },
  23384. set: function (newValues) {
  23385. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23386. this._onrightstickchanged(newValues);
  23387. }
  23388. this._rightStick = newValues;
  23389. },
  23390. enumerable: true,
  23391. configurable: true
  23392. });
  23393. Gamepad.prototype.update = function () {
  23394. if (this._leftStick) {
  23395. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23396. }
  23397. if (this._rightStick) {
  23398. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23399. }
  23400. };
  23401. return Gamepad;
  23402. })();
  23403. BABYLON.Gamepad = Gamepad;
  23404. var GenericPad = (function (_super) {
  23405. __extends(GenericPad, _super);
  23406. function GenericPad(id, index, gamepad) {
  23407. _super.call(this, id, index, gamepad);
  23408. this.id = id;
  23409. this.index = index;
  23410. this.gamepad = gamepad;
  23411. this._buttons = new Array(gamepad.buttons.length);
  23412. }
  23413. GenericPad.prototype.onbuttondown = function (callback) {
  23414. this._onbuttondown = callback;
  23415. };
  23416. GenericPad.prototype.onbuttonup = function (callback) {
  23417. this._onbuttonup = callback;
  23418. };
  23419. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23420. if (newValue !== currentValue) {
  23421. if (this._onbuttondown && newValue === 1) {
  23422. this._onbuttondown(buttonIndex);
  23423. }
  23424. if (this._onbuttonup && newValue === 0) {
  23425. this._onbuttonup(buttonIndex);
  23426. }
  23427. }
  23428. return newValue;
  23429. };
  23430. GenericPad.prototype.update = function () {
  23431. _super.prototype.update.call(this);
  23432. for (var index = 0; index < this._buttons.length; index++) {
  23433. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23434. }
  23435. };
  23436. return GenericPad;
  23437. })(Gamepad);
  23438. BABYLON.GenericPad = GenericPad;
  23439. (function (Xbox360Button) {
  23440. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23441. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23442. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23443. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23444. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23445. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23446. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23447. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23448. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23449. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23450. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23451. var Xbox360Button = BABYLON.Xbox360Button;
  23452. (function (Xbox360Dpad) {
  23453. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23454. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23455. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23456. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23457. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23458. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23459. var Xbox360Pad = (function (_super) {
  23460. __extends(Xbox360Pad, _super);
  23461. function Xbox360Pad() {
  23462. _super.apply(this, arguments);
  23463. this._leftTrigger = 0;
  23464. this._rightTrigger = 0;
  23465. this._buttonA = 0;
  23466. this._buttonB = 0;
  23467. this._buttonX = 0;
  23468. this._buttonY = 0;
  23469. this._buttonBack = 0;
  23470. this._buttonStart = 0;
  23471. this._buttonLB = 0;
  23472. this._buttonRB = 0;
  23473. this._buttonLeftStick = 0;
  23474. this._buttonRightStick = 0;
  23475. this._dPadUp = 0;
  23476. this._dPadDown = 0;
  23477. this._dPadLeft = 0;
  23478. this._dPadRight = 0;
  23479. }
  23480. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23481. this._onlefttriggerchanged = callback;
  23482. };
  23483. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23484. this._onrighttriggerchanged = callback;
  23485. };
  23486. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23487. get: function () {
  23488. return this._leftTrigger;
  23489. },
  23490. set: function (newValue) {
  23491. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23492. this._onlefttriggerchanged(newValue);
  23493. }
  23494. this._leftTrigger = newValue;
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23500. get: function () {
  23501. return this._rightTrigger;
  23502. },
  23503. set: function (newValue) {
  23504. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23505. this._onrighttriggerchanged(newValue);
  23506. }
  23507. this._rightTrigger = newValue;
  23508. },
  23509. enumerable: true,
  23510. configurable: true
  23511. });
  23512. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23513. this._onbuttondown = callback;
  23514. };
  23515. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23516. this._onbuttonup = callback;
  23517. };
  23518. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23519. this._ondpaddown = callback;
  23520. };
  23521. Xbox360Pad.prototype.ondpadup = function (callback) {
  23522. this._ondpadup = callback;
  23523. };
  23524. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23525. if (newValue !== currentValue) {
  23526. if (this._onbuttondown && newValue === 1) {
  23527. this._onbuttondown(buttonType);
  23528. }
  23529. if (this._onbuttonup && newValue === 0) {
  23530. this._onbuttonup(buttonType);
  23531. }
  23532. }
  23533. return newValue;
  23534. };
  23535. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23536. if (newValue !== currentValue) {
  23537. if (this._ondpaddown && newValue === 1) {
  23538. this._ondpaddown(buttonType);
  23539. }
  23540. if (this._ondpadup && newValue === 0) {
  23541. this._ondpadup(buttonType);
  23542. }
  23543. }
  23544. return newValue;
  23545. };
  23546. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23547. get: function () {
  23548. return this._buttonA;
  23549. },
  23550. set: function (value) {
  23551. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23552. },
  23553. enumerable: true,
  23554. configurable: true
  23555. });
  23556. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23557. get: function () {
  23558. return this._buttonB;
  23559. },
  23560. set: function (value) {
  23561. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23562. },
  23563. enumerable: true,
  23564. configurable: true
  23565. });
  23566. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23567. get: function () {
  23568. return this._buttonX;
  23569. },
  23570. set: function (value) {
  23571. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23572. },
  23573. enumerable: true,
  23574. configurable: true
  23575. });
  23576. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23577. get: function () {
  23578. return this._buttonY;
  23579. },
  23580. set: function (value) {
  23581. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23582. },
  23583. enumerable: true,
  23584. configurable: true
  23585. });
  23586. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23587. get: function () {
  23588. return this._buttonStart;
  23589. },
  23590. set: function (value) {
  23591. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23592. },
  23593. enumerable: true,
  23594. configurable: true
  23595. });
  23596. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23597. get: function () {
  23598. return this._buttonBack;
  23599. },
  23600. set: function (value) {
  23601. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23602. },
  23603. enumerable: true,
  23604. configurable: true
  23605. });
  23606. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23607. get: function () {
  23608. return this._buttonLB;
  23609. },
  23610. set: function (value) {
  23611. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23612. },
  23613. enumerable: true,
  23614. configurable: true
  23615. });
  23616. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23617. get: function () {
  23618. return this._buttonRB;
  23619. },
  23620. set: function (value) {
  23621. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23622. },
  23623. enumerable: true,
  23624. configurable: true
  23625. });
  23626. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23627. get: function () {
  23628. return this._buttonLeftStick;
  23629. },
  23630. set: function (value) {
  23631. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23632. },
  23633. enumerable: true,
  23634. configurable: true
  23635. });
  23636. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23637. get: function () {
  23638. return this._buttonRightStick;
  23639. },
  23640. set: function (value) {
  23641. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23642. },
  23643. enumerable: true,
  23644. configurable: true
  23645. });
  23646. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23647. get: function () {
  23648. return this._dPadUp;
  23649. },
  23650. set: function (value) {
  23651. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23652. },
  23653. enumerable: true,
  23654. configurable: true
  23655. });
  23656. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23657. get: function () {
  23658. return this._dPadDown;
  23659. },
  23660. set: function (value) {
  23661. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23662. },
  23663. enumerable: true,
  23664. configurable: true
  23665. });
  23666. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23667. get: function () {
  23668. return this._dPadLeft;
  23669. },
  23670. set: function (value) {
  23671. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23672. },
  23673. enumerable: true,
  23674. configurable: true
  23675. });
  23676. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23677. get: function () {
  23678. return this._dPadRight;
  23679. },
  23680. set: function (value) {
  23681. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23682. },
  23683. enumerable: true,
  23684. configurable: true
  23685. });
  23686. Xbox360Pad.prototype.update = function () {
  23687. _super.prototype.update.call(this);
  23688. this.buttonA = this.browserGamepad.buttons[0].value;
  23689. this.buttonB = this.browserGamepad.buttons[1].value;
  23690. this.buttonX = this.browserGamepad.buttons[2].value;
  23691. this.buttonY = this.browserGamepad.buttons[3].value;
  23692. this.buttonLB = this.browserGamepad.buttons[4].value;
  23693. this.buttonRB = this.browserGamepad.buttons[5].value;
  23694. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23695. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23696. this.buttonBack = this.browserGamepad.buttons[8].value;
  23697. this.buttonStart = this.browserGamepad.buttons[9].value;
  23698. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23699. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23700. this.dPadUp = this.browserGamepad.buttons[12].value;
  23701. this.dPadDown = this.browserGamepad.buttons[13].value;
  23702. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23703. this.dPadRight = this.browserGamepad.buttons[15].value;
  23704. };
  23705. return Xbox360Pad;
  23706. })(Gamepad);
  23707. BABYLON.Xbox360Pad = Xbox360Pad;
  23708. })(BABYLON || (BABYLON = {}));
  23709. //# sourceMappingURL=babylon.gamepads.js.map
  23710. var BABYLON;
  23711. (function (BABYLON) {
  23712. // We're mainly based on the logic defined into the FreeCamera code
  23713. var GamepadCamera = (function (_super) {
  23714. __extends(GamepadCamera, _super);
  23715. function GamepadCamera(name, position, scene) {
  23716. var _this = this;
  23717. _super.call(this, name, position, scene);
  23718. this.angularSensibility = 200;
  23719. this.moveSensibility = 75;
  23720. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23721. _this._onNewGameConnected(gamepad);
  23722. });
  23723. }
  23724. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23725. // Only the first gamepad can control the camera
  23726. if (gamepad.index === 0) {
  23727. this._gamepad = gamepad;
  23728. }
  23729. };
  23730. GamepadCamera.prototype._checkInputs = function () {
  23731. if (!this._gamepad) {
  23732. return;
  23733. }
  23734. var LSValues = this._gamepad.leftStick;
  23735. var normalizedLX = LSValues.x / this.moveSensibility;
  23736. var normalizedLY = LSValues.y / this.moveSensibility;
  23737. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23738. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23739. var RSValues = this._gamepad.rightStick;
  23740. var normalizedRX = RSValues.x / this.angularSensibility;
  23741. var normalizedRY = RSValues.y / this.angularSensibility;
  23742. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23743. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23744. ;
  23745. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23746. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23747. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  23748. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  23749. };
  23750. GamepadCamera.prototype.dispose = function () {
  23751. this._gamepads.dispose();
  23752. _super.prototype.dispose.call(this);
  23753. };
  23754. return GamepadCamera;
  23755. })(BABYLON.FreeCamera);
  23756. BABYLON.GamepadCamera = GamepadCamera;
  23757. })(BABYLON || (BABYLON = {}));
  23758. //# sourceMappingURL=babylon.gamepadCamera.js.map
  23759. var BABYLON;
  23760. (function (BABYLON) {
  23761. var LinesMesh = (function (_super) {
  23762. __extends(LinesMesh, _super);
  23763. function LinesMesh(name, scene, updatable) {
  23764. if (typeof updatable === "undefined") { updatable = false; }
  23765. _super.call(this, name, scene);
  23766. this.color = new BABYLON.Color3(1, 1, 1);
  23767. this.alpha = 1;
  23768. this._indices = new Array();
  23769. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23770. attributes: ["position"],
  23771. uniforms: ["worldViewProjection", "color"],
  23772. needAlphaBlending: true
  23773. });
  23774. }
  23775. Object.defineProperty(LinesMesh.prototype, "material", {
  23776. get: function () {
  23777. return this._colorShader;
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  23783. get: function () {
  23784. return false;
  23785. },
  23786. enumerable: true,
  23787. configurable: true
  23788. });
  23789. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  23790. get: function () {
  23791. return false;
  23792. },
  23793. enumerable: true,
  23794. configurable: true
  23795. });
  23796. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  23797. var engine = this.getScene().getEngine();
  23798. var indexToBind = this._geometry.getIndexBuffer();
  23799. // VBOs
  23800. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  23801. // Color
  23802. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  23803. };
  23804. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  23805. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  23806. return;
  23807. }
  23808. var engine = this.getScene().getEngine();
  23809. // Draw order
  23810. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  23811. };
  23812. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  23813. return null;
  23814. };
  23815. LinesMesh.prototype.dispose = function (doNotRecurse) {
  23816. this._colorShader.dispose();
  23817. _super.prototype.dispose.call(this, doNotRecurse);
  23818. };
  23819. return LinesMesh;
  23820. })(BABYLON.Mesh);
  23821. BABYLON.LinesMesh = LinesMesh;
  23822. })(BABYLON || (BABYLON = {}));
  23823. //# sourceMappingURL=babylon.linesMesh.js.map
  23824. var BABYLON;
  23825. (function (BABYLON) {
  23826. var OutlineRenderer = (function () {
  23827. function OutlineRenderer(scene) {
  23828. this._scene = scene;
  23829. }
  23830. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  23831. if (typeof useOverlay === "undefined") { useOverlay = false; }
  23832. var scene = this._scene;
  23833. var engine = this._scene.getEngine();
  23834. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  23835. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  23836. return;
  23837. }
  23838. var mesh = subMesh.getRenderingMesh();
  23839. var material = subMesh.getMaterial();
  23840. engine.enableEffect(this._effect);
  23841. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  23842. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  23843. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  23844. // Bones
  23845. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  23846. if (useBones) {
  23847. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  23848. }
  23849. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  23850. // Alpha test
  23851. if (material && material.needAlphaTesting()) {
  23852. var alphaTexture = material.getAlphaTestTexture();
  23853. this._effect.setTexture("diffuseSampler", alphaTexture);
  23854. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  23855. }
  23856. if (hardwareInstancedRendering) {
  23857. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  23858. } else {
  23859. if (batch.renderSelf[subMesh._id]) {
  23860. this._effect.setMatrix("world", mesh.getWorldMatrix());
  23861. // Draw
  23862. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23863. }
  23864. if (batch.visibleInstances[subMesh._id]) {
  23865. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  23866. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  23867. this._effect.setMatrix("world", instance.getWorldMatrix());
  23868. // Draw
  23869. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  23870. }
  23871. }
  23872. }
  23873. };
  23874. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  23875. var defines = [];
  23876. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  23877. var mesh = subMesh.getMesh();
  23878. var material = subMesh.getMaterial();
  23879. // Alpha test
  23880. if (material && material.needAlphaTesting()) {
  23881. defines.push("#define ALPHATEST");
  23882. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  23883. attribs.push(BABYLON.VertexBuffer.UVKind);
  23884. defines.push("#define UV1");
  23885. }
  23886. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  23887. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  23888. defines.push("#define UV2");
  23889. }
  23890. }
  23891. // Bones
  23892. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23893. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  23894. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  23895. defines.push("#define BONES");
  23896. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  23897. }
  23898. // Instances
  23899. if (useInstances) {
  23900. defines.push("#define INSTANCES");
  23901. attribs.push("world0");
  23902. attribs.push("world1");
  23903. attribs.push("world2");
  23904. attribs.push("world3");
  23905. }
  23906. // Get correct effect
  23907. var join = defines.join("\n");
  23908. if (this._cachedDefines != join) {
  23909. this._cachedDefines = join;
  23910. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  23911. }
  23912. return this._effect.isReady();
  23913. };
  23914. return OutlineRenderer;
  23915. })();
  23916. BABYLON.OutlineRenderer = OutlineRenderer;
  23917. })(BABYLON || (BABYLON = {}));
  23918. //# sourceMappingURL=babylon.outlineRenderer.js.map
  23919. var BABYLON;
  23920. (function (BABYLON) {
  23921. var MeshAssetTask = (function () {
  23922. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  23923. this.name = name;
  23924. this.meshesNames = meshesNames;
  23925. this.rootUrl = rootUrl;
  23926. this.sceneFilename = sceneFilename;
  23927. this.isCompleted = false;
  23928. }
  23929. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23930. var _this = this;
  23931. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  23932. _this.loadedMeshes = meshes;
  23933. _this.loadedParticleSystems = particleSystems;
  23934. _this.loadedSkeletons = skeletons;
  23935. _this.isCompleted = true;
  23936. if (_this.onSuccess) {
  23937. _this.onSuccess(_this);
  23938. }
  23939. onSuccess();
  23940. }, null, function () {
  23941. if (_this.onError) {
  23942. _this.onError(_this);
  23943. }
  23944. onError();
  23945. });
  23946. };
  23947. return MeshAssetTask;
  23948. })();
  23949. BABYLON.MeshAssetTask = MeshAssetTask;
  23950. var TextFileAssetTask = (function () {
  23951. function TextFileAssetTask(name, url) {
  23952. this.name = name;
  23953. this.url = url;
  23954. this.isCompleted = false;
  23955. }
  23956. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23957. var _this = this;
  23958. BABYLON.Tools.LoadFile(this.url, function (data) {
  23959. _this.text = data;
  23960. _this.isCompleted = true;
  23961. if (_this.onSuccess) {
  23962. _this.onSuccess(_this);
  23963. }
  23964. onSuccess();
  23965. }, null, scene.database, false, function () {
  23966. if (_this.onError) {
  23967. _this.onError(_this);
  23968. }
  23969. onError();
  23970. });
  23971. };
  23972. return TextFileAssetTask;
  23973. })();
  23974. BABYLON.TextFileAssetTask = TextFileAssetTask;
  23975. var BinaryFileAssetTask = (function () {
  23976. function BinaryFileAssetTask(name, url) {
  23977. this.name = name;
  23978. this.url = url;
  23979. this.isCompleted = false;
  23980. }
  23981. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  23982. var _this = this;
  23983. BABYLON.Tools.LoadFile(this.url, function (data) {
  23984. _this.data = data;
  23985. _this.isCompleted = true;
  23986. if (_this.onSuccess) {
  23987. _this.onSuccess(_this);
  23988. }
  23989. onSuccess();
  23990. }, null, scene.database, true, function () {
  23991. if (_this.onError) {
  23992. _this.onError(_this);
  23993. }
  23994. onError();
  23995. });
  23996. };
  23997. return BinaryFileAssetTask;
  23998. })();
  23999. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24000. var ImageAssetTask = (function () {
  24001. function ImageAssetTask(name, url) {
  24002. this.name = name;
  24003. this.url = url;
  24004. this.isCompleted = false;
  24005. }
  24006. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24007. var _this = this;
  24008. var img = new Image();
  24009. img.onload = function () {
  24010. _this.image = img;
  24011. _this.isCompleted = true;
  24012. if (_this.onSuccess) {
  24013. _this.onSuccess(_this);
  24014. }
  24015. onSuccess();
  24016. };
  24017. img.onerror = function () {
  24018. if (_this.onError) {
  24019. _this.onError(_this);
  24020. }
  24021. onError();
  24022. };
  24023. img.src = this.url;
  24024. };
  24025. return ImageAssetTask;
  24026. })();
  24027. BABYLON.ImageAssetTask = ImageAssetTask;
  24028. var TextureAssetTask = (function () {
  24029. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24030. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24031. this.name = name;
  24032. this.url = url;
  24033. this.noMipmap = noMipmap;
  24034. this.invertY = invertY;
  24035. this.samplingMode = samplingMode;
  24036. this.isCompleted = false;
  24037. }
  24038. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24039. var _this = this;
  24040. var onload = function () {
  24041. _this.isCompleted = true;
  24042. if (_this.onSuccess) {
  24043. _this.onSuccess(_this);
  24044. }
  24045. onSuccess();
  24046. };
  24047. var onerror = function () {
  24048. if (_this.onError) {
  24049. _this.onError(_this);
  24050. }
  24051. onError();
  24052. };
  24053. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24054. };
  24055. return TextureAssetTask;
  24056. })();
  24057. BABYLON.TextureAssetTask = TextureAssetTask;
  24058. var AssetsManager = (function () {
  24059. function AssetsManager(scene) {
  24060. this._tasks = new Array();
  24061. this._waitingTasksCount = 0;
  24062. this.useDefaultLoadingScreen = true;
  24063. this._scene = scene;
  24064. }
  24065. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24066. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24067. this._tasks.push(task);
  24068. return task;
  24069. };
  24070. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24071. var task = new TextFileAssetTask(taskName, url);
  24072. this._tasks.push(task);
  24073. return task;
  24074. };
  24075. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24076. var task = new BinaryFileAssetTask(taskName, url);
  24077. this._tasks.push(task);
  24078. return task;
  24079. };
  24080. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24081. var task = new ImageAssetTask(taskName, url);
  24082. this._tasks.push(task);
  24083. return task;
  24084. };
  24085. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24086. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24087. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24088. this._tasks.push(task);
  24089. return task;
  24090. };
  24091. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24092. this._waitingTasksCount--;
  24093. if (this._waitingTasksCount === 0) {
  24094. if (this.onFinish) {
  24095. this.onFinish(this._tasks);
  24096. }
  24097. this._scene.getEngine().hideLoadingUI();
  24098. }
  24099. };
  24100. AssetsManager.prototype._runTask = function (task) {
  24101. var _this = this;
  24102. task.run(this._scene, function () {
  24103. if (_this.onTaskSuccess) {
  24104. _this.onTaskSuccess(task);
  24105. }
  24106. _this._decreaseWaitingTasksCount();
  24107. }, function () {
  24108. if (_this.onTaskError) {
  24109. _this.onTaskError(task);
  24110. }
  24111. _this._decreaseWaitingTasksCount();
  24112. });
  24113. };
  24114. AssetsManager.prototype.reset = function () {
  24115. this._tasks = new Array();
  24116. return this;
  24117. };
  24118. AssetsManager.prototype.load = function () {
  24119. this._waitingTasksCount = this._tasks.length;
  24120. if (this._waitingTasksCount === 0) {
  24121. if (this.onFinish) {
  24122. this.onFinish(this._tasks);
  24123. }
  24124. return this;
  24125. }
  24126. if (this.useDefaultLoadingScreen) {
  24127. this._scene.getEngine().displayLoadingUI();
  24128. }
  24129. for (var index = 0; index < this._tasks.length; index++) {
  24130. var task = this._tasks[index];
  24131. this._runTask(task);
  24132. }
  24133. return this;
  24134. };
  24135. return AssetsManager;
  24136. })();
  24137. BABYLON.AssetsManager = AssetsManager;
  24138. })(BABYLON || (BABYLON = {}));
  24139. //# sourceMappingURL=babylon.assetsManager.js.map
  24140. var BABYLON;
  24141. (function (BABYLON) {
  24142. var VRDeviceOrientationCamera = (function (_super) {
  24143. __extends(VRDeviceOrientationCamera, _super);
  24144. function VRDeviceOrientationCamera(name, position, scene) {
  24145. _super.call(this, name, position, scene);
  24146. this._alpha = 0;
  24147. this._beta = 0;
  24148. this._gamma = 0;
  24149. }
  24150. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24151. this._alpha = +evt.alpha | 0;
  24152. this._beta = +evt.beta | 0;
  24153. this._gamma = +evt.gamma | 0;
  24154. if (this._gamma < 0) {
  24155. this._gamma = 90 + this._gamma;
  24156. } else {
  24157. // Incline it in the correct angle.
  24158. this._gamma = 270 - this._gamma;
  24159. }
  24160. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24161. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24162. this.rotation.z = this._beta / 180.0 * Math.PI;
  24163. };
  24164. return VRDeviceOrientationCamera;
  24165. })(BABYLON.OculusCamera);
  24166. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24167. })(BABYLON || (BABYLON = {}));
  24168. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24169. var BABYLON;
  24170. (function (BABYLON) {
  24171. var WebVRCamera = (function (_super) {
  24172. __extends(WebVRCamera, _super);
  24173. function WebVRCamera(name, position, scene) {
  24174. _super.call(this, name, position, scene);
  24175. this._hmdDevice = null;
  24176. this._sensorDevice = null;
  24177. this._cacheState = null;
  24178. this._cacheQuaternion = new BABYLON.Quaternion();
  24179. this._cacheRotation = BABYLON.Vector3.Zero();
  24180. this._vrEnabled = false;
  24181. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24182. }
  24183. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24184. var size = devices.length;
  24185. var i = 0;
  24186. // Reset devices.
  24187. this._sensorDevice = null;
  24188. this._hmdDevice = null;
  24189. while (i < size && this._hmdDevice === null) {
  24190. if (devices[i] instanceof HMDVRDevice) {
  24191. this._hmdDevice = devices[i];
  24192. }
  24193. i++;
  24194. }
  24195. i = 0;
  24196. while (i < size && this._sensorDevice === null) {
  24197. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24198. this._sensorDevice = devices[i];
  24199. }
  24200. i++;
  24201. }
  24202. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24203. };
  24204. WebVRCamera.prototype._update = function () {
  24205. if (this._vrEnabled) {
  24206. this._cacheState = this._sensorDevice.getState();
  24207. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24208. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24209. this.rotation.x = -this._cacheRotation.z;
  24210. this.rotation.y = -this._cacheRotation.y;
  24211. this.rotation.z = this._cacheRotation.x;
  24212. }
  24213. _super.prototype._update.call(this);
  24214. };
  24215. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24216. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24217. if (navigator.getVRDevices) {
  24218. navigator.getVRDevices().then(this._getWebVRDevices);
  24219. } else if (navigator.mozGetVRDevices) {
  24220. navigator.mozGetVRDevices(this._getWebVRDevices);
  24221. }
  24222. };
  24223. WebVRCamera.prototype.detachControl = function (element) {
  24224. _super.prototype.detachControl.call(this, element);
  24225. this._vrEnabled = false;
  24226. };
  24227. return WebVRCamera;
  24228. })(BABYLON.OculusCamera);
  24229. BABYLON.WebVRCamera = WebVRCamera;
  24230. })(BABYLON || (BABYLON = {}));
  24231. //# sourceMappingURL=babylon.webVRCamera.js.map
  24232. var BABYLON;
  24233. (function (BABYLON) {
  24234. // Standard optimizations
  24235. var SceneOptimization = (function () {
  24236. function SceneOptimization(priority) {
  24237. if (typeof priority === "undefined") { priority = 0; }
  24238. this.priority = priority;
  24239. this.apply = function (scene) {
  24240. return true;
  24241. };
  24242. }
  24243. return SceneOptimization;
  24244. })();
  24245. BABYLON.SceneOptimization = SceneOptimization;
  24246. var TextureOptimization = (function (_super) {
  24247. __extends(TextureOptimization, _super);
  24248. function TextureOptimization(priority, maximumSize) {
  24249. if (typeof priority === "undefined") { priority = 0; }
  24250. if (typeof maximumSize === "undefined") { maximumSize = 1024; }
  24251. var _this = this;
  24252. _super.call(this, priority);
  24253. this.priority = priority;
  24254. this.maximumSize = maximumSize;
  24255. this.apply = function (scene) {
  24256. var allDone = true;
  24257. for (var index = 0; index < scene.textures.length; index++) {
  24258. var texture = scene.textures[index];
  24259. if (!texture.canRescale) {
  24260. continue;
  24261. }
  24262. var currentSize = texture.getSize();
  24263. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24264. if (maxDimension > _this.maximumSize) {
  24265. texture.scale(0.5);
  24266. allDone = false;
  24267. }
  24268. }
  24269. return allDone;
  24270. };
  24271. }
  24272. return TextureOptimization;
  24273. })(SceneOptimization);
  24274. BABYLON.TextureOptimization = TextureOptimization;
  24275. var HardwareScalingOptimization = (function (_super) {
  24276. __extends(HardwareScalingOptimization, _super);
  24277. function HardwareScalingOptimization(priority, maximumScale) {
  24278. if (typeof priority === "undefined") { priority = 0; }
  24279. if (typeof maximumScale === "undefined") { maximumScale = 2; }
  24280. var _this = this;
  24281. _super.call(this, priority);
  24282. this.priority = priority;
  24283. this.maximumScale = maximumScale;
  24284. this._currentScale = 1;
  24285. this.apply = function (scene) {
  24286. _this._currentScale++;
  24287. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24288. return _this._currentScale >= _this.maximumScale;
  24289. };
  24290. }
  24291. return HardwareScalingOptimization;
  24292. })(SceneOptimization);
  24293. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24294. var ShadowsOptimization = (function (_super) {
  24295. __extends(ShadowsOptimization, _super);
  24296. function ShadowsOptimization() {
  24297. _super.apply(this, arguments);
  24298. this.apply = function (scene) {
  24299. scene.shadowsEnabled = false;
  24300. return true;
  24301. };
  24302. }
  24303. return ShadowsOptimization;
  24304. })(SceneOptimization);
  24305. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24306. var PostProcessesOptimization = (function (_super) {
  24307. __extends(PostProcessesOptimization, _super);
  24308. function PostProcessesOptimization() {
  24309. _super.apply(this, arguments);
  24310. this.apply = function (scene) {
  24311. scene.postProcessesEnabled = false;
  24312. return true;
  24313. };
  24314. }
  24315. return PostProcessesOptimization;
  24316. })(SceneOptimization);
  24317. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24318. var LensFlaresOptimization = (function (_super) {
  24319. __extends(LensFlaresOptimization, _super);
  24320. function LensFlaresOptimization() {
  24321. _super.apply(this, arguments);
  24322. this.apply = function (scene) {
  24323. scene.lensFlaresEnabled = false;
  24324. return true;
  24325. };
  24326. }
  24327. return LensFlaresOptimization;
  24328. })(SceneOptimization);
  24329. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24330. var ParticlesOptimization = (function (_super) {
  24331. __extends(ParticlesOptimization, _super);
  24332. function ParticlesOptimization() {
  24333. _super.apply(this, arguments);
  24334. this.apply = function (scene) {
  24335. scene.particlesEnabled = false;
  24336. return true;
  24337. };
  24338. }
  24339. return ParticlesOptimization;
  24340. })(SceneOptimization);
  24341. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24342. var RenderTargetsOptimization = (function (_super) {
  24343. __extends(RenderTargetsOptimization, _super);
  24344. function RenderTargetsOptimization() {
  24345. _super.apply(this, arguments);
  24346. this.apply = function (scene) {
  24347. scene.renderTargetsEnabled = false;
  24348. return true;
  24349. };
  24350. }
  24351. return RenderTargetsOptimization;
  24352. })(SceneOptimization);
  24353. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24354. var MergeMeshesOptimization = (function (_super) {
  24355. __extends(MergeMeshesOptimization, _super);
  24356. function MergeMeshesOptimization() {
  24357. _super.apply(this, arguments);
  24358. var _this = this;
  24359. this._canBeMerged = function (abstractMesh) {
  24360. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24361. return false;
  24362. }
  24363. var mesh = abstractMesh;
  24364. if (!mesh.isVisible || !mesh.isEnabled()) {
  24365. return false;
  24366. }
  24367. if (mesh.instances.length > 0) {
  24368. return false;
  24369. }
  24370. if (mesh.skeleton || mesh.hasLODLevels) {
  24371. return false;
  24372. }
  24373. return true;
  24374. };
  24375. this.apply = function (scene) {
  24376. var globalPool = scene.meshes.slice(0);
  24377. var globalLength = globalPool.length;
  24378. for (var index = 0; index < globalLength; index++) {
  24379. var currentPool = new Array();
  24380. var current = globalPool[index];
  24381. // Checks
  24382. if (!_this._canBeMerged(current)) {
  24383. continue;
  24384. }
  24385. currentPool.push(current);
  24386. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24387. var otherMesh = globalPool[subIndex];
  24388. if (!_this._canBeMerged(otherMesh)) {
  24389. continue;
  24390. }
  24391. if (otherMesh.material !== current.material) {
  24392. continue;
  24393. }
  24394. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24395. continue;
  24396. }
  24397. currentPool.push(otherMesh);
  24398. globalLength--;
  24399. globalPool.splice(subIndex, 1);
  24400. subIndex--;
  24401. }
  24402. if (currentPool.length < 2) {
  24403. continue;
  24404. }
  24405. // Merge meshes
  24406. BABYLON.Mesh.MergeMeshes(currentPool);
  24407. }
  24408. return true;
  24409. };
  24410. }
  24411. return MergeMeshesOptimization;
  24412. })(SceneOptimization);
  24413. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24414. // Options
  24415. var SceneOptimizerOptions = (function () {
  24416. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24417. if (typeof targetFrameRate === "undefined") { targetFrameRate = 60; }
  24418. if (typeof trackerDuration === "undefined") { trackerDuration = 2000; }
  24419. this.targetFrameRate = targetFrameRate;
  24420. this.trackerDuration = trackerDuration;
  24421. this.optimizations = new Array();
  24422. }
  24423. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24424. var result = new SceneOptimizerOptions(targetFrameRate);
  24425. var priority = 0;
  24426. result.optimizations.push(new MergeMeshesOptimization(priority));
  24427. result.optimizations.push(new ShadowsOptimization(priority));
  24428. result.optimizations.push(new LensFlaresOptimization(priority));
  24429. // Next priority
  24430. priority++;
  24431. result.optimizations.push(new PostProcessesOptimization(priority));
  24432. result.optimizations.push(new ParticlesOptimization(priority));
  24433. // Next priority
  24434. priority++;
  24435. result.optimizations.push(new TextureOptimization(priority, 1024));
  24436. return result;
  24437. };
  24438. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24439. var result = new SceneOptimizerOptions(targetFrameRate);
  24440. var priority = 0;
  24441. result.optimizations.push(new MergeMeshesOptimization(priority));
  24442. result.optimizations.push(new ShadowsOptimization(priority));
  24443. result.optimizations.push(new LensFlaresOptimization(priority));
  24444. // Next priority
  24445. priority++;
  24446. result.optimizations.push(new PostProcessesOptimization(priority));
  24447. result.optimizations.push(new ParticlesOptimization(priority));
  24448. // Next priority
  24449. priority++;
  24450. result.optimizations.push(new TextureOptimization(priority, 512));
  24451. // Next priority
  24452. priority++;
  24453. result.optimizations.push(new RenderTargetsOptimization(priority));
  24454. // Next priority
  24455. priority++;
  24456. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24457. return result;
  24458. };
  24459. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24460. var result = new SceneOptimizerOptions(targetFrameRate);
  24461. var priority = 0;
  24462. result.optimizations.push(new MergeMeshesOptimization(priority));
  24463. result.optimizations.push(new ShadowsOptimization(priority));
  24464. result.optimizations.push(new LensFlaresOptimization(priority));
  24465. // Next priority
  24466. priority++;
  24467. result.optimizations.push(new PostProcessesOptimization(priority));
  24468. result.optimizations.push(new ParticlesOptimization(priority));
  24469. // Next priority
  24470. priority++;
  24471. result.optimizations.push(new TextureOptimization(priority, 256));
  24472. // Next priority
  24473. priority++;
  24474. result.optimizations.push(new RenderTargetsOptimization(priority));
  24475. // Next priority
  24476. priority++;
  24477. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24478. return result;
  24479. };
  24480. return SceneOptimizerOptions;
  24481. })();
  24482. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24483. // Scene optimizer tool
  24484. var SceneOptimizer = (function () {
  24485. function SceneOptimizer() {
  24486. }
  24487. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24488. // TODO: add an epsilon
  24489. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24490. if (onSuccess) {
  24491. onSuccess();
  24492. }
  24493. return;
  24494. }
  24495. // Apply current level of optimizations
  24496. var allDone = true;
  24497. var noOptimizationApplied = true;
  24498. for (var index = 0; index < options.optimizations.length; index++) {
  24499. var optimization = options.optimizations[index];
  24500. if (optimization.priority === currentPriorityLevel) {
  24501. noOptimizationApplied = false;
  24502. allDone = allDone && optimization.apply(scene);
  24503. }
  24504. }
  24505. // If no optimization was applied, this is a failure :(
  24506. if (noOptimizationApplied) {
  24507. if (onFailure) {
  24508. onFailure();
  24509. }
  24510. return;
  24511. }
  24512. // If all optimizations were done, move to next level
  24513. if (allDone) {
  24514. currentPriorityLevel++;
  24515. }
  24516. // Let's the system running for a specific amount of time before checking FPS
  24517. scene.executeWhenReady(function () {
  24518. setTimeout(function () {
  24519. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24520. }, options.trackerDuration);
  24521. });
  24522. };
  24523. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24524. if (!options) {
  24525. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24526. }
  24527. // Let's the system running for a specific amount of time before checking FPS
  24528. scene.executeWhenReady(function () {
  24529. setTimeout(function () {
  24530. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24531. }, options.trackerDuration);
  24532. });
  24533. };
  24534. return SceneOptimizer;
  24535. })();
  24536. BABYLON.SceneOptimizer = SceneOptimizer;
  24537. })(BABYLON || (BABYLON = {}));
  24538. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  24539. var BABYLON;
  24540. (function (BABYLON) {
  24541. (function (Internals) {
  24542. var MeshLODLevel = (function () {
  24543. function MeshLODLevel(distance, mesh) {
  24544. this.distance = distance;
  24545. this.mesh = mesh;
  24546. }
  24547. return MeshLODLevel;
  24548. })();
  24549. Internals.MeshLODLevel = MeshLODLevel;
  24550. })(BABYLON.Internals || (BABYLON.Internals = {}));
  24551. var Internals = BABYLON.Internals;
  24552. })(BABYLON || (BABYLON = {}));
  24553. //# sourceMappingURL=babylon.meshLODLevel.js.map
  24554. var BABYLON;
  24555. (function (BABYLON) {
  24556. var AudioEngine = (function () {
  24557. function AudioEngine() {
  24558. this.audioContext = null;
  24559. this.canUseWebAudio = false;
  24560. try {
  24561. if (typeof AudioContext !== 'undefined') {
  24562. this.audioContext = new AudioContext();
  24563. this.canUseWebAudio = true;
  24564. } else if (typeof webkitAudioContext !== 'undefined') {
  24565. this.audioContext = new webkitAudioContext();
  24566. this.canUseWebAudio = true;
  24567. }
  24568. } catch (e) {
  24569. this.canUseWebAudio = false;
  24570. }
  24571. // create a global volume gain node
  24572. if (this.canUseWebAudio) {
  24573. this.masterGain = this.audioContext.createGain();
  24574. this.masterGain.gain.value = 1;
  24575. this.masterGain.connect(this.audioContext.destination);
  24576. }
  24577. }
  24578. AudioEngine.prototype.getGlobalVolume = function () {
  24579. if (this.canUseWebAudio) {
  24580. return this.masterGain.gain.value;
  24581. } else {
  24582. return -1;
  24583. }
  24584. };
  24585. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24586. if (this.canUseWebAudio) {
  24587. this.masterGain.gain.value = newVolume;
  24588. }
  24589. };
  24590. return AudioEngine;
  24591. })();
  24592. BABYLON.AudioEngine = AudioEngine;
  24593. })(BABYLON || (BABYLON = {}));
  24594. //# sourceMappingURL=babylon.audioengine.js.map
  24595. var BABYLON;
  24596. (function (BABYLON) {
  24597. var Sound = (function () {
  24598. /**
  24599. * Create a sound and attach it to a scene
  24600. * @param name Name of your sound
  24601. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24602. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24603. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24604. */
  24605. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24606. var _this = this;
  24607. this.autoplay = false;
  24608. this.loop = false;
  24609. this.useCustomAttenuation = false;
  24610. this.spatialSound = false;
  24611. this.refDistance = 1;
  24612. this.rolloffFactor = 1;
  24613. this.maxDistance = 100;
  24614. this.distanceModel = "linear";
  24615. this.panningModel = "HRTF";
  24616. this.startTime = 0;
  24617. this.startOffset = 0;
  24618. this._position = BABYLON.Vector3.Zero();
  24619. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24620. this._volume = 1;
  24621. this._isLoaded = false;
  24622. this._isReadyToPlay = false;
  24623. this._isPlaying = false;
  24624. this._isDirectional = false;
  24625. // Used if you'd like to create a directional sound.
  24626. // If not set, the sound will be omnidirectional
  24627. this._coneInnerAngle = 360;
  24628. this._coneOuterAngle = 360;
  24629. this._coneOuterGain = 0;
  24630. this._name = name;
  24631. this._scene = scene;
  24632. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24633. this._readyToPlayCallback = readyToPlayCallback;
  24634. // Default custom attenuation function is a linear attenuation
  24635. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24636. if (currentDistance < maxDistance) {
  24637. return currentVolume * (1 - currentDistance / maxDistance);
  24638. } else {
  24639. return 0;
  24640. }
  24641. };
  24642. if (options) {
  24643. this.autoplay = options.autoplay || false;
  24644. this.loop = options.loop || false;
  24645. this._volume = options.volume || 1;
  24646. this.spatialSound = options.spatialSound || false;
  24647. this.maxDistance = options.maxDistance || 100;
  24648. this.useCustomAttenuation = options.useCustomAttenation || false;
  24649. this.rolloffFactor = options.rolloffFactor || 1;
  24650. this.refDistance = options.refDistance || 1;
  24651. this.distanceModel = options.distanceModel || "linear";
  24652. this.panningModel = options.panningModel || "HRTF";
  24653. }
  24654. if (this._audioEngine.canUseWebAudio) {
  24655. this._soundGain = this._audioEngine.audioContext.createGain();
  24656. this._soundGain.gain.value = this._volume;
  24657. if (this.spatialSound) {
  24658. this._createSpatialParameters();
  24659. } else {
  24660. this._audioNode = this._soundGain;
  24661. }
  24662. this._scene.mainSoundTrack.AddSound(this);
  24663. if (typeof (urlOrArrayBuffer) === "string") {
  24664. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24665. _this._soundLoaded(data);
  24666. }, null, null, true);
  24667. } else {
  24668. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24669. this._soundLoaded(urlOrArrayBuffer);
  24670. } else {
  24671. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24672. }
  24673. }
  24674. }
  24675. }
  24676. Sound.prototype.updateOptions = function (options) {
  24677. if (options) {
  24678. this.loop = options.loop || this.loop;
  24679. this.maxDistance = options.maxDistance || this.maxDistance;
  24680. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24681. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24682. this.refDistance = options.refDistance || this.refDistance;
  24683. this.distanceModel = options.distanceModel || this.distanceModel;
  24684. this.panningModel = options.panningModel || this.panningModel;
  24685. }
  24686. };
  24687. Sound.prototype._createSpatialParameters = function () {
  24688. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24689. if (this.useCustomAttenuation) {
  24690. // Tricks to disable in a way embedded Web Audio attenuation
  24691. this._soundPanner.distanceModel = "linear";
  24692. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24693. this._soundPanner.refDistance = 1;
  24694. this._soundPanner.rolloffFactor = 1;
  24695. this._soundPanner.panningModel = "HRTF";
  24696. } else {
  24697. this._soundPanner.distanceModel = this.distanceModel;
  24698. this._soundPanner.maxDistance = this.maxDistance;
  24699. this._soundPanner.refDistance = this.refDistance;
  24700. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24701. this._soundPanner.panningModel = this.panningModel;
  24702. }
  24703. this._soundPanner.connect(this._soundGain);
  24704. this._audioNode = this._soundPanner;
  24705. };
  24706. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24707. if (this._audioEngine.canUseWebAudio) {
  24708. this._audioNode.disconnect();
  24709. this._audioNode.connect(soundTrackAudioNode);
  24710. }
  24711. };
  24712. /**
  24713. * Transform this sound into a directional source
  24714. * @param coneInnerAngle Size of the inner cone in degree
  24715. * @param coneOuterAngle Size of the outer cone in degree
  24716. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24717. */
  24718. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24719. if (coneOuterAngle < coneInnerAngle) {
  24720. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24721. return;
  24722. }
  24723. this._coneInnerAngle = coneInnerAngle;
  24724. this._coneOuterAngle = coneOuterAngle;
  24725. this._coneOuterGain = coneOuterGain;
  24726. this._isDirectional = true;
  24727. if (this._isPlaying && this.loop) {
  24728. this.stop();
  24729. this.play();
  24730. }
  24731. };
  24732. Sound.prototype.setPosition = function (newPosition) {
  24733. this._position = newPosition;
  24734. if (this._isPlaying && this.spatialSound) {
  24735. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24736. }
  24737. };
  24738. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24739. this._localDirection = newLocalDirection;
  24740. if (this._connectedMesh && this._isPlaying) {
  24741. this._updateDirection();
  24742. }
  24743. };
  24744. Sound.prototype._updateDirection = function () {
  24745. var mat = this._connectedMesh.getWorldMatrix();
  24746. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  24747. direction.normalize();
  24748. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  24749. };
  24750. Sound.prototype.updateDistanceFromListener = function () {
  24751. if (this._connectedMesh && this.useCustomAttenuation) {
  24752. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  24753. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  24754. }
  24755. };
  24756. Sound.prototype.setAttenuationFunction = function (callback) {
  24757. this._customAttenuationFunction = callback;
  24758. };
  24759. /**
  24760. * Play the sound
  24761. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  24762. */
  24763. Sound.prototype.play = function (time) {
  24764. if (this._isReadyToPlay) {
  24765. try {
  24766. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24767. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  24768. this._soundSource.buffer = this._audioBuffer;
  24769. if (this.spatialSound) {
  24770. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24771. if (this._isDirectional) {
  24772. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  24773. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  24774. this._soundPanner.coneOuterGain = this._coneOuterGain;
  24775. if (this._connectedMesh) {
  24776. this._updateDirection();
  24777. } else {
  24778. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  24779. }
  24780. }
  24781. }
  24782. this._soundSource.connect(this._audioNode);
  24783. this._soundSource.loop = this.loop;
  24784. this.startTime = startTime;
  24785. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  24786. this._isPlaying = true;
  24787. } catch (ex) {
  24788. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  24789. }
  24790. }
  24791. };
  24792. /**
  24793. * Stop the sound
  24794. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  24795. */
  24796. Sound.prototype.stop = function (time) {
  24797. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  24798. this._soundSource.stop(stopTime);
  24799. this._isPlaying = false;
  24800. };
  24801. Sound.prototype.pause = function () {
  24802. this._soundSource.stop(0);
  24803. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  24804. };
  24805. Sound.prototype.setVolume = function (newVolume) {
  24806. this._volume = newVolume;
  24807. this._soundGain.gain.value = newVolume;
  24808. };
  24809. Sound.prototype.getVolume = function () {
  24810. return this._volume;
  24811. };
  24812. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  24813. var _this = this;
  24814. this._connectedMesh = meshToConnectTo;
  24815. if (!this.spatialSound) {
  24816. this._createSpatialParameters();
  24817. this.spatialSound = true;
  24818. if (this._isPlaying && this.loop) {
  24819. this.stop();
  24820. this.play();
  24821. }
  24822. }
  24823. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) {
  24824. return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh);
  24825. });
  24826. };
  24827. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  24828. this.setPosition(connectedMesh.position);
  24829. if (this._isDirectional && this._isPlaying) {
  24830. this._updateDirection();
  24831. }
  24832. };
  24833. Sound.prototype._soundLoaded = function (audioData) {
  24834. var _this = this;
  24835. this._isLoaded = true;
  24836. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  24837. _this._audioBuffer = buffer;
  24838. _this._isReadyToPlay = true;
  24839. if (_this.autoplay) {
  24840. _this.play();
  24841. }
  24842. if (_this._readyToPlayCallback) {
  24843. _this._readyToPlayCallback();
  24844. }
  24845. }, function (error) {
  24846. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  24847. });
  24848. };
  24849. return Sound;
  24850. })();
  24851. BABYLON.Sound = Sound;
  24852. })(BABYLON || (BABYLON = {}));
  24853. //# sourceMappingURL=babylon.sound.js.map
  24854. var BABYLON;
  24855. (function (BABYLON) {
  24856. var SoundTrack = (function () {
  24857. function SoundTrack(scene, options) {
  24858. this.id = -1;
  24859. this._isMainTrack = false;
  24860. this._scene = scene;
  24861. this._audioEngine = scene.getEngine().getAudioEngine();
  24862. this.soundCollection = new Array();
  24863. if (this._audioEngine.canUseWebAudio) {
  24864. this._trackGain = this._audioEngine.audioContext.createGain();
  24865. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  24866. //this._trackConvolver.connect(this._trackGain);
  24867. this._trackGain.connect(this._audioEngine.masterGain);
  24868. if (options) {
  24869. if (options.volume) {
  24870. this._trackGain.gain.value = options.volume;
  24871. }
  24872. if (options.mainTrack) {
  24873. this._isMainTrack = options.mainTrack;
  24874. }
  24875. }
  24876. }
  24877. if (!this._isMainTrack) {
  24878. this._scene.soundTracks.push(this);
  24879. this.id = this._scene.soundTracks.length - 1;
  24880. }
  24881. }
  24882. SoundTrack.prototype.AddSound = function (sound) {
  24883. sound.connectToSoundTrackAudioNode(this._trackGain);
  24884. if (sound.soundTrackId) {
  24885. if (sound.soundTrackId === -1) {
  24886. this._scene.mainSoundTrack.RemoveSound(sound);
  24887. } else {
  24888. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  24889. }
  24890. }
  24891. this.soundCollection.push(sound);
  24892. sound.soundTrackId = this.id;
  24893. };
  24894. SoundTrack.prototype.RemoveSound = function (sound) {
  24895. var index = this.soundCollection.indexOf(sound);
  24896. if (index !== -1) {
  24897. this.soundCollection.splice(index, 1);
  24898. }
  24899. };
  24900. SoundTrack.prototype.setVolume = function (newVolume) {
  24901. if (this._audioEngine.canUseWebAudio) {
  24902. this._trackGain.gain.value = newVolume;
  24903. }
  24904. };
  24905. return SoundTrack;
  24906. })();
  24907. BABYLON.SoundTrack = SoundTrack;
  24908. })(BABYLON || (BABYLON = {}));
  24909. //# sourceMappingURL=babylon.soundtrack.js.map
  24910. var BABYLON;
  24911. (function (BABYLON) {
  24912. var DebugLayer = (function () {
  24913. function DebugLayer(scene) {
  24914. var _this = this;
  24915. this._enabled = false;
  24916. this._labelsEnabled = false;
  24917. this._displayStatistics = true;
  24918. this._displayTree = false;
  24919. this._displayLogs = false;
  24920. this._identityMatrix = BABYLON.Matrix.Identity();
  24921. this.axisRatio = 0.02;
  24922. this.accentColor = "orange";
  24923. this._scene = scene;
  24924. this._syncPositions = function () {
  24925. var engine = _this._scene.getEngine();
  24926. var canvasRect = engine.getRenderingCanvasClientRect();
  24927. if (_this._showUI) {
  24928. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  24929. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  24930. _this._statsDiv.style.width = "400px";
  24931. _this._statsDiv.style.height = "auto";
  24932. _this._statsSubsetDiv.style.maxHeight = "240px";
  24933. _this._optionsDiv.style.left = "0px";
  24934. _this._optionsDiv.style.top = "10px";
  24935. _this._optionsDiv.style.width = "200px";
  24936. _this._optionsDiv.style.height = "auto";
  24937. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  24938. _this._logDiv.style.left = "0px";
  24939. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  24940. _this._logDiv.style.width = "600px";
  24941. _this._logDiv.style.height = "160px";
  24942. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  24943. _this._treeDiv.style.top = "10px";
  24944. _this._treeDiv.style.width = "300px";
  24945. _this._treeDiv.style.height = "auto";
  24946. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  24947. }
  24948. _this._globalDiv.style.left = canvasRect.left + "px";
  24949. _this._globalDiv.style.top = canvasRect.top + "px";
  24950. _this._drawingCanvas.style.left = "0px";
  24951. _this._drawingCanvas.style.top = "0px";
  24952. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  24953. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  24954. var devicePixelRatio = window.devicePixelRatio || 1;
  24955. var context = _this._drawingContext;
  24956. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  24957. _this._ratio = devicePixelRatio / backingStoreRatio;
  24958. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  24959. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  24960. };
  24961. this._onCanvasClick = function (evt) {
  24962. _this._clickPosition = {
  24963. x: evt.clientX * _this._ratio,
  24964. y: evt.clientY * _this._ratio
  24965. };
  24966. };
  24967. this._syncData = function () {
  24968. if (_this._showUI) {
  24969. if (_this._displayStatistics) {
  24970. _this._displayStats();
  24971. _this._statsDiv.style.display = "";
  24972. } else {
  24973. _this._statsDiv.style.display = "none";
  24974. }
  24975. if (_this._displayLogs) {
  24976. _this._logDiv.style.display = "";
  24977. } else {
  24978. _this._logDiv.style.display = "none";
  24979. }
  24980. if (_this._displayTree) {
  24981. _this._treeDiv.style.display = "";
  24982. if (_this._needToRefreshMeshesTree) {
  24983. _this._needToRefreshMeshesTree = false;
  24984. _this._refreshMeshesTreeContent();
  24985. }
  24986. } else {
  24987. _this._treeDiv.style.display = "none";
  24988. }
  24989. }
  24990. if (_this._labelsEnabled || !_this._showUI) {
  24991. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  24992. var engine = _this._scene.getEngine();
  24993. var viewport = _this._scene.activeCamera.viewport;
  24994. var globalViewport = viewport.toGlobal(engine);
  24995. // Meshes
  24996. var meshes = _this._scene.getActiveMeshes();
  24997. for (var index = 0; index < meshes.length; index++) {
  24998. var mesh = meshes.data[index];
  24999. var position = mesh.getBoundingInfo().boundingSphere.center;
  25000. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25001. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25002. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25003. }
  25004. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25005. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25006. mesh.renderOverlay = !mesh.renderOverlay;
  25007. }, function () {
  25008. return mesh.renderOverlay ? 'red' : 'black';
  25009. });
  25010. }
  25011. }
  25012. // Cameras
  25013. var cameras = _this._scene.cameras;
  25014. for (index = 0; index < cameras.length; index++) {
  25015. var camera = cameras[index];
  25016. if (camera === _this._scene.activeCamera) {
  25017. continue;
  25018. }
  25019. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25020. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25021. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25022. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25023. _this._scene.activeCamera = camera;
  25024. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25025. }, function () {
  25026. return "purple";
  25027. });
  25028. }
  25029. }
  25030. // Lights
  25031. var lights = _this._scene.lights;
  25032. for (index = 0; index < lights.length; index++) {
  25033. var light = lights[index];
  25034. if (light.position) {
  25035. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25036. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25037. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25038. light.setEnabled(!light.isEnabled());
  25039. }, function () {
  25040. return light.isEnabled() ? "orange" : "gray";
  25041. });
  25042. }
  25043. }
  25044. }
  25045. }
  25046. _this._clickPosition = undefined;
  25047. };
  25048. }
  25049. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25050. while (this._treeSubsetDiv.hasChildNodes()) {
  25051. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25052. }
  25053. // Add meshes
  25054. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25055. sortedArray.sort(function (a, b) {
  25056. if (a.name === b.name) {
  25057. return 0;
  25058. }
  25059. return (a.name > b.name) ? 1 : -1;
  25060. });
  25061. for (var index = 0; index < sortedArray.length; index++) {
  25062. var mesh = sortedArray[index];
  25063. if (!mesh.isEnabled()) {
  25064. continue;
  25065. }
  25066. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25067. m.isVisible = element.checked;
  25068. }, mesh);
  25069. }
  25070. };
  25071. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25072. this._drawingContext.beginPath();
  25073. this._drawingContext.moveTo(zero.x, zero.y);
  25074. this._drawingContext.lineTo(unit.x, unit.y);
  25075. this._drawingContext.strokeStyle = color;
  25076. this._drawingContext.lineWidth = 4;
  25077. this._drawingContext.stroke();
  25078. this._drawingContext.font = "normal 14px Segoe UI";
  25079. this._drawingContext.fillStyle = color;
  25080. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25081. };
  25082. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25083. var position = mesh.getBoundingInfo().boundingSphere.center;
  25084. var worldMatrix = mesh.getWorldMatrix();
  25085. 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());
  25086. var unit = (unprojectedVector.subtract(position)).length();
  25087. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25088. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25089. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25090. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25091. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25092. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25093. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25094. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25095. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25096. };
  25097. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25098. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25099. this._drawingContext.font = "normal 12px Segoe UI";
  25100. var textMetrics = this._drawingContext.measureText(text);
  25101. var centerX = projectedPosition.x - textMetrics.width / 2;
  25102. var centerY = projectedPosition.y;
  25103. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25104. onClick();
  25105. }
  25106. this._drawingContext.beginPath();
  25107. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25108. this._drawingContext.fillStyle = getFillStyle();
  25109. this._drawingContext.globalAlpha = 0.5;
  25110. this._drawingContext.fill();
  25111. this._drawingContext.globalAlpha = 1.0;
  25112. this._drawingContext.strokeStyle = '#FFFFFF';
  25113. this._drawingContext.lineWidth = 1;
  25114. this._drawingContext.stroke();
  25115. this._drawingContext.fillStyle = "#FFFFFF";
  25116. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25117. this._drawingContext.beginPath();
  25118. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25119. this._drawingContext.fill();
  25120. }
  25121. };
  25122. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25123. if (!this._clickPosition) {
  25124. return false;
  25125. }
  25126. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25127. return false;
  25128. }
  25129. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25130. return false;
  25131. }
  25132. return true;
  25133. };
  25134. DebugLayer.prototype.isVisible = function () {
  25135. return this._enabled;
  25136. };
  25137. DebugLayer.prototype.hide = function () {
  25138. if (!this._enabled) {
  25139. return;
  25140. }
  25141. this._enabled = false;
  25142. var engine = this._scene.getEngine();
  25143. this._scene.unregisterAfterRender(this._syncData);
  25144. document.body.removeChild(this._globalDiv);
  25145. window.removeEventListener("resize", this._syncPositions);
  25146. this._scene.forceShowBoundingBoxes = false;
  25147. this._scene.forceWireframe = false;
  25148. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25149. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25150. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25151. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25152. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25153. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25154. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25155. this._scene.shadowsEnabled = true;
  25156. this._scene.particlesEnabled = true;
  25157. this._scene.postProcessesEnabled = true;
  25158. this._scene.collisionsEnabled = true;
  25159. this._scene.lightsEnabled = true;
  25160. this._scene.texturesEnabled = true;
  25161. this._scene.lensFlaresEnabled = true;
  25162. this._scene.proceduralTexturesEnabled = true;
  25163. this._scene.renderTargetsEnabled = true;
  25164. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25165. };
  25166. DebugLayer.prototype.show = function (showUI) {
  25167. if (typeof showUI === "undefined") { showUI = true; }
  25168. if (this._enabled) {
  25169. return;
  25170. }
  25171. this._enabled = true;
  25172. this._showUI = showUI;
  25173. var engine = this._scene.getEngine();
  25174. this._globalDiv = document.createElement("div");
  25175. document.body.appendChild(this._globalDiv);
  25176. this._generateDOMelements();
  25177. window.addEventListener("resize", this._syncPositions);
  25178. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25179. this._syncPositions();
  25180. this._scene.registerAfterRender(this._syncData);
  25181. };
  25182. DebugLayer.prototype._clearLabels = function () {
  25183. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25184. for (var index = 0; index < this._scene.meshes.length; index++) {
  25185. var mesh = this._scene.meshes[index];
  25186. mesh.renderOverlay = false;
  25187. }
  25188. };
  25189. DebugLayer.prototype._generateheader = function (root, text) {
  25190. var header = document.createElement("div");
  25191. header.innerHTML = text + "&nbsp;";
  25192. header.style.textAlign = "right";
  25193. header.style.width = "100%";
  25194. header.style.color = "white";
  25195. header.style.backgroundColor = "Black";
  25196. header.style.padding = "5px 5px 4px 0px";
  25197. header.style.marginLeft = "-5px";
  25198. header.style.fontWeight = "bold";
  25199. root.appendChild(header);
  25200. };
  25201. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25202. var label = document.createElement("label");
  25203. label.innerHTML = title;
  25204. label.style.color = color;
  25205. root.appendChild(label);
  25206. root.appendChild(document.createElement("br"));
  25207. };
  25208. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25209. if (typeof tag === "undefined") { tag = null; }
  25210. var label = document.createElement("label");
  25211. var boundingBoxesCheckbox = document.createElement("input");
  25212. boundingBoxesCheckbox.type = "checkbox";
  25213. boundingBoxesCheckbox.checked = initialState;
  25214. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25215. task(evt.target, tag);
  25216. });
  25217. label.appendChild(boundingBoxesCheckbox);
  25218. var container = document.createElement("span");
  25219. var leftPart = document.createElement("span");
  25220. var rightPart = document.createElement("span");
  25221. rightPart.style.cssFloat = "right";
  25222. leftPart.innerHTML = leftTitle;
  25223. rightPart.innerHTML = rightTitle;
  25224. rightPart.style.fontSize = "12px";
  25225. rightPart.style.maxWidth = "200px";
  25226. container.appendChild(leftPart);
  25227. container.appendChild(rightPart);
  25228. label.appendChild(container);
  25229. root.appendChild(label);
  25230. root.appendChild(document.createElement("br"));
  25231. };
  25232. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25233. if (typeof tag === "undefined") { tag = null; }
  25234. var label = document.createElement("label");
  25235. var boundingBoxesCheckbox = document.createElement("input");
  25236. boundingBoxesCheckbox.type = "checkbox";
  25237. boundingBoxesCheckbox.checked = initialState;
  25238. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25239. task(evt.target, tag);
  25240. });
  25241. label.appendChild(boundingBoxesCheckbox);
  25242. label.appendChild(document.createTextNode(title));
  25243. root.appendChild(label);
  25244. root.appendChild(document.createElement("br"));
  25245. };
  25246. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25247. if (typeof tag === "undefined") { tag = null; }
  25248. var label = document.createElement("label");
  25249. var boundingBoxesRadio = document.createElement("input");
  25250. boundingBoxesRadio.type = "radio";
  25251. boundingBoxesRadio.name = name;
  25252. boundingBoxesRadio.checked = initialState;
  25253. boundingBoxesRadio.addEventListener("change", function (evt) {
  25254. task(evt.target, tag);
  25255. });
  25256. label.appendChild(boundingBoxesRadio);
  25257. label.appendChild(document.createTextNode(title));
  25258. root.appendChild(label);
  25259. root.appendChild(document.createElement("br"));
  25260. };
  25261. DebugLayer.prototype._generateDOMelements = function () {
  25262. var _this = this;
  25263. this._globalDiv.id = "DebugLayer";
  25264. this._globalDiv.style.position = "absolute";
  25265. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25266. this._globalDiv.style.fontSize = "14px";
  25267. this._globalDiv.style.color = "white";
  25268. // Drawing canvas
  25269. this._drawingCanvas = document.createElement("canvas");
  25270. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25271. this._drawingCanvas.style.position = "absolute";
  25272. this._drawingCanvas.style.pointerEvents = "none";
  25273. this._drawingContext = this._drawingCanvas.getContext("2d");
  25274. this._globalDiv.appendChild(this._drawingCanvas);
  25275. if (this._showUI) {
  25276. var background = "rgba(128, 128, 128, 0.4)";
  25277. var border = "rgb(180, 180, 180) solid 1px";
  25278. // Stats
  25279. this._statsDiv = document.createElement("div");
  25280. this._statsDiv.id = "DebugLayerStats";
  25281. this._statsDiv.style.border = border;
  25282. this._statsDiv.style.position = "absolute";
  25283. this._statsDiv.style.background = background;
  25284. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25285. this._generateheader(this._statsDiv, "STATISTICS");
  25286. this._statsSubsetDiv = document.createElement("div");
  25287. this._statsSubsetDiv.style.paddingTop = "5px";
  25288. this._statsSubsetDiv.style.paddingBottom = "5px";
  25289. this._statsSubsetDiv.style.overflowY = "auto";
  25290. this._statsDiv.appendChild(this._statsSubsetDiv);
  25291. // Tree
  25292. this._treeDiv = document.createElement("div");
  25293. this._treeDiv.id = "DebugLayerTree";
  25294. this._treeDiv.style.border = border;
  25295. this._treeDiv.style.position = "absolute";
  25296. this._treeDiv.style.background = background;
  25297. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25298. this._treeDiv.style.display = "none";
  25299. this._generateheader(this._treeDiv, "MESHES TREE");
  25300. this._treeSubsetDiv = document.createElement("div");
  25301. this._treeSubsetDiv.style.paddingTop = "5px";
  25302. this._treeSubsetDiv.style.paddingRight = "5px";
  25303. this._treeSubsetDiv.style.overflowY = "auto";
  25304. this._treeSubsetDiv.style.maxHeight = "300px";
  25305. this._treeDiv.appendChild(this._treeSubsetDiv);
  25306. this._needToRefreshMeshesTree = true;
  25307. // Logs
  25308. this._logDiv = document.createElement("div");
  25309. this._logDiv.style.border = border;
  25310. this._logDiv.id = "DebugLayerLogs";
  25311. this._logDiv.style.position = "absolute";
  25312. this._logDiv.style.background = background;
  25313. this._logDiv.style.padding = "0px 0px 0px 5px";
  25314. this._logDiv.style.display = "none";
  25315. this._generateheader(this._logDiv, "LOGS");
  25316. this._logSubsetDiv = document.createElement("div");
  25317. this._logSubsetDiv.style.height = "127px";
  25318. this._logSubsetDiv.style.paddingTop = "5px";
  25319. this._logSubsetDiv.style.overflowY = "auto";
  25320. this._logSubsetDiv.style.fontSize = "12px";
  25321. this._logSubsetDiv.style.fontFamily = "consolas";
  25322. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25323. this._logDiv.appendChild(this._logSubsetDiv);
  25324. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25325. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25326. };
  25327. // Options
  25328. this._optionsDiv = document.createElement("div");
  25329. this._optionsDiv.id = "DebugLayerOptions";
  25330. this._optionsDiv.style.border = border;
  25331. this._optionsDiv.style.position = "absolute";
  25332. this._optionsDiv.style.background = background;
  25333. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25334. this._optionsDiv.style.overflowY = "auto";
  25335. this._generateheader(this._optionsDiv, "OPTIONS");
  25336. this._optionsSubsetDiv = document.createElement("div");
  25337. this._optionsSubsetDiv.style.paddingTop = "5px";
  25338. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25339. this._optionsSubsetDiv.style.overflowY = "auto";
  25340. this._optionsSubsetDiv.style.maxHeight = "200px";
  25341. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25342. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25343. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25344. _this._displayStatistics = element.checked;
  25345. });
  25346. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25347. _this._displayLogs = element.checked;
  25348. });
  25349. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25350. _this._displayTree = element.checked;
  25351. _this._needToRefreshMeshesTree = true;
  25352. });
  25353. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25354. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25355. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25356. _this._scene.forceShowBoundingBoxes = element.checked;
  25357. });
  25358. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25359. _this._labelsEnabled = element.checked;
  25360. if (!_this._labelsEnabled) {
  25361. _this._clearLabels();
  25362. }
  25363. });
  25364. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25365. if (element.checked) {
  25366. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25367. } else {
  25368. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25369. }
  25370. });
  25371. ;
  25372. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25373. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25374. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25375. if (element.checked) {
  25376. _this._scene.forceWireframe = false;
  25377. _this._scene.forcePointsCloud = false;
  25378. }
  25379. });
  25380. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25381. if (element.checked) {
  25382. _this._scene.forceWireframe = true;
  25383. _this._scene.forcePointsCloud = false;
  25384. }
  25385. });
  25386. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25387. if (element.checked) {
  25388. _this._scene.forceWireframe = false;
  25389. _this._scene.forcePointsCloud = true;
  25390. }
  25391. });
  25392. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25393. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25394. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25395. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25396. });
  25397. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25398. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25399. });
  25400. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25401. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25402. });
  25403. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25404. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25405. });
  25406. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25407. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25408. });
  25409. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25410. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25411. });
  25412. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25413. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25414. });
  25415. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25416. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25417. });
  25418. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25419. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25420. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25421. _this._scene.animationsEnabled = element.checked;
  25422. });
  25423. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25424. _this._scene.collisionsEnabled = element.checked;
  25425. });
  25426. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25427. _this._scene.fogEnabled = element.checked;
  25428. });
  25429. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25430. _this._scene.lensFlaresEnabled = element.checked;
  25431. });
  25432. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25433. _this._scene.lightsEnabled = element.checked;
  25434. });
  25435. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25436. _this._scene.particlesEnabled = element.checked;
  25437. });
  25438. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25439. _this._scene.postProcessesEnabled = element.checked;
  25440. });
  25441. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25442. _this._scene.proceduralTexturesEnabled = element.checked;
  25443. });
  25444. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25445. _this._scene.renderTargetsEnabled = element.checked;
  25446. });
  25447. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25448. _this._scene.shadowsEnabled = element.checked;
  25449. });
  25450. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25451. _this._scene.skeletonsEnabled = element.checked;
  25452. });
  25453. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25454. _this._scene.texturesEnabled = element.checked;
  25455. });
  25456. this._globalDiv.appendChild(this._statsDiv);
  25457. this._globalDiv.appendChild(this._logDiv);
  25458. this._globalDiv.appendChild(this._optionsDiv);
  25459. this._globalDiv.appendChild(this._treeDiv);
  25460. }
  25461. };
  25462. DebugLayer.prototype._displayStats = function () {
  25463. var scene = this._scene;
  25464. var engine = scene.getEngine();
  25465. var glInfo = engine.getGlInfo();
  25466. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Count</b><br>" + "Total meshes: " + scene.meshes.length + "<br>" + "Total vertices: " + scene.getTotalVertices() + "<br>" + "Total materials: " + scene.materials.length + "<br>" + "Total textures: " + scene.textures.length + "<br>" + "Active meshes: " + scene.getActiveMeshes().length + "<br>" + "Active vertices: " + scene.getActiveVertices() + "<br>" + "Active bones: " + scene.getActiveBones() + "<br>" + "Active particles: " + scene.getActiveParticles() + "<br>" + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>" + "<b>Duration</b><br>" + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>" + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>" + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>" + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>" + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>" + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>" + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br><br>" + "</div>" + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>" + "<b>Extensions</b><br>" + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>" + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>" + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>" + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br>" + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>" + "<b>Caps.</b><br>" + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>" + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>" + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br><br><br>" + "</div><br>" + "<b>Info</b><br>" + glInfo.version + "<br>" + glInfo.renderer + "<br>";
  25467. if (this.customStatsFunction) {
  25468. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25469. }
  25470. };
  25471. return DebugLayer;
  25472. })();
  25473. BABYLON.DebugLayer = DebugLayer;
  25474. })(BABYLON || (BABYLON = {}));
  25475. //# sourceMappingURL=babylon.debugLayer.js.map
  25476. var BABYLON;
  25477. (function (BABYLON) {
  25478. var RawTexture = (function (_super) {
  25479. __extends(RawTexture, _super);
  25480. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25481. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25482. if (typeof invertY === "undefined") { invertY = false; }
  25483. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25484. _super.call(this, null, scene, !generateMipMaps, invertY);
  25485. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25486. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25487. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25488. }
  25489. // Statics
  25490. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25491. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25492. if (typeof invertY === "undefined") { invertY = false; }
  25493. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25494. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25495. };
  25496. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25497. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25498. if (typeof invertY === "undefined") { invertY = false; }
  25499. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25500. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25501. };
  25502. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25503. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25504. if (typeof invertY === "undefined") { invertY = false; }
  25505. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25506. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25507. };
  25508. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25509. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25510. if (typeof invertY === "undefined") { invertY = false; }
  25511. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25512. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25513. };
  25514. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25515. if (typeof generateMipMaps === "undefined") { generateMipMaps = true; }
  25516. if (typeof invertY === "undefined") { invertY = false; }
  25517. if (typeof samplingMode === "undefined") { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25518. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25519. };
  25520. return RawTexture;
  25521. })(BABYLON.Texture);
  25522. BABYLON.RawTexture = RawTexture;
  25523. })(BABYLON || (BABYLON = {}));
  25524. //# sourceMappingURL=babylon.rawTexture.js.map
  25525. var BABYLON;
  25526. (function (BABYLON) {
  25527. var IndexedVector2 = (function (_super) {
  25528. __extends(IndexedVector2, _super);
  25529. function IndexedVector2(original, index) {
  25530. _super.call(this, original.x, original.y);
  25531. this.index = index;
  25532. }
  25533. return IndexedVector2;
  25534. })(BABYLON.Vector2);
  25535. var PolygonPoints = (function () {
  25536. function PolygonPoints() {
  25537. this.elements = new Array();
  25538. }
  25539. PolygonPoints.prototype.add = function (originalPoints) {
  25540. var _this = this;
  25541. var result = new Array();
  25542. originalPoints.forEach(function (point) {
  25543. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25544. var newPoint = new IndexedVector2(point, _this.elements.length);
  25545. result.push(newPoint);
  25546. _this.elements.push(newPoint);
  25547. }
  25548. });
  25549. return result;
  25550. };
  25551. PolygonPoints.prototype.computeBounds = function () {
  25552. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25553. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25554. this.elements.forEach(function (point) {
  25555. // x
  25556. if (point.x < lmin.x) {
  25557. lmin.x = point.x;
  25558. } else if (point.x > lmax.x) {
  25559. lmax.x = point.x;
  25560. }
  25561. // y
  25562. if (point.y < lmin.y) {
  25563. lmin.y = point.y;
  25564. } else if (point.y > lmax.y) {
  25565. lmax.y = point.y;
  25566. }
  25567. });
  25568. return {
  25569. min: lmin,
  25570. max: lmax,
  25571. width: lmax.x - lmin.x,
  25572. height: lmax.y - lmin.y
  25573. };
  25574. };
  25575. return PolygonPoints;
  25576. })();
  25577. var Polygon = (function () {
  25578. function Polygon() {
  25579. }
  25580. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25581. return [
  25582. new BABYLON.Vector2(xmin, ymin),
  25583. new BABYLON.Vector2(xmax, ymin),
  25584. new BABYLON.Vector2(xmax, ymax),
  25585. new BABYLON.Vector2(xmin, ymax)
  25586. ];
  25587. };
  25588. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25589. if (typeof cx === "undefined") { cx = 0; }
  25590. if (typeof cy === "undefined") { cy = 0; }
  25591. if (typeof numberOfSides === "undefined") { numberOfSides = 32; }
  25592. var result = new Array();
  25593. var angle = 0;
  25594. var increment = (Math.PI * 2) / numberOfSides;
  25595. for (var i = 0; i < numberOfSides; i++) {
  25596. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25597. angle -= increment;
  25598. }
  25599. return result;
  25600. };
  25601. Polygon.Parse = function (input) {
  25602. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) {
  25603. return (!isNaN(val));
  25604. });
  25605. var i, result = [];
  25606. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25607. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25608. }
  25609. return result;
  25610. };
  25611. Polygon.StartingAt = function (x, y) {
  25612. return BABYLON.Path2.StartingAt(x, y);
  25613. };
  25614. return Polygon;
  25615. })();
  25616. BABYLON.Polygon = Polygon;
  25617. var PolygonMeshBuilder = (function () {
  25618. function PolygonMeshBuilder(name, contours, scene) {
  25619. this._points = new PolygonPoints();
  25620. if (!("poly2tri" in window)) {
  25621. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25622. }
  25623. this._name = name;
  25624. this._scene = scene;
  25625. var points;
  25626. if (contours instanceof BABYLON.Path2) {
  25627. points = contours.getPoints();
  25628. } else {
  25629. points = contours;
  25630. }
  25631. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25632. }
  25633. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25634. this._swctx.addHole(this._points.add(hole));
  25635. return this;
  25636. };
  25637. PolygonMeshBuilder.prototype.build = function (updatable) {
  25638. if (typeof updatable === "undefined") { updatable = false; }
  25639. var result = new BABYLON.Mesh(this._name, this._scene);
  25640. var normals = [];
  25641. var positions = [];
  25642. var uvs = [];
  25643. var bounds = this._points.computeBounds();
  25644. this._points.elements.forEach(function (p) {
  25645. normals.push(0, 1.0, 0);
  25646. positions.push(p.x, 0, p.y);
  25647. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25648. });
  25649. var indices = [];
  25650. this._swctx.triangulate();
  25651. this._swctx.getTriangles().forEach(function (triangle) {
  25652. triangle.getPoints().forEach(function (point) {
  25653. indices.push(point.index);
  25654. });
  25655. });
  25656. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25657. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25658. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25659. result.setIndices(indices);
  25660. return result;
  25661. };
  25662. return PolygonMeshBuilder;
  25663. })();
  25664. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25665. })(BABYLON || (BABYLON = {}));
  25666. //# sourceMappingURL=babylon.polygonMesh.js.map
  25667. var BABYLON;
  25668. (function (BABYLON) {
  25669. var SimplificationSettings = (function () {
  25670. function SimplificationSettings(quality, distance) {
  25671. this.quality = quality;
  25672. this.distance = distance;
  25673. }
  25674. return SimplificationSettings;
  25675. })();
  25676. BABYLON.SimplificationSettings = SimplificationSettings;
  25677. /**
  25678. * The implemented types of simplification.
  25679. * At the moment only Quadratic Error Decimation is implemented.
  25680. */
  25681. (function (SimplificationType) {
  25682. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25683. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25684. var SimplificationType = BABYLON.SimplificationType;
  25685. var DecimationTriangle = (function () {
  25686. function DecimationTriangle(vertices) {
  25687. this.vertices = vertices;
  25688. this.error = new Array(4);
  25689. this.deleted = false;
  25690. this.isDirty = false;
  25691. this.borderFactor = 0;
  25692. }
  25693. return DecimationTriangle;
  25694. })();
  25695. BABYLON.DecimationTriangle = DecimationTriangle;
  25696. var DecimationVertex = (function () {
  25697. function DecimationVertex(position, normal, uv, id) {
  25698. this.position = position;
  25699. this.normal = normal;
  25700. this.uv = uv;
  25701. this.id = id;
  25702. this.isBorder = true;
  25703. this.q = new QuadraticMatrix();
  25704. this.triangleCount = 0;
  25705. this.triangleStart = 0;
  25706. }
  25707. return DecimationVertex;
  25708. })();
  25709. BABYLON.DecimationVertex = DecimationVertex;
  25710. var QuadraticMatrix = (function () {
  25711. function QuadraticMatrix(data) {
  25712. this.data = new Array(10);
  25713. for (var i = 0; i < 10; ++i) {
  25714. if (data && data[i]) {
  25715. this.data[i] = data[i];
  25716. } else {
  25717. this.data[i] = 0;
  25718. }
  25719. }
  25720. }
  25721. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25722. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] + this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] - this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  25723. return det;
  25724. };
  25725. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25726. for (var i = 0; i < 10; ++i) {
  25727. this.data[i] += matrix.data[i];
  25728. }
  25729. };
  25730. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  25731. for (var i = 0; i < 10; ++i) {
  25732. this.data[i] += data[i];
  25733. }
  25734. };
  25735. QuadraticMatrix.prototype.add = function (matrix) {
  25736. var m = new QuadraticMatrix();
  25737. for (var i = 0; i < 10; ++i) {
  25738. m.data[i] = this.data[i] + matrix.data[i];
  25739. }
  25740. return m;
  25741. };
  25742. QuadraticMatrix.FromData = function (a, b, c, d) {
  25743. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  25744. };
  25745. //returning an array to avoid garbage collection
  25746. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  25747. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  25748. };
  25749. return QuadraticMatrix;
  25750. })();
  25751. BABYLON.QuadraticMatrix = QuadraticMatrix;
  25752. var Reference = (function () {
  25753. function Reference(vertexId, triangleId) {
  25754. this.vertexId = vertexId;
  25755. this.triangleId = triangleId;
  25756. }
  25757. return Reference;
  25758. })();
  25759. BABYLON.Reference = Reference;
  25760. /**
  25761. * An implementation of the Quadratic Error simplification algorithm.
  25762. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  25763. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  25764. * @author RaananW
  25765. */
  25766. var QuadraticErrorSimplification = (function () {
  25767. function QuadraticErrorSimplification(_mesh) {
  25768. this._mesh = _mesh;
  25769. this.initialised = false;
  25770. this.syncIterations = 5000;
  25771. this.aggressiveness = 7;
  25772. this.decimationIterations = 100;
  25773. }
  25774. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  25775. var _this = this;
  25776. this.initWithMesh(this._mesh, function () {
  25777. _this.runDecimation(settings, successCallback);
  25778. });
  25779. };
  25780. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  25781. var _this = this;
  25782. var targetCount = ~~(this.triangles.length * settings.quality);
  25783. var deletedTriangles = 0;
  25784. var triangleCount = this.triangles.length;
  25785. var iterationFunction = function (iteration, callback) {
  25786. setTimeout(function () {
  25787. if (iteration % 5 === 0) {
  25788. _this.updateMesh(iteration === 0);
  25789. }
  25790. for (var i = 0; i < _this.triangles.length; ++i) {
  25791. _this.triangles[i].isDirty = false;
  25792. }
  25793. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  25794. var trianglesIterator = function (i) {
  25795. var t = _this.triangles[i];
  25796. if (!t)
  25797. return;
  25798. if (t.error[3] > threshold) {
  25799. return;
  25800. }
  25801. if (t.deleted) {
  25802. return;
  25803. }
  25804. if (t.isDirty) {
  25805. return;
  25806. }
  25807. for (var j = 0; j < 3; ++j) {
  25808. if (t.error[j] < threshold) {
  25809. var deleted0 = [];
  25810. var deleted1 = [];
  25811. var i0 = t.vertices[j];
  25812. var i1 = t.vertices[(j + 1) % 3];
  25813. var v0 = _this.vertices[i0];
  25814. var v1 = _this.vertices[i1];
  25815. if (v0.isBorder !== v1.isBorder)
  25816. continue;
  25817. var p = BABYLON.Vector3.Zero();
  25818. var n = BABYLON.Vector3.Zero();
  25819. var uv = BABYLON.Vector2.Zero();
  25820. _this.calculateError(v0, v1, p, n, uv);
  25821. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  25822. continue;
  25823. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  25824. continue;
  25825. v0.position = p;
  25826. v0.normal = n;
  25827. v0.uv = uv;
  25828. v0.q = v1.q.add(v0.q);
  25829. var tStart = _this.references.length;
  25830. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  25831. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  25832. var tCount = _this.references.length - tStart;
  25833. if (tCount <= v0.triangleCount) {
  25834. if (tCount) {
  25835. for (var c = 0; c < tCount; c++) {
  25836. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  25837. }
  25838. }
  25839. } else {
  25840. v0.triangleStart = tStart;
  25841. }
  25842. v0.triangleCount = tCount;
  25843. break;
  25844. }
  25845. }
  25846. };
  25847. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  25848. return (triangleCount - deletedTriangles <= targetCount);
  25849. });
  25850. }, 0);
  25851. };
  25852. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  25853. if (triangleCount - deletedTriangles <= targetCount)
  25854. loop.breakLoop();
  25855. else {
  25856. iterationFunction(loop.index, function () {
  25857. loop.executeNext();
  25858. });
  25859. }
  25860. }, function () {
  25861. setTimeout(function () {
  25862. successCallback(_this.reconstructMesh());
  25863. }, 0);
  25864. });
  25865. };
  25866. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  25867. var _this = this;
  25868. if (!mesh)
  25869. return;
  25870. this.vertices = [];
  25871. this.triangles = [];
  25872. this._mesh = mesh;
  25873. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  25874. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  25875. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  25876. var indices = mesh.getIndices();
  25877. var vertexInit = function (i) {
  25878. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), BABYLON.Vector2.FromArray(uvs, i * 2), i);
  25879. _this.vertices.push(vertex);
  25880. };
  25881. var totalVertices = mesh.getTotalVertices();
  25882. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  25883. var indicesInit = function (i) {
  25884. var pos = i * 3;
  25885. var i0 = indices[pos + 0];
  25886. var i1 = indices[pos + 1];
  25887. var i2 = indices[pos + 2];
  25888. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  25889. _this.triangles.push(triangle);
  25890. };
  25891. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  25892. _this.init(callback);
  25893. });
  25894. });
  25895. };
  25896. QuadraticErrorSimplification.prototype.init = function (callback) {
  25897. var _this = this;
  25898. var triangleInit1 = function (i) {
  25899. var t = _this.triangles[i];
  25900. t.normal = BABYLON.Vector3.Cross(_this.vertices[t.vertices[1]].position.subtract(_this.vertices[t.vertices[0]].position), _this.vertices[t.vertices[2]].position.subtract(_this.vertices[t.vertices[0]].position)).normalize();
  25901. for (var j = 0; j < 3; j++) {
  25902. _this.vertices[t.vertices[j]].q.addArrayInPlace(QuadraticMatrix.DataFromNumbers(t.normal.x, t.normal.y, t.normal.z, -(BABYLON.Vector3.Dot(t.normal, _this.vertices[t.vertices[0]].position))));
  25903. }
  25904. };
  25905. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  25906. var triangleInit2 = function (i) {
  25907. var t = _this.triangles[i];
  25908. for (var j = 0; j < 3; ++j) {
  25909. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  25910. }
  25911. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  25912. };
  25913. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  25914. _this.initialised = true;
  25915. callback();
  25916. });
  25917. });
  25918. };
  25919. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  25920. var newTriangles = [];
  25921. var i;
  25922. for (i = 0; i < this.vertices.length; ++i) {
  25923. this.vertices[i].triangleCount = 0;
  25924. }
  25925. var t;
  25926. var j;
  25927. for (i = 0; i < this.triangles.length; ++i) {
  25928. if (!this.triangles[i].deleted) {
  25929. t = this.triangles[i];
  25930. for (j = 0; j < 3; ++j) {
  25931. this.vertices[t.vertices[j]].triangleCount = 1;
  25932. }
  25933. newTriangles.push(t);
  25934. }
  25935. }
  25936. var newVerticesOrder = [];
  25937. //compact vertices, get the IDs of the vertices used.
  25938. var dst = 0;
  25939. for (i = 0; i < this.vertices.length; ++i) {
  25940. if (this.vertices[i].triangleCount) {
  25941. this.vertices[i].triangleStart = dst;
  25942. this.vertices[dst].position = this.vertices[i].position;
  25943. this.vertices[dst].normal = this.vertices[i].normal;
  25944. this.vertices[dst].uv = this.vertices[i].uv;
  25945. newVerticesOrder.push(i);
  25946. dst++;
  25947. }
  25948. }
  25949. for (i = 0; i < newTriangles.length; ++i) {
  25950. t = newTriangles[i];
  25951. for (j = 0; j < 3; ++j) {
  25952. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  25953. }
  25954. }
  25955. this.vertices = this.vertices.slice(0, dst);
  25956. var newPositionData = [];
  25957. var newNormalData = [];
  25958. var newUVsData = [];
  25959. for (i = 0; i < newVerticesOrder.length; ++i) {
  25960. newPositionData.push(this.vertices[i].position.x);
  25961. newPositionData.push(this.vertices[i].position.y);
  25962. newPositionData.push(this.vertices[i].position.z);
  25963. newNormalData.push(this.vertices[i].normal.x);
  25964. newNormalData.push(this.vertices[i].normal.y);
  25965. newNormalData.push(this.vertices[i].normal.z);
  25966. newUVsData.push(this.vertices[i].uv.x);
  25967. newUVsData.push(this.vertices[i].uv.y);
  25968. }
  25969. var newIndicesArray = [];
  25970. for (i = 0; i < newTriangles.length; ++i) {
  25971. newIndicesArray.push(newTriangles[i].vertices[0]);
  25972. newIndicesArray.push(newTriangles[i].vertices[1]);
  25973. newIndicesArray.push(newTriangles[i].vertices[2]);
  25974. }
  25975. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  25976. newMesh.material = this._mesh.material;
  25977. newMesh.parent = this._mesh.parent;
  25978. newMesh.setIndices(newIndicesArray);
  25979. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  25980. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  25981. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  25982. //preparing the skeleton support
  25983. if (this._mesh.skeleton) {
  25984. //newMesh.skeleton = this._mesh.skeleton.clone("", "");
  25985. //newMesh.getScene().beginAnimation(newMesh.skeleton, 0, 100, true, 1.0);
  25986. }
  25987. return newMesh;
  25988. };
  25989. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  25990. for (var i = 0; i < vertex1.triangleCount; ++i) {
  25991. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  25992. if (t.deleted)
  25993. continue;
  25994. var s = this.references[vertex1.triangleStart + i].vertexId;
  25995. var id1 = t.vertices[(s + 1) % 3];
  25996. var id2 = t.vertices[(s + 2) % 3];
  25997. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  25998. deletedArray[i] = true;
  25999. continue;
  26000. }
  26001. var d1 = this.vertices[id1].position.subtract(point);
  26002. d1 = d1.normalize();
  26003. var d2 = this.vertices[id2].position.subtract(point);
  26004. d2 = d2.normalize();
  26005. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26006. return true;
  26007. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26008. deletedArray[i] = false;
  26009. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26010. return true;
  26011. }
  26012. return false;
  26013. };
  26014. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26015. var newDeleted = deletedTriangles;
  26016. for (var i = 0; i < vertex.triangleCount; ++i) {
  26017. var ref = this.references[vertex.triangleStart + i];
  26018. var t = this.triangles[ref.triangleId];
  26019. if (t.deleted)
  26020. continue;
  26021. if (deletedArray[i]) {
  26022. t.deleted = true;
  26023. newDeleted++;
  26024. continue;
  26025. }
  26026. t.vertices[ref.vertexId] = vertexId;
  26027. t.isDirty = true;
  26028. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26029. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26030. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26031. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26032. this.references.push(ref);
  26033. }
  26034. return newDeleted;
  26035. };
  26036. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26037. for (var i = 0; i < this.vertices.length; ++i) {
  26038. var vCount = [];
  26039. var vId = [];
  26040. var v = this.vertices[i];
  26041. var j;
  26042. for (j = 0; j < v.triangleCount; ++j) {
  26043. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26044. for (var ii = 0; ii < 3; ii++) {
  26045. var ofs = 0;
  26046. var id = triangle.vertices[ii];
  26047. while (ofs < vCount.length) {
  26048. if (vId[ofs] === id)
  26049. break;
  26050. ++ofs;
  26051. }
  26052. if (ofs === vCount.length) {
  26053. vCount.push(1);
  26054. vId.push(id);
  26055. } else {
  26056. vCount[ofs]++;
  26057. }
  26058. }
  26059. }
  26060. for (j = 0; j < vCount.length; ++j) {
  26061. if (vCount[j] === 1) {
  26062. this.vertices[vId[j]].isBorder = true;
  26063. } else {
  26064. this.vertices[vId[j]].isBorder = false;
  26065. }
  26066. }
  26067. }
  26068. };
  26069. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26070. if (typeof identifyBorders === "undefined") { identifyBorders = false; }
  26071. var i;
  26072. if (!identifyBorders) {
  26073. var newTrianglesVector = [];
  26074. for (i = 0; i < this.triangles.length; ++i) {
  26075. if (!this.triangles[i].deleted) {
  26076. newTrianglesVector.push(this.triangles[i]);
  26077. }
  26078. }
  26079. this.triangles = newTrianglesVector;
  26080. }
  26081. for (i = 0; i < this.vertices.length; ++i) {
  26082. this.vertices[i].triangleCount = 0;
  26083. this.vertices[i].triangleStart = 0;
  26084. }
  26085. var t;
  26086. var j;
  26087. var v;
  26088. for (i = 0; i < this.triangles.length; ++i) {
  26089. t = this.triangles[i];
  26090. for (j = 0; j < 3; ++j) {
  26091. v = this.vertices[t.vertices[j]];
  26092. v.triangleCount++;
  26093. }
  26094. }
  26095. var tStart = 0;
  26096. for (i = 0; i < this.vertices.length; ++i) {
  26097. this.vertices[i].triangleStart = tStart;
  26098. tStart += this.vertices[i].triangleCount;
  26099. this.vertices[i].triangleCount = 0;
  26100. }
  26101. var newReferences = new Array(this.triangles.length * 3);
  26102. for (i = 0; i < this.triangles.length; ++i) {
  26103. t = this.triangles[i];
  26104. for (j = 0; j < 3; ++j) {
  26105. v = this.vertices[t.vertices[j]];
  26106. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26107. v.triangleCount++;
  26108. }
  26109. }
  26110. this.references = newReferences;
  26111. if (identifyBorders) {
  26112. this.identifyBorder();
  26113. }
  26114. };
  26115. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26116. var x = point.x;
  26117. var y = point.y;
  26118. var z = point.z;
  26119. return q.data[0] * x * x + 2 * q.data[1] * x * y + 2 * q.data[2] * x * z + 2 * q.data[3] * x + q.data[4] * y * y + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  26120. };
  26121. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  26122. var q = vertex1.q.add(vertex2.q);
  26123. var border = vertex1.isBorder && vertex2.isBorder;
  26124. var error = 0;
  26125. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26126. if (qDet !== 0 && !border) {
  26127. if (!pointResult) {
  26128. pointResult = BABYLON.Vector3.Zero();
  26129. }
  26130. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26131. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26132. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26133. error = this.vertexError(q, pointResult);
  26134. //TODO this should be correctly calculated
  26135. if (normalResult) {
  26136. normalResult.copyFrom(vertex1.normal);
  26137. uvResult.copyFrom(vertex1.uv);
  26138. }
  26139. } else {
  26140. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26141. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  26142. var error1 = this.vertexError(q, vertex1.position);
  26143. var error2 = this.vertexError(q, vertex2.position);
  26144. var error3 = this.vertexError(q, p3);
  26145. error = Math.min(error1, error2, error3);
  26146. if (error === error1) {
  26147. if (pointResult) {
  26148. pointResult.copyFrom(vertex1.position);
  26149. normalResult.copyFrom(vertex1.normal);
  26150. uvResult.copyFrom(vertex1.uv);
  26151. }
  26152. } else if (error === error2) {
  26153. if (pointResult) {
  26154. pointResult.copyFrom(vertex2.position);
  26155. normalResult.copyFrom(vertex2.normal);
  26156. uvResult.copyFrom(vertex2.uv);
  26157. }
  26158. } else {
  26159. if (pointResult) {
  26160. pointResult.copyFrom(p3);
  26161. normalResult.copyFrom(norm3);
  26162. uvResult.copyFrom(vertex1.uv);
  26163. }
  26164. }
  26165. }
  26166. return error;
  26167. };
  26168. return QuadraticErrorSimplification;
  26169. })();
  26170. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26171. })(BABYLON || (BABYLON = {}));
  26172. //# sourceMappingURL=babylon.meshSimplification.js.map