babylon.2.0-alpha.debug.js 1.3 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454
  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 (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { 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 (alpha === void 0) { 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, offset) {
  91. if (offset === void 0) { offset = 0; }
  92. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  93. };
  94. Color3.FromInts = function (r, g, b) {
  95. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  96. };
  97. Color3.Lerp = function (start, end, amount) {
  98. var r = start.r + ((end.r - start.r) * amount);
  99. var g = start.g + ((end.g - start.g) * amount);
  100. var b = start.b + ((end.b - start.b) * amount);
  101. return new Color3(r, g, b);
  102. };
  103. Color3.Red = function () {
  104. return new Color3(1, 0, 0);
  105. };
  106. Color3.Green = function () {
  107. return new Color3(0, 1, 0);
  108. };
  109. Color3.Blue = function () {
  110. return new Color3(0, 0, 1);
  111. };
  112. Color3.Black = function () {
  113. return new Color3(0, 0, 0);
  114. };
  115. Color3.White = function () {
  116. return new Color3(1, 1, 1);
  117. };
  118. Color3.Purple = function () {
  119. return new Color3(0.5, 0, 0.5);
  120. };
  121. Color3.Magenta = function () {
  122. return new Color3(1, 0, 1);
  123. };
  124. Color3.Yellow = function () {
  125. return new Color3(1, 1, 0);
  126. };
  127. Color3.Gray = function () {
  128. return new Color3(0.5, 0.5, 0.5);
  129. };
  130. return Color3;
  131. })();
  132. BABYLON.Color3 = Color3;
  133. var Color4 = (function () {
  134. function Color4(r, g, b, a) {
  135. this.r = r;
  136. this.g = g;
  137. this.b = b;
  138. this.a = a;
  139. }
  140. // Operators
  141. Color4.prototype.addInPlace = function (right) {
  142. this.r += right.r;
  143. this.g += right.g;
  144. this.b += right.b;
  145. this.a += right.a;
  146. };
  147. Color4.prototype.asArray = function () {
  148. var result = [];
  149. this.toArray(result, 0);
  150. return result;
  151. };
  152. Color4.prototype.toArray = function (array, index) {
  153. if (index === undefined) {
  154. index = 0;
  155. }
  156. array[index] = this.r;
  157. array[index + 1] = this.g;
  158. array[index + 2] = this.b;
  159. array[index + 3] = this.a;
  160. };
  161. Color4.prototype.add = function (right) {
  162. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  163. };
  164. Color4.prototype.subtract = function (right) {
  165. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  166. };
  167. Color4.prototype.subtractToRef = function (right, result) {
  168. result.r = this.r - right.r;
  169. result.g = this.g - right.g;
  170. result.b = this.b - right.b;
  171. result.a = this.a - right.a;
  172. };
  173. Color4.prototype.scale = function (scale) {
  174. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  175. };
  176. Color4.prototype.scaleToRef = function (scale, result) {
  177. result.r = this.r * scale;
  178. result.g = this.g * scale;
  179. result.b = this.b * scale;
  180. result.a = this.a * scale;
  181. };
  182. Color4.prototype.toString = function () {
  183. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  184. };
  185. Color4.prototype.clone = function () {
  186. return new Color4(this.r, this.g, this.b, this.a);
  187. };
  188. Color4.prototype.copyFrom = function (source) {
  189. this.r = source.r;
  190. this.g = source.g;
  191. this.b = source.b;
  192. this.a = source.a;
  193. };
  194. // Statics
  195. Color4.Lerp = function (left, right, amount) {
  196. var result = new Color4(0, 0, 0, 0);
  197. Color4.LerpToRef(left, right, amount, result);
  198. return result;
  199. };
  200. Color4.LerpToRef = function (left, right, amount, result) {
  201. result.r = left.r + (right.r - left.r) * amount;
  202. result.g = left.g + (right.g - left.g) * amount;
  203. result.b = left.b + (right.b - left.b) * amount;
  204. result.a = left.a + (right.a - left.a) * amount;
  205. };
  206. Color4.FromArray = function (array, offset) {
  207. if (offset === void 0) { offset = 0; }
  208. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  209. };
  210. Color4.FromInts = function (r, g, b, a) {
  211. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  212. };
  213. return Color4;
  214. })();
  215. BABYLON.Color4 = Color4;
  216. var Vector2 = (function () {
  217. function Vector2(x, y) {
  218. this.x = x;
  219. this.y = y;
  220. }
  221. Vector2.prototype.toString = function () {
  222. return "{X: " + this.x + " Y:" + this.y + "}";
  223. };
  224. // Operators
  225. Vector2.prototype.toArray = function (array, index) {
  226. if (index === undefined) {
  227. index = 0;
  228. }
  229. array[index] = this.x;
  230. array[index + 1] = this.y;
  231. };
  232. Vector2.prototype.asArray = function () {
  233. var result = [];
  234. this.toArray(result, 0);
  235. return result;
  236. };
  237. Vector2.prototype.copyFrom = function (source) {
  238. this.x = source.x;
  239. this.y = source.y;
  240. };
  241. Vector2.prototype.copyFromFloats = function (x, y) {
  242. this.x = x;
  243. this.y = y;
  244. };
  245. Vector2.prototype.add = function (otherVector) {
  246. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  247. };
  248. Vector2.prototype.addVector3 = function (otherVector) {
  249. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  250. };
  251. Vector2.prototype.subtract = function (otherVector) {
  252. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  253. };
  254. Vector2.prototype.subtractInPlace = function (otherVector) {
  255. this.x -= otherVector.x;
  256. this.y -= otherVector.y;
  257. };
  258. Vector2.prototype.multiplyInPlace = function (otherVector) {
  259. this.x *= otherVector.x;
  260. this.y *= otherVector.y;
  261. };
  262. Vector2.prototype.multiply = function (otherVector) {
  263. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  264. };
  265. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  266. result.x = this.x * otherVector.x;
  267. result.y = this.y * otherVector.y;
  268. };
  269. Vector2.prototype.multiplyByFloats = function (x, y) {
  270. return new Vector2(this.x * x, this.y * y);
  271. };
  272. Vector2.prototype.divide = function (otherVector) {
  273. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  274. };
  275. Vector2.prototype.divideToRef = function (otherVector, result) {
  276. result.x = this.x / otherVector.x;
  277. result.y = this.y / otherVector.y;
  278. };
  279. Vector2.prototype.negate = function () {
  280. return new Vector2(-this.x, -this.y);
  281. };
  282. Vector2.prototype.scaleInPlace = function (scale) {
  283. this.x *= scale;
  284. this.y *= scale;
  285. return this;
  286. };
  287. Vector2.prototype.scale = function (scale) {
  288. return new Vector2(this.x * scale, this.y * scale);
  289. };
  290. Vector2.prototype.equals = function (otherVector) {
  291. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  292. };
  293. // Properties
  294. Vector2.prototype.length = function () {
  295. return Math.sqrt(this.x * this.x + this.y * this.y);
  296. };
  297. Vector2.prototype.lengthSquared = function () {
  298. return (this.x * this.x + this.y * this.y);
  299. };
  300. // Methods
  301. Vector2.prototype.normalize = function () {
  302. var len = this.length();
  303. if (len === 0)
  304. return this;
  305. var num = 1.0 / len;
  306. this.x *= num;
  307. this.y *= num;
  308. return this;
  309. };
  310. Vector2.prototype.clone = function () {
  311. return new Vector2(this.x, this.y);
  312. };
  313. // Statics
  314. Vector2.Zero = function () {
  315. return new Vector2(0, 0);
  316. };
  317. Vector2.FromArray = function (array, offset) {
  318. if (offset === void 0) { offset = 0; }
  319. return new Vector2(array[offset], array[offset + 1]);
  320. };
  321. Vector2.FromArrayToRef = function (array, offset, result) {
  322. result.x = array[offset];
  323. result.y = array[offset + 1];
  324. };
  325. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  326. var squared = amount * amount;
  327. var cubed = amount * squared;
  328. 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));
  329. 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));
  330. return new Vector2(x, y);
  331. };
  332. Vector2.Clamp = function (value, min, max) {
  333. var x = value.x;
  334. x = (x > max.x) ? max.x : x;
  335. x = (x < min.x) ? min.x : x;
  336. var y = value.y;
  337. y = (y > max.y) ? max.y : y;
  338. y = (y < min.y) ? min.y : y;
  339. return new Vector2(x, y);
  340. };
  341. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  342. var squared = amount * amount;
  343. var cubed = amount * squared;
  344. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  345. var part2 = (-2.0 * cubed) + (3.0 * squared);
  346. var part3 = (cubed - (2.0 * squared)) + amount;
  347. var part4 = cubed - squared;
  348. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  349. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  350. return new Vector2(x, y);
  351. };
  352. Vector2.Lerp = function (start, end, amount) {
  353. var x = start.x + ((end.x - start.x) * amount);
  354. var y = start.y + ((end.y - start.y) * amount);
  355. return new Vector2(x, y);
  356. };
  357. Vector2.Dot = function (left, right) {
  358. return left.x * right.x + left.y * right.y;
  359. };
  360. Vector2.Normalize = function (vector) {
  361. var newVector = vector.clone();
  362. newVector.normalize();
  363. return newVector;
  364. };
  365. Vector2.Minimize = function (left, right) {
  366. var x = (left.x < right.x) ? left.x : right.x;
  367. var y = (left.y < right.y) ? left.y : right.y;
  368. return new Vector2(x, y);
  369. };
  370. Vector2.Maximize = function (left, right) {
  371. var x = (left.x > right.x) ? left.x : right.x;
  372. var y = (left.y > right.y) ? left.y : right.y;
  373. return new Vector2(x, y);
  374. };
  375. Vector2.Transform = function (vector, transformation) {
  376. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  377. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  378. return new Vector2(x, y);
  379. };
  380. Vector2.Distance = function (value1, value2) {
  381. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  382. };
  383. Vector2.DistanceSquared = function (value1, value2) {
  384. var x = value1.x - value2.x;
  385. var y = value1.y - value2.y;
  386. return (x * x) + (y * y);
  387. };
  388. return Vector2;
  389. })();
  390. BABYLON.Vector2 = Vector2;
  391. var Vector3 = (function () {
  392. function Vector3(x, y, z) {
  393. this.x = x;
  394. this.y = y;
  395. this.z = z;
  396. }
  397. Vector3.prototype.toString = function () {
  398. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  399. };
  400. // Operators
  401. Vector3.prototype.asArray = function () {
  402. var result = [];
  403. this.toArray(result, 0);
  404. return result;
  405. };
  406. Vector3.prototype.toArray = function (array, index) {
  407. if (index === undefined) {
  408. index = 0;
  409. }
  410. array[index] = this.x;
  411. array[index + 1] = this.y;
  412. array[index + 2] = this.z;
  413. };
  414. Vector3.prototype.addInPlace = function (otherVector) {
  415. this.x += otherVector.x;
  416. this.y += otherVector.y;
  417. this.z += otherVector.z;
  418. };
  419. Vector3.prototype.add = function (otherVector) {
  420. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  421. };
  422. Vector3.prototype.addToRef = function (otherVector, result) {
  423. result.x = this.x + otherVector.x;
  424. result.y = this.y + otherVector.y;
  425. result.z = this.z + otherVector.z;
  426. };
  427. Vector3.prototype.subtractInPlace = function (otherVector) {
  428. this.x -= otherVector.x;
  429. this.y -= otherVector.y;
  430. this.z -= otherVector.z;
  431. };
  432. Vector3.prototype.subtract = function (otherVector) {
  433. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  434. };
  435. Vector3.prototype.subtractToRef = function (otherVector, result) {
  436. result.x = this.x - otherVector.x;
  437. result.y = this.y - otherVector.y;
  438. result.z = this.z - otherVector.z;
  439. };
  440. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  441. return new Vector3(this.x - x, this.y - y, this.z - z);
  442. };
  443. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  444. result.x = this.x - x;
  445. result.y = this.y - y;
  446. result.z = this.z - z;
  447. };
  448. Vector3.prototype.negate = function () {
  449. return new Vector3(-this.x, -this.y, -this.z);
  450. };
  451. Vector3.prototype.scaleInPlace = function (scale) {
  452. this.x *= scale;
  453. this.y *= scale;
  454. this.z *= scale;
  455. return this;
  456. };
  457. Vector3.prototype.scale = function (scale) {
  458. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  459. };
  460. Vector3.prototype.scaleToRef = function (scale, result) {
  461. result.x = this.x * scale;
  462. result.y = this.y * scale;
  463. result.z = this.z * scale;
  464. };
  465. Vector3.prototype.equals = function (otherVector) {
  466. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  467. };
  468. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  469. 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;
  470. };
  471. Vector3.prototype.equalsToFloats = function (x, y, z) {
  472. return this.x === x && this.y === y && this.z === z;
  473. };
  474. Vector3.prototype.multiplyInPlace = function (otherVector) {
  475. this.x *= otherVector.x;
  476. this.y *= otherVector.y;
  477. this.z *= otherVector.z;
  478. };
  479. Vector3.prototype.multiply = function (otherVector) {
  480. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  481. };
  482. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  483. result.x = this.x * otherVector.x;
  484. result.y = this.y * otherVector.y;
  485. result.z = this.z * otherVector.z;
  486. };
  487. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  488. return new Vector3(this.x * x, this.y * y, this.z * z);
  489. };
  490. Vector3.prototype.divide = function (otherVector) {
  491. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  492. };
  493. Vector3.prototype.divideToRef = function (otherVector, result) {
  494. result.x = this.x / otherVector.x;
  495. result.y = this.y / otherVector.y;
  496. result.z = this.z / otherVector.z;
  497. };
  498. Vector3.prototype.MinimizeInPlace = function (other) {
  499. if (other.x < this.x)
  500. this.x = other.x;
  501. if (other.y < this.y)
  502. this.y = other.y;
  503. if (other.z < this.z)
  504. this.z = other.z;
  505. };
  506. Vector3.prototype.MaximizeInPlace = function (other) {
  507. if (other.x > this.x)
  508. this.x = other.x;
  509. if (other.y > this.y)
  510. this.y = other.y;
  511. if (other.z > this.z)
  512. this.z = other.z;
  513. };
  514. // Properties
  515. Vector3.prototype.length = function () {
  516. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  517. };
  518. Vector3.prototype.lengthSquared = function () {
  519. return (this.x * this.x + this.y * this.y + this.z * this.z);
  520. };
  521. // Methods
  522. Vector3.prototype.normalize = function () {
  523. var len = this.length();
  524. if (len === 0)
  525. return this;
  526. var num = 1.0 / len;
  527. this.x *= num;
  528. this.y *= num;
  529. this.z *= num;
  530. return this;
  531. };
  532. Vector3.prototype.clone = function () {
  533. return new Vector3(this.x, this.y, this.z);
  534. };
  535. Vector3.prototype.copyFrom = function (source) {
  536. this.x = source.x;
  537. this.y = source.y;
  538. this.z = source.z;
  539. };
  540. Vector3.prototype.copyFromFloats = function (x, y, z) {
  541. this.x = x;
  542. this.y = y;
  543. this.z = z;
  544. };
  545. // Statics
  546. Vector3.FromArray = function (array, offset) {
  547. if (!offset) {
  548. offset = 0;
  549. }
  550. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  551. };
  552. Vector3.FromArrayToRef = function (array, offset, result) {
  553. result.x = array[offset];
  554. result.y = array[offset + 1];
  555. result.z = array[offset + 2];
  556. };
  557. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  558. result.x = array[offset];
  559. result.y = array[offset + 1];
  560. result.z = array[offset + 2];
  561. };
  562. Vector3.FromFloatsToRef = function (x, y, z, result) {
  563. result.x = x;
  564. result.y = y;
  565. result.z = z;
  566. };
  567. Vector3.Zero = function () {
  568. return new Vector3(0, 0, 0);
  569. };
  570. Vector3.Up = function () {
  571. return new Vector3(0, 1.0, 0);
  572. };
  573. Vector3.TransformCoordinates = function (vector, transformation) {
  574. var result = Vector3.Zero();
  575. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  576. return result;
  577. };
  578. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  579. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  580. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  581. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  582. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  583. result.x = x / w;
  584. result.y = y / w;
  585. result.z = z / w;
  586. };
  587. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  588. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  589. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  590. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  591. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  592. result.x = rx / rw;
  593. result.y = ry / rw;
  594. result.z = rz / rw;
  595. };
  596. Vector3.TransformNormal = function (vector, transformation) {
  597. var result = Vector3.Zero();
  598. Vector3.TransformNormalToRef(vector, transformation, result);
  599. return result;
  600. };
  601. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  602. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  603. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  604. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  605. };
  606. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  607. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  608. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  609. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  610. };
  611. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  612. var squared = amount * amount;
  613. var cubed = amount * squared;
  614. 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));
  615. 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));
  616. 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));
  617. return new Vector3(x, y, z);
  618. };
  619. Vector3.Clamp = function (value, min, max) {
  620. var x = value.x;
  621. x = (x > max.x) ? max.x : x;
  622. x = (x < min.x) ? min.x : x;
  623. var y = value.y;
  624. y = (y > max.y) ? max.y : y;
  625. y = (y < min.y) ? min.y : y;
  626. var z = value.z;
  627. z = (z > max.z) ? max.z : z;
  628. z = (z < min.z) ? min.z : z;
  629. return new Vector3(x, y, z);
  630. };
  631. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  632. var squared = amount * amount;
  633. var cubed = amount * squared;
  634. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  635. var part2 = (-2.0 * cubed) + (3.0 * squared);
  636. var part3 = (cubed - (2.0 * squared)) + amount;
  637. var part4 = cubed - squared;
  638. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  639. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  640. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  641. return new Vector3(x, y, z);
  642. };
  643. Vector3.Lerp = function (start, end, amount) {
  644. var x = start.x + ((end.x - start.x) * amount);
  645. var y = start.y + ((end.y - start.y) * amount);
  646. var z = start.z + ((end.z - start.z) * amount);
  647. return new Vector3(x, y, z);
  648. };
  649. Vector3.Dot = function (left, right) {
  650. return (left.x * right.x + left.y * right.y + left.z * right.z);
  651. };
  652. Vector3.Cross = function (left, right) {
  653. var result = Vector3.Zero();
  654. Vector3.CrossToRef(left, right, result);
  655. return result;
  656. };
  657. Vector3.CrossToRef = function (left, right, result) {
  658. result.x = left.y * right.z - left.z * right.y;
  659. result.y = left.z * right.x - left.x * right.z;
  660. result.z = left.x * right.y - left.y * right.x;
  661. };
  662. Vector3.Normalize = function (vector) {
  663. var result = Vector3.Zero();
  664. Vector3.NormalizeToRef(vector, result);
  665. return result;
  666. };
  667. Vector3.NormalizeToRef = function (vector, result) {
  668. result.copyFrom(vector);
  669. result.normalize();
  670. };
  671. Vector3.Project = function (vector, world, transform, viewport) {
  672. var cw = viewport.width;
  673. var ch = viewport.height;
  674. var cx = viewport.x;
  675. var cy = viewport.y;
  676. 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);
  677. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  678. return Vector3.TransformCoordinates(vector, finalMatrix);
  679. };
  680. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  681. var matrix = world.multiply(transform);
  682. matrix.invert();
  683. source.x = source.x / viewportWidth * 2 - 1;
  684. source.y = -(source.y / viewportHeight * 2 - 1);
  685. var vector = Vector3.TransformCoordinates(source, matrix);
  686. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  687. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  688. vector = vector.scale(1.0 / num);
  689. }
  690. return vector;
  691. };
  692. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  693. var matrix = world.multiply(view).multiply(projection);
  694. matrix.invert();
  695. source.x = source.x / viewportWidth * 2 - 1;
  696. source.y = -(source.y / viewportHeight * 2 - 1);
  697. var vector = Vector3.TransformCoordinates(source, matrix);
  698. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  699. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  700. vector = vector.scale(1.0 / num);
  701. }
  702. return vector;
  703. };
  704. Vector3.Minimize = function (left, right) {
  705. var min = left.clone();
  706. min.MinimizeInPlace(right);
  707. return min;
  708. };
  709. Vector3.Maximize = function (left, right) {
  710. var max = left.clone();
  711. max.MaximizeInPlace(right);
  712. return max;
  713. };
  714. Vector3.Distance = function (value1, value2) {
  715. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  716. };
  717. Vector3.DistanceSquared = function (value1, value2) {
  718. var x = value1.x - value2.x;
  719. var y = value1.y - value2.y;
  720. var z = value1.z - value2.z;
  721. return (x * x) + (y * y) + (z * z);
  722. };
  723. Vector3.Center = function (value1, value2) {
  724. var center = value1.add(value2);
  725. center.scaleInPlace(0.5);
  726. return center;
  727. };
  728. return Vector3;
  729. })();
  730. BABYLON.Vector3 = Vector3;
  731. //Vector4 class created for EulerAngle class conversion to Quaternion
  732. var Vector4 = (function () {
  733. function Vector4(x, y, z, w) {
  734. this.x = x;
  735. this.y = y;
  736. this.z = z;
  737. this.w = w;
  738. }
  739. Vector4.prototype.toString = function () {
  740. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  741. };
  742. // Operators
  743. Vector4.prototype.asArray = function () {
  744. var result = [];
  745. this.toArray(result, 0);
  746. return result;
  747. };
  748. Vector4.prototype.toArray = function (array, index) {
  749. if (index === undefined) {
  750. index = 0;
  751. }
  752. array[index] = this.x;
  753. array[index + 1] = this.y;
  754. array[index + 2] = this.z;
  755. array[index + 3] = this.w;
  756. };
  757. Vector4.prototype.addInPlace = function (otherVector) {
  758. this.x += otherVector.x;
  759. this.y += otherVector.y;
  760. this.z += otherVector.z;
  761. this.w += otherVector.w;
  762. };
  763. Vector4.prototype.add = function (otherVector) {
  764. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  765. };
  766. Vector4.prototype.addToRef = function (otherVector, result) {
  767. result.x = this.x + otherVector.x;
  768. result.y = this.y + otherVector.y;
  769. result.z = this.z + otherVector.z;
  770. result.w = this.w + otherVector.w;
  771. };
  772. Vector4.prototype.subtractInPlace = function (otherVector) {
  773. this.x -= otherVector.x;
  774. this.y -= otherVector.y;
  775. this.z -= otherVector.z;
  776. this.w -= otherVector.w;
  777. };
  778. Vector4.prototype.subtract = function (otherVector) {
  779. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  780. };
  781. Vector4.prototype.subtractToRef = function (otherVector, result) {
  782. result.x = this.x - otherVector.x;
  783. result.y = this.y - otherVector.y;
  784. result.z = this.z - otherVector.z;
  785. result.w = this.w - otherVector.w;
  786. };
  787. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  788. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  789. };
  790. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  791. result.x = this.x - x;
  792. result.y = this.y - y;
  793. result.z = this.z - z;
  794. result.w = this.w - w;
  795. };
  796. Vector4.prototype.negate = function () {
  797. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  798. };
  799. Vector4.prototype.scaleInPlace = function (scale) {
  800. this.x *= scale;
  801. this.y *= scale;
  802. this.z *= scale;
  803. this.w *= scale;
  804. return this;
  805. };
  806. Vector4.prototype.scale = function (scale) {
  807. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  808. };
  809. Vector4.prototype.scaleToRef = function (scale, result) {
  810. result.x = this.x * scale;
  811. result.y = this.y * scale;
  812. result.z = this.z * scale;
  813. result.w = this.w * scale;
  814. };
  815. Vector4.prototype.equals = function (otherVector) {
  816. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  817. };
  818. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  819. 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;
  820. };
  821. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  822. return this.x === x && this.y === y && this.z === z && this.w === w;
  823. };
  824. Vector4.prototype.multiplyInPlace = function (otherVector) {
  825. this.x *= otherVector.x;
  826. this.y *= otherVector.y;
  827. this.z *= otherVector.z;
  828. this.w *= otherVector.w;
  829. };
  830. Vector4.prototype.multiply = function (otherVector) {
  831. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  832. };
  833. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  834. result.x = this.x * otherVector.x;
  835. result.y = this.y * otherVector.y;
  836. result.z = this.z * otherVector.z;
  837. result.w = this.w * otherVector.w;
  838. };
  839. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  840. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  841. };
  842. Vector4.prototype.divide = function (otherVector) {
  843. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  844. };
  845. Vector4.prototype.divideToRef = function (otherVector, result) {
  846. result.x = this.x / otherVector.x;
  847. result.y = this.y / otherVector.y;
  848. result.z = this.z / otherVector.z;
  849. result.w = this.w / otherVector.w;
  850. };
  851. Vector4.prototype.MinimizeInPlace = function (other) {
  852. if (other.x < this.x)
  853. this.x = other.x;
  854. if (other.y < this.y)
  855. this.y = other.y;
  856. if (other.z < this.z)
  857. this.z = other.z;
  858. if (other.w < this.w)
  859. this.w = other.w;
  860. };
  861. Vector4.prototype.MaximizeInPlace = function (other) {
  862. if (other.x > this.x)
  863. this.x = other.x;
  864. if (other.y > this.y)
  865. this.y = other.y;
  866. if (other.z > this.z)
  867. this.z = other.z;
  868. if (other.w > this.w)
  869. this.w = other.w;
  870. };
  871. // Properties
  872. Vector4.prototype.length = function () {
  873. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  874. };
  875. Vector4.prototype.lengthSquared = function () {
  876. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  877. };
  878. // Methods
  879. Vector4.prototype.normalize = function () {
  880. var len = this.length();
  881. if (len === 0)
  882. return this;
  883. var num = 1.0 / len;
  884. this.x *= num;
  885. this.y *= num;
  886. this.z *= num;
  887. this.w *= num;
  888. return this;
  889. };
  890. Vector4.prototype.clone = function () {
  891. return new Vector4(this.x, this.y, this.z, this.w);
  892. };
  893. Vector4.prototype.copyFrom = function (source) {
  894. this.x = source.x;
  895. this.y = source.y;
  896. this.z = source.z;
  897. this.w = source.w;
  898. };
  899. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  900. this.x = x;
  901. this.y = y;
  902. this.z = z;
  903. this.w = w;
  904. };
  905. // Statics
  906. Vector4.FromArray = function (array, offset) {
  907. if (!offset) {
  908. offset = 0;
  909. }
  910. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  911. };
  912. Vector4.FromArrayToRef = function (array, offset, result) {
  913. result.x = array[offset];
  914. result.y = array[offset + 1];
  915. result.z = array[offset + 2];
  916. result.w = array[offset + 3];
  917. };
  918. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  919. result.x = array[offset];
  920. result.y = array[offset + 1];
  921. result.z = array[offset + 2];
  922. result.w = array[offset + 3];
  923. };
  924. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  925. result.x = x;
  926. result.y = y;
  927. result.z = z;
  928. result.w = w;
  929. };
  930. Vector4.Zero = function () {
  931. return new Vector4(0, 0, 0, 0);
  932. };
  933. Vector4.Normalize = function (vector) {
  934. var result = Vector4.Zero();
  935. Vector4.NormalizeToRef(vector, result);
  936. return result;
  937. };
  938. Vector4.NormalizeToRef = function (vector, result) {
  939. result.copyFrom(vector);
  940. result.normalize();
  941. };
  942. Vector4.Minimize = function (left, right) {
  943. var min = left.clone();
  944. min.MinimizeInPlace(right);
  945. return min;
  946. };
  947. Vector4.Maximize = function (left, right) {
  948. var max = left.clone();
  949. max.MaximizeInPlace(right);
  950. return max;
  951. };
  952. Vector4.Distance = function (value1, value2) {
  953. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  954. };
  955. Vector4.DistanceSquared = function (value1, value2) {
  956. var x = value1.x - value2.x;
  957. var y = value1.y - value2.y;
  958. var z = value1.z - value2.z;
  959. var w = value1.w - value2.w;
  960. return (x * x) + (y * y) + (z * z) + (w * w);
  961. };
  962. Vector4.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. return Vector4;
  968. })();
  969. BABYLON.Vector4 = Vector4;
  970. var Quaternion = (function () {
  971. function Quaternion(x, y, z, w) {
  972. if (x === void 0) { x = 0; }
  973. if (y === void 0) { y = 0; }
  974. if (z === void 0) { z = 0; }
  975. if (w === void 0) { w = 1; }
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. }
  981. Quaternion.prototype.toString = function () {
  982. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  983. };
  984. Quaternion.prototype.asArray = function () {
  985. return [this.x, this.y, this.z, this.w];
  986. };
  987. Quaternion.prototype.equals = function (otherQuaternion) {
  988. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  989. };
  990. Quaternion.prototype.clone = function () {
  991. return new Quaternion(this.x, this.y, this.z, this.w);
  992. };
  993. Quaternion.prototype.copyFrom = function (other) {
  994. this.x = other.x;
  995. this.y = other.y;
  996. this.z = other.z;
  997. this.w = other.w;
  998. };
  999. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1000. this.x = x;
  1001. this.y = y;
  1002. this.z = z;
  1003. this.w = w;
  1004. };
  1005. Quaternion.prototype.add = function (other) {
  1006. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1007. };
  1008. Quaternion.prototype.subtract = function (other) {
  1009. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1010. };
  1011. Quaternion.prototype.scale = function (value) {
  1012. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1013. };
  1014. Quaternion.prototype.multiply = function (q1) {
  1015. var result = new Quaternion(0, 0, 0, 1.0);
  1016. this.multiplyToRef(q1, result);
  1017. return result;
  1018. };
  1019. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1020. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1021. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1022. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1023. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1024. };
  1025. Quaternion.prototype.length = function () {
  1026. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1027. };
  1028. Quaternion.prototype.normalize = function () {
  1029. var length = 1.0 / this.length();
  1030. this.x *= length;
  1031. this.y *= length;
  1032. this.z *= length;
  1033. this.w *= length;
  1034. };
  1035. Quaternion.prototype.toEulerAngles = function () {
  1036. var result = Vector3.Zero();
  1037. this.toEulerAnglesToRef(result);
  1038. return result;
  1039. };
  1040. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1041. //result is an EulerAngles in the in the z-x-z convention
  1042. var qx = this.x;
  1043. var qy = this.y;
  1044. var qz = this.z;
  1045. var qw = this.w;
  1046. var qxy = qx * qy;
  1047. var qxz = qx * qz;
  1048. var qwy = qw * qy;
  1049. var qwz = qw * qz;
  1050. var qwx = qw * qx;
  1051. var qyz = qy * qz;
  1052. var sqx = qx * qx;
  1053. var sqy = qy * qy;
  1054. var determinant = sqx + sqy;
  1055. if (determinant !== 0.000 && determinant !== 1.000) {
  1056. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1057. result.y = Math.acos(1 - 2 * determinant);
  1058. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1059. }
  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. }
  1066. else {
  1067. 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)
  1068. result.y = Math.PI;
  1069. result.z = 0.0;
  1070. }
  1071. }
  1072. };
  1073. Quaternion.prototype.toRotationMatrix = function (result) {
  1074. var xx = this.x * this.x;
  1075. var yy = this.y * this.y;
  1076. var zz = this.z * this.z;
  1077. var xy = this.x * this.y;
  1078. var zw = this.z * this.w;
  1079. var zx = this.z * this.x;
  1080. var yw = this.y * this.w;
  1081. var yz = this.y * this.z;
  1082. var xw = this.x * this.w;
  1083. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1084. result.m[1] = 2.0 * (xy + zw);
  1085. result.m[2] = 2.0 * (zx - yw);
  1086. result.m[3] = 0;
  1087. result.m[4] = 2.0 * (xy - zw);
  1088. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1089. result.m[6] = 2.0 * (yz + xw);
  1090. result.m[7] = 0;
  1091. result.m[8] = 2.0 * (zx + yw);
  1092. result.m[9] = 2.0 * (yz - xw);
  1093. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1094. result.m[11] = 0;
  1095. result.m[12] = 0;
  1096. result.m[13] = 0;
  1097. result.m[14] = 0;
  1098. result.m[15] = 1.0;
  1099. };
  1100. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1101. var data = matrix.m;
  1102. var m11 = data[0], m12 = data[4], m13 = data[8];
  1103. var m21 = data[1], m22 = data[5], m23 = data[9];
  1104. var m31 = data[2], m32 = data[6], m33 = data[10];
  1105. var trace = m11 + m22 + m33;
  1106. var s;
  1107. if (trace > 0) {
  1108. s = 0.5 / Math.sqrt(trace + 1.0);
  1109. this.w = 0.25 / s;
  1110. this.x = (m32 - m23) * s;
  1111. this.y = (m13 - m31) * s;
  1112. this.z = (m21 - m12) * s;
  1113. return;
  1114. }
  1115. if (m11 > m22 && m11 > m33) {
  1116. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1117. this.w = (m32 - m23) / s;
  1118. this.x = 0.25 * s;
  1119. this.y = (m12 + m21) / s;
  1120. this.z = (m13 + m31) / s;
  1121. return;
  1122. }
  1123. if (m22 > m33) {
  1124. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1125. this.w = (m13 - m31) / s;
  1126. this.x = (m12 + m21) / s;
  1127. this.y = 0.25 * s;
  1128. this.z = (m23 + m32) / s;
  1129. return;
  1130. }
  1131. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1132. this.w = (m21 - m12) / s;
  1133. this.x = (m13 + m31) / s;
  1134. this.y = (m23 + m32) / s;
  1135. this.z = 0.25 * s;
  1136. };
  1137. // Statics
  1138. Quaternion.Inverse = function (q) {
  1139. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1140. };
  1141. Quaternion.Identity = function () {
  1142. return new Quaternion(0, 0, 0, 1);
  1143. };
  1144. Quaternion.RotationAxis = function (axis, angle) {
  1145. var result = new Quaternion();
  1146. var sin = Math.sin(angle / 2);
  1147. result.w = Math.cos(angle / 2);
  1148. result.x = axis.x * sin;
  1149. result.y = axis.y * sin;
  1150. result.z = axis.z * sin;
  1151. return result;
  1152. };
  1153. Quaternion.FromArray = function (array, offset) {
  1154. if (!offset) {
  1155. offset = 0;
  1156. }
  1157. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1158. };
  1159. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1160. var result = new Quaternion();
  1161. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1162. return result;
  1163. };
  1164. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1165. var halfRoll = roll * 0.5;
  1166. var halfPitch = pitch * 0.5;
  1167. var halfYaw = yaw * 0.5;
  1168. var sinRoll = Math.sin(halfRoll);
  1169. var cosRoll = Math.cos(halfRoll);
  1170. var sinPitch = Math.sin(halfPitch);
  1171. var cosPitch = Math.cos(halfPitch);
  1172. var sinYaw = Math.sin(halfYaw);
  1173. var cosYaw = Math.cos(halfYaw);
  1174. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1175. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1176. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1177. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1178. };
  1179. Quaternion.Slerp = function (left, right, amount) {
  1180. var num2;
  1181. var num3;
  1182. var num = amount;
  1183. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1184. var flag = false;
  1185. if (num4 < 0) {
  1186. flag = true;
  1187. num4 = -num4;
  1188. }
  1189. if (num4 > 0.999999) {
  1190. num3 = 1 - num;
  1191. num2 = flag ? -num : num;
  1192. }
  1193. else {
  1194. var num5 = Math.acos(num4);
  1195. var num6 = (1.0 / Math.sin(num5));
  1196. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1197. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1198. }
  1199. 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));
  1200. };
  1201. return Quaternion;
  1202. })();
  1203. BABYLON.Quaternion = Quaternion;
  1204. var Matrix = (function () {
  1205. function Matrix() {
  1206. this.m = new Float32Array(16);
  1207. }
  1208. // Properties
  1209. Matrix.prototype.isIdentity = function () {
  1210. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1211. return false;
  1212. 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)
  1213. return false;
  1214. return true;
  1215. };
  1216. Matrix.prototype.determinant = function () {
  1217. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1218. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1219. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1220. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1221. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1222. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1223. 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))));
  1224. };
  1225. // Methods
  1226. Matrix.prototype.toArray = function () {
  1227. return this.m;
  1228. };
  1229. Matrix.prototype.asArray = function () {
  1230. return this.toArray();
  1231. };
  1232. Matrix.prototype.invert = function () {
  1233. this.invertToRef(this);
  1234. };
  1235. Matrix.prototype.invertToRef = function (other) {
  1236. var l1 = this.m[0];
  1237. var l2 = this.m[1];
  1238. var l3 = this.m[2];
  1239. var l4 = this.m[3];
  1240. var l5 = this.m[4];
  1241. var l6 = this.m[5];
  1242. var l7 = this.m[6];
  1243. var l8 = this.m[7];
  1244. var l9 = this.m[8];
  1245. var l10 = this.m[9];
  1246. var l11 = this.m[10];
  1247. var l12 = this.m[11];
  1248. var l13 = this.m[12];
  1249. var l14 = this.m[13];
  1250. var l15 = this.m[14];
  1251. var l16 = this.m[15];
  1252. var l17 = (l11 * l16) - (l12 * l15);
  1253. var l18 = (l10 * l16) - (l12 * l14);
  1254. var l19 = (l10 * l15) - (l11 * l14);
  1255. var l20 = (l9 * l16) - (l12 * l13);
  1256. var l21 = (l9 * l15) - (l11 * l13);
  1257. var l22 = (l9 * l14) - (l10 * l13);
  1258. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1259. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1260. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1261. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1262. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1263. var l28 = (l7 * l16) - (l8 * l15);
  1264. var l29 = (l6 * l16) - (l8 * l14);
  1265. var l30 = (l6 * l15) - (l7 * l14);
  1266. var l31 = (l5 * l16) - (l8 * l13);
  1267. var l32 = (l5 * l15) - (l7 * l13);
  1268. var l33 = (l5 * l14) - (l6 * l13);
  1269. var l34 = (l7 * l12) - (l8 * l11);
  1270. var l35 = (l6 * l12) - (l8 * l10);
  1271. var l36 = (l6 * l11) - (l7 * l10);
  1272. var l37 = (l5 * l12) - (l8 * l9);
  1273. var l38 = (l5 * l11) - (l7 * l9);
  1274. var l39 = (l5 * l10) - (l6 * l9);
  1275. other.m[0] = l23 * l27;
  1276. other.m[4] = l24 * l27;
  1277. other.m[8] = l25 * l27;
  1278. other.m[12] = l26 * l27;
  1279. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1280. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1281. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1282. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1283. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1284. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1285. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1286. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1287. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1288. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1289. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1290. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1291. };
  1292. Matrix.prototype.setTranslation = function (vector3) {
  1293. this.m[12] = vector3.x;
  1294. this.m[13] = vector3.y;
  1295. this.m[14] = vector3.z;
  1296. };
  1297. Matrix.prototype.multiply = function (other) {
  1298. var result = new Matrix();
  1299. this.multiplyToRef(other, result);
  1300. return result;
  1301. };
  1302. Matrix.prototype.copyFrom = function (other) {
  1303. for (var index = 0; index < 16; index++) {
  1304. this.m[index] = other.m[index];
  1305. }
  1306. };
  1307. Matrix.prototype.copyToArray = function (array, offset) {
  1308. if (offset === void 0) { offset = 0; }
  1309. for (var index = 0; index < 16; index++) {
  1310. array[offset + index] = this.m[index];
  1311. }
  1312. };
  1313. Matrix.prototype.multiplyToRef = function (other, result) {
  1314. this.multiplyToArray(other, result.m, 0);
  1315. };
  1316. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1317. var tm0 = this.m[0];
  1318. var tm1 = this.m[1];
  1319. var tm2 = this.m[2];
  1320. var tm3 = this.m[3];
  1321. var tm4 = this.m[4];
  1322. var tm5 = this.m[5];
  1323. var tm6 = this.m[6];
  1324. var tm7 = this.m[7];
  1325. var tm8 = this.m[8];
  1326. var tm9 = this.m[9];
  1327. var tm10 = this.m[10];
  1328. var tm11 = this.m[11];
  1329. var tm12 = this.m[12];
  1330. var tm13 = this.m[13];
  1331. var tm14 = this.m[14];
  1332. var tm15 = this.m[15];
  1333. var om0 = other.m[0];
  1334. var om1 = other.m[1];
  1335. var om2 = other.m[2];
  1336. var om3 = other.m[3];
  1337. var om4 = other.m[4];
  1338. var om5 = other.m[5];
  1339. var om6 = other.m[6];
  1340. var om7 = other.m[7];
  1341. var om8 = other.m[8];
  1342. var om9 = other.m[9];
  1343. var om10 = other.m[10];
  1344. var om11 = other.m[11];
  1345. var om12 = other.m[12];
  1346. var om13 = other.m[13];
  1347. var om14 = other.m[14];
  1348. var om15 = other.m[15];
  1349. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1350. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1351. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1352. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1353. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1354. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1355. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1356. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1357. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1358. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1359. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1360. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1361. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1362. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1363. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1364. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1365. };
  1366. Matrix.prototype.equals = function (value) {
  1367. 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]);
  1368. };
  1369. Matrix.prototype.clone = function () {
  1370. 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]);
  1371. };
  1372. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1373. translation.x = this.m[12];
  1374. translation.y = this.m[13];
  1375. translation.z = this.m[14];
  1376. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1377. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1378. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1379. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1380. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1381. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1382. if (scale.x == 0 || scale.y == 0 || scale.z == 0) {
  1383. rotation.x = 0;
  1384. rotation.y = 0;
  1385. rotation.z = 0;
  1386. rotation.w = 1;
  1387. return false;
  1388. }
  1389. 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);
  1390. rotation.fromRotationMatrix(rotationMatrix);
  1391. return true;
  1392. };
  1393. // Statics
  1394. Matrix.FromArray = function (array, offset) {
  1395. var result = new Matrix();
  1396. if (!offset) {
  1397. offset = 0;
  1398. }
  1399. Matrix.FromArrayToRef(array, offset, result);
  1400. return result;
  1401. };
  1402. Matrix.FromArrayToRef = function (array, offset, result) {
  1403. for (var index = 0; index < 16; index++) {
  1404. result.m[index] = array[index + offset];
  1405. }
  1406. };
  1407. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1408. result.m[0] = initialM11;
  1409. result.m[1] = initialM12;
  1410. result.m[2] = initialM13;
  1411. result.m[3] = initialM14;
  1412. result.m[4] = initialM21;
  1413. result.m[5] = initialM22;
  1414. result.m[6] = initialM23;
  1415. result.m[7] = initialM24;
  1416. result.m[8] = initialM31;
  1417. result.m[9] = initialM32;
  1418. result.m[10] = initialM33;
  1419. result.m[11] = initialM34;
  1420. result.m[12] = initialM41;
  1421. result.m[13] = initialM42;
  1422. result.m[14] = initialM43;
  1423. result.m[15] = initialM44;
  1424. };
  1425. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1426. var result = new Matrix();
  1427. result.m[0] = initialM11;
  1428. result.m[1] = initialM12;
  1429. result.m[2] = initialM13;
  1430. result.m[3] = initialM14;
  1431. result.m[4] = initialM21;
  1432. result.m[5] = initialM22;
  1433. result.m[6] = initialM23;
  1434. result.m[7] = initialM24;
  1435. result.m[8] = initialM31;
  1436. result.m[9] = initialM32;
  1437. result.m[10] = initialM33;
  1438. result.m[11] = initialM34;
  1439. result.m[12] = initialM41;
  1440. result.m[13] = initialM42;
  1441. result.m[14] = initialM43;
  1442. result.m[15] = initialM44;
  1443. return result;
  1444. };
  1445. Matrix.Compose = function (scale, rotation, translation) {
  1446. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1447. var rotationMatrix = Matrix.Identity();
  1448. rotation.toRotationMatrix(rotationMatrix);
  1449. result = result.multiply(rotationMatrix);
  1450. result.setTranslation(translation);
  1451. return result;
  1452. };
  1453. Matrix.Identity = function () {
  1454. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1455. };
  1456. Matrix.IdentityToRef = function (result) {
  1457. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1458. };
  1459. Matrix.Zero = function () {
  1460. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1461. };
  1462. Matrix.RotationX = function (angle) {
  1463. var result = new Matrix();
  1464. Matrix.RotationXToRef(angle, result);
  1465. return result;
  1466. };
  1467. Matrix.Invert = function (source) {
  1468. var result = new Matrix();
  1469. source.invertToRef(result);
  1470. return result;
  1471. };
  1472. Matrix.RotationXToRef = function (angle, result) {
  1473. var s = Math.sin(angle);
  1474. var c = Math.cos(angle);
  1475. result.m[0] = 1.0;
  1476. result.m[15] = 1.0;
  1477. result.m[5] = c;
  1478. result.m[10] = c;
  1479. result.m[9] = -s;
  1480. result.m[6] = s;
  1481. result.m[1] = 0;
  1482. result.m[2] = 0;
  1483. result.m[3] = 0;
  1484. result.m[4] = 0;
  1485. result.m[7] = 0;
  1486. result.m[8] = 0;
  1487. result.m[11] = 0;
  1488. result.m[12] = 0;
  1489. result.m[13] = 0;
  1490. result.m[14] = 0;
  1491. };
  1492. Matrix.RotationY = function (angle) {
  1493. var result = new Matrix();
  1494. Matrix.RotationYToRef(angle, result);
  1495. return result;
  1496. };
  1497. Matrix.RotationYToRef = function (angle, result) {
  1498. var s = Math.sin(angle);
  1499. var c = Math.cos(angle);
  1500. result.m[5] = 1.0;
  1501. result.m[15] = 1.0;
  1502. result.m[0] = c;
  1503. result.m[2] = -s;
  1504. result.m[8] = s;
  1505. result.m[10] = c;
  1506. result.m[1] = 0;
  1507. result.m[3] = 0;
  1508. result.m[4] = 0;
  1509. result.m[6] = 0;
  1510. result.m[7] = 0;
  1511. result.m[9] = 0;
  1512. result.m[11] = 0;
  1513. result.m[12] = 0;
  1514. result.m[13] = 0;
  1515. result.m[14] = 0;
  1516. };
  1517. Matrix.RotationZ = function (angle) {
  1518. var result = new Matrix();
  1519. Matrix.RotationZToRef(angle, result);
  1520. return result;
  1521. };
  1522. Matrix.RotationZToRef = function (angle, result) {
  1523. var s = Math.sin(angle);
  1524. var c = Math.cos(angle);
  1525. result.m[10] = 1.0;
  1526. result.m[15] = 1.0;
  1527. result.m[0] = c;
  1528. result.m[1] = s;
  1529. result.m[4] = -s;
  1530. result.m[5] = c;
  1531. result.m[2] = 0;
  1532. result.m[3] = 0;
  1533. result.m[6] = 0;
  1534. result.m[7] = 0;
  1535. result.m[8] = 0;
  1536. result.m[9] = 0;
  1537. result.m[11] = 0;
  1538. result.m[12] = 0;
  1539. result.m[13] = 0;
  1540. result.m[14] = 0;
  1541. };
  1542. Matrix.RotationAxis = function (axis, angle) {
  1543. var s = Math.sin(-angle);
  1544. var c = Math.cos(-angle);
  1545. var c1 = 1 - c;
  1546. axis.normalize();
  1547. var result = Matrix.Zero();
  1548. result.m[0] = (axis.x * axis.x) * c1 + c;
  1549. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1550. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1551. result.m[3] = 0.0;
  1552. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1553. result.m[5] = (axis.y * axis.y) * c1 + c;
  1554. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1555. result.m[7] = 0.0;
  1556. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1557. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1558. result.m[10] = (axis.z * axis.z) * c1 + c;
  1559. result.m[11] = 0.0;
  1560. result.m[15] = 1.0;
  1561. return result;
  1562. };
  1563. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1564. var result = new Matrix();
  1565. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1566. return result;
  1567. };
  1568. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1569. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1570. this._tempQuaternion.toRotationMatrix(result);
  1571. };
  1572. Matrix.Scaling = function (x, y, z) {
  1573. var result = Matrix.Zero();
  1574. Matrix.ScalingToRef(x, y, z, result);
  1575. return result;
  1576. };
  1577. Matrix.ScalingToRef = function (x, y, z, result) {
  1578. result.m[0] = x;
  1579. result.m[1] = 0;
  1580. result.m[2] = 0;
  1581. result.m[3] = 0;
  1582. result.m[4] = 0;
  1583. result.m[5] = y;
  1584. result.m[6] = 0;
  1585. result.m[7] = 0;
  1586. result.m[8] = 0;
  1587. result.m[9] = 0;
  1588. result.m[10] = z;
  1589. result.m[11] = 0;
  1590. result.m[12] = 0;
  1591. result.m[13] = 0;
  1592. result.m[14] = 0;
  1593. result.m[15] = 1.0;
  1594. };
  1595. Matrix.Translation = function (x, y, z) {
  1596. var result = Matrix.Identity();
  1597. Matrix.TranslationToRef(x, y, z, result);
  1598. return result;
  1599. };
  1600. Matrix.TranslationToRef = function (x, y, z, result) {
  1601. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1602. };
  1603. Matrix.LookAtLH = function (eye, target, up) {
  1604. var result = Matrix.Zero();
  1605. Matrix.LookAtLHToRef(eye, target, up, result);
  1606. return result;
  1607. };
  1608. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1609. // Z axis
  1610. target.subtractToRef(eye, this._zAxis);
  1611. this._zAxis.normalize();
  1612. // X axis
  1613. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1614. this._xAxis.normalize();
  1615. // Y axis
  1616. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1617. this._yAxis.normalize();
  1618. // Eye angles
  1619. var ex = -Vector3.Dot(this._xAxis, eye);
  1620. var ey = -Vector3.Dot(this._yAxis, eye);
  1621. var ez = -Vector3.Dot(this._zAxis, eye);
  1622. 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);
  1623. };
  1624. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1625. var hw = 2.0 / width;
  1626. var hh = 2.0 / height;
  1627. var id = 1.0 / (zfar - znear);
  1628. var nid = znear / (znear - zfar);
  1629. return Matrix.FromValues(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1);
  1630. };
  1631. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1632. var matrix = Matrix.Zero();
  1633. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1634. return matrix;
  1635. };
  1636. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1637. result.m[0] = 2.0 / (right - left);
  1638. result.m[1] = result.m[2] = result.m[3] = 0;
  1639. result.m[5] = 2.0 / (top - bottom);
  1640. result.m[4] = result.m[6] = result.m[7] = 0;
  1641. result.m[10] = -1.0 / (znear - zfar);
  1642. result.m[8] = result.m[9] = result.m[11] = 0;
  1643. result.m[12] = (left + right) / (left - right);
  1644. result.m[13] = (top + bottom) / (bottom - top);
  1645. result.m[14] = znear / (znear - zfar);
  1646. result.m[15] = 1.0;
  1647. };
  1648. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1649. var matrix = Matrix.Zero();
  1650. matrix.m[0] = (2.0 * znear) / width;
  1651. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1652. matrix.m[5] = (2.0 * znear) / height;
  1653. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1654. matrix.m[10] = -zfar / (znear - zfar);
  1655. matrix.m[8] = matrix.m[9] = 0.0;
  1656. matrix.m[11] = 1.0;
  1657. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1658. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1659. return matrix;
  1660. };
  1661. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1662. var matrix = Matrix.Zero();
  1663. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1664. return matrix;
  1665. };
  1666. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result) {
  1667. var tan = 1.0 / (Math.tan(fov * 0.5));
  1668. result.m[0] = tan / aspect;
  1669. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1670. result.m[5] = tan;
  1671. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1672. result.m[8] = result.m[9] = 0.0;
  1673. result.m[10] = -zfar / (znear - zfar);
  1674. result.m[11] = 1.0;
  1675. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1676. result.m[14] = (znear * zfar) / (znear - zfar);
  1677. };
  1678. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1679. var cw = viewport.width;
  1680. var ch = viewport.height;
  1681. var cx = viewport.x;
  1682. var cy = viewport.y;
  1683. 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);
  1684. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1685. };
  1686. Matrix.Transpose = function (matrix) {
  1687. var result = new Matrix();
  1688. result.m[0] = matrix.m[0];
  1689. result.m[1] = matrix.m[4];
  1690. result.m[2] = matrix.m[8];
  1691. result.m[3] = matrix.m[12];
  1692. result.m[4] = matrix.m[1];
  1693. result.m[5] = matrix.m[5];
  1694. result.m[6] = matrix.m[9];
  1695. result.m[7] = matrix.m[13];
  1696. result.m[8] = matrix.m[2];
  1697. result.m[9] = matrix.m[6];
  1698. result.m[10] = matrix.m[10];
  1699. result.m[11] = matrix.m[14];
  1700. result.m[12] = matrix.m[3];
  1701. result.m[13] = matrix.m[7];
  1702. result.m[14] = matrix.m[11];
  1703. result.m[15] = matrix.m[15];
  1704. return result;
  1705. };
  1706. Matrix.Reflection = function (plane) {
  1707. var matrix = new Matrix();
  1708. Matrix.ReflectionToRef(plane, matrix);
  1709. return matrix;
  1710. };
  1711. Matrix.ReflectionToRef = function (plane, result) {
  1712. plane.normalize();
  1713. var x = plane.normal.x;
  1714. var y = plane.normal.y;
  1715. var z = plane.normal.z;
  1716. var temp = -2 * x;
  1717. var temp2 = -2 * y;
  1718. var temp3 = -2 * z;
  1719. result.m[0] = (temp * x) + 1;
  1720. result.m[1] = temp2 * x;
  1721. result.m[2] = temp3 * x;
  1722. result.m[3] = 0.0;
  1723. result.m[4] = temp * y;
  1724. result.m[5] = (temp2 * y) + 1;
  1725. result.m[6] = temp3 * y;
  1726. result.m[7] = 0.0;
  1727. result.m[8] = temp * z;
  1728. result.m[9] = temp2 * z;
  1729. result.m[10] = (temp3 * z) + 1;
  1730. result.m[11] = 0.0;
  1731. result.m[12] = temp * plane.d;
  1732. result.m[13] = temp2 * plane.d;
  1733. result.m[14] = temp3 * plane.d;
  1734. result.m[15] = 1.0;
  1735. };
  1736. Matrix._tempQuaternion = new Quaternion();
  1737. Matrix._xAxis = Vector3.Zero();
  1738. Matrix._yAxis = Vector3.Zero();
  1739. Matrix._zAxis = Vector3.Zero();
  1740. return Matrix;
  1741. })();
  1742. BABYLON.Matrix = Matrix;
  1743. var Plane = (function () {
  1744. function Plane(a, b, c, d) {
  1745. this.normal = new Vector3(a, b, c);
  1746. this.d = d;
  1747. }
  1748. Plane.prototype.asArray = function () {
  1749. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1750. };
  1751. // Methods
  1752. Plane.prototype.clone = function () {
  1753. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1754. };
  1755. Plane.prototype.normalize = function () {
  1756. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1757. var magnitude = 0;
  1758. if (norm !== 0) {
  1759. magnitude = 1.0 / norm;
  1760. }
  1761. this.normal.x *= magnitude;
  1762. this.normal.y *= magnitude;
  1763. this.normal.z *= magnitude;
  1764. this.d *= magnitude;
  1765. };
  1766. Plane.prototype.transform = function (transformation) {
  1767. var transposedMatrix = Matrix.Transpose(transformation);
  1768. var x = this.normal.x;
  1769. var y = this.normal.y;
  1770. var z = this.normal.z;
  1771. var d = this.d;
  1772. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1773. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1774. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1775. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1776. return new Plane(normalX, normalY, normalZ, finalD);
  1777. };
  1778. Plane.prototype.dotCoordinate = function (point) {
  1779. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1780. };
  1781. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1782. var x1 = point2.x - point1.x;
  1783. var y1 = point2.y - point1.y;
  1784. var z1 = point2.z - point1.z;
  1785. var x2 = point3.x - point1.x;
  1786. var y2 = point3.y - point1.y;
  1787. var z2 = point3.z - point1.z;
  1788. var yz = (y1 * z2) - (z1 * y2);
  1789. var xz = (z1 * x2) - (x1 * z2);
  1790. var xy = (x1 * y2) - (y1 * x2);
  1791. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1792. var invPyth;
  1793. if (pyth !== 0) {
  1794. invPyth = 1.0 / pyth;
  1795. }
  1796. else {
  1797. invPyth = 0;
  1798. }
  1799. this.normal.x = yz * invPyth;
  1800. this.normal.y = xz * invPyth;
  1801. this.normal.z = xy * invPyth;
  1802. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1803. };
  1804. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1805. var dot = Vector3.Dot(this.normal, direction);
  1806. return (dot <= epsilon);
  1807. };
  1808. Plane.prototype.signedDistanceTo = function (point) {
  1809. return Vector3.Dot(point, this.normal) + this.d;
  1810. };
  1811. // Statics
  1812. Plane.FromArray = function (array) {
  1813. return new Plane(array[0], array[1], array[2], array[3]);
  1814. };
  1815. Plane.FromPoints = function (point1, point2, point3) {
  1816. var result = new Plane(0, 0, 0, 0);
  1817. result.copyFromPoints(point1, point2, point3);
  1818. return result;
  1819. };
  1820. Plane.FromPositionAndNormal = function (origin, normal) {
  1821. var result = new Plane(0, 0, 0, 0);
  1822. normal.normalize();
  1823. result.normal = normal;
  1824. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1825. return result;
  1826. };
  1827. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1828. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1829. return Vector3.Dot(point, normal) + d;
  1830. };
  1831. return Plane;
  1832. })();
  1833. BABYLON.Plane = Plane;
  1834. var Viewport = (function () {
  1835. function Viewport(x, y, width, height) {
  1836. this.x = x;
  1837. this.y = y;
  1838. this.width = width;
  1839. this.height = height;
  1840. }
  1841. Viewport.prototype.toGlobal = function (engine) {
  1842. var width = engine.getRenderWidth();
  1843. var height = engine.getRenderHeight();
  1844. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1845. };
  1846. return Viewport;
  1847. })();
  1848. BABYLON.Viewport = Viewport;
  1849. var Frustum = (function () {
  1850. function Frustum() {
  1851. }
  1852. Frustum.GetPlanes = function (transform) {
  1853. var frustumPlanes = [];
  1854. for (var index = 0; index < 6; index++) {
  1855. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1856. }
  1857. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1858. return frustumPlanes;
  1859. };
  1860. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1861. // Near
  1862. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1863. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1864. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1865. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1866. frustumPlanes[0].normalize();
  1867. // Far
  1868. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1869. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1870. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1871. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1872. frustumPlanes[1].normalize();
  1873. // Left
  1874. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1875. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1876. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1877. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1878. frustumPlanes[2].normalize();
  1879. // Right
  1880. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1881. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1882. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1883. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1884. frustumPlanes[3].normalize();
  1885. // Top
  1886. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1887. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1888. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  1889. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  1890. frustumPlanes[4].normalize();
  1891. // Bottom
  1892. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  1893. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  1894. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  1895. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  1896. frustumPlanes[5].normalize();
  1897. };
  1898. return Frustum;
  1899. })();
  1900. BABYLON.Frustum = Frustum;
  1901. var Ray = (function () {
  1902. function Ray(origin, direction, length) {
  1903. if (length === void 0) { length = Number.MAX_VALUE; }
  1904. this.origin = origin;
  1905. this.direction = direction;
  1906. this.length = length;
  1907. }
  1908. // Methods
  1909. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  1910. var d = 0.0;
  1911. var maxValue = Number.MAX_VALUE;
  1912. if (Math.abs(this.direction.x) < 0.0000001) {
  1913. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  1914. return false;
  1915. }
  1916. }
  1917. else {
  1918. var inv = 1.0 / this.direction.x;
  1919. var min = (minimum.x - this.origin.x) * inv;
  1920. var max = (maximum.x - this.origin.x) * inv;
  1921. if (max === -Infinity) {
  1922. max = Infinity;
  1923. }
  1924. if (min > max) {
  1925. var temp = min;
  1926. min = max;
  1927. max = temp;
  1928. }
  1929. d = Math.max(min, d);
  1930. maxValue = Math.min(max, maxValue);
  1931. if (d > maxValue) {
  1932. return false;
  1933. }
  1934. }
  1935. if (Math.abs(this.direction.y) < 0.0000001) {
  1936. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  1937. return false;
  1938. }
  1939. }
  1940. else {
  1941. inv = 1.0 / this.direction.y;
  1942. min = (minimum.y - this.origin.y) * inv;
  1943. max = (maximum.y - this.origin.y) * inv;
  1944. if (max === -Infinity) {
  1945. max = Infinity;
  1946. }
  1947. if (min > max) {
  1948. temp = min;
  1949. min = max;
  1950. max = temp;
  1951. }
  1952. d = Math.max(min, d);
  1953. maxValue = Math.min(max, maxValue);
  1954. if (d > maxValue) {
  1955. return false;
  1956. }
  1957. }
  1958. if (Math.abs(this.direction.z) < 0.0000001) {
  1959. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  1960. return false;
  1961. }
  1962. }
  1963. else {
  1964. inv = 1.0 / this.direction.z;
  1965. min = (minimum.z - this.origin.z) * inv;
  1966. max = (maximum.z - this.origin.z) * inv;
  1967. if (max === -Infinity) {
  1968. max = Infinity;
  1969. }
  1970. if (min > max) {
  1971. temp = min;
  1972. min = max;
  1973. max = temp;
  1974. }
  1975. d = Math.max(min, d);
  1976. maxValue = Math.min(max, maxValue);
  1977. if (d > maxValue) {
  1978. return false;
  1979. }
  1980. }
  1981. return true;
  1982. };
  1983. Ray.prototype.intersectsBox = function (box) {
  1984. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  1985. };
  1986. Ray.prototype.intersectsSphere = function (sphere) {
  1987. var x = sphere.center.x - this.origin.x;
  1988. var y = sphere.center.y - this.origin.y;
  1989. var z = sphere.center.z - this.origin.z;
  1990. var pyth = (x * x) + (y * y) + (z * z);
  1991. var rr = sphere.radius * sphere.radius;
  1992. if (pyth <= rr) {
  1993. return true;
  1994. }
  1995. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  1996. if (dot < 0.0) {
  1997. return false;
  1998. }
  1999. var temp = pyth - (dot * dot);
  2000. return temp <= rr;
  2001. };
  2002. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2003. if (!this._edge1) {
  2004. this._edge1 = Vector3.Zero();
  2005. this._edge2 = Vector3.Zero();
  2006. this._pvec = Vector3.Zero();
  2007. this._tvec = Vector3.Zero();
  2008. this._qvec = Vector3.Zero();
  2009. }
  2010. vertex1.subtractToRef(vertex0, this._edge1);
  2011. vertex2.subtractToRef(vertex0, this._edge2);
  2012. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2013. var det = Vector3.Dot(this._edge1, this._pvec);
  2014. if (det === 0) {
  2015. return null;
  2016. }
  2017. var invdet = 1 / det;
  2018. this.origin.subtractToRef(vertex0, this._tvec);
  2019. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2020. if (bu < 0 || bu > 1.0) {
  2021. return null;
  2022. }
  2023. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2024. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2025. if (bv < 0 || bu + bv > 1.0) {
  2026. return null;
  2027. }
  2028. //check if the distance is longer than the predefined length.
  2029. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2030. if (distance > this.length) {
  2031. return null;
  2032. }
  2033. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2034. };
  2035. // Statics
  2036. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2037. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2038. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2039. var direction = end.subtract(start);
  2040. direction.normalize();
  2041. return new Ray(start, direction);
  2042. };
  2043. /**
  2044. * 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
  2045. * transformed to the given world matrix.
  2046. * @param origin The origin point
  2047. * @param end The end point
  2048. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2049. */
  2050. Ray.CreateNewFromTo = function (origin, end, world) {
  2051. if (world === void 0) { world = Matrix.Identity(); }
  2052. var direction = end.subtract(origin);
  2053. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2054. direction.normalize();
  2055. return Ray.Transform(new Ray(origin, direction, length), world);
  2056. };
  2057. Ray.Transform = function (ray, matrix) {
  2058. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2059. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2060. return new Ray(newOrigin, newDirection, ray.length);
  2061. };
  2062. return Ray;
  2063. })();
  2064. BABYLON.Ray = Ray;
  2065. (function (Space) {
  2066. Space[Space["LOCAL"] = 0] = "LOCAL";
  2067. Space[Space["WORLD"] = 1] = "WORLD";
  2068. })(BABYLON.Space || (BABYLON.Space = {}));
  2069. var Space = BABYLON.Space;
  2070. var Axis = (function () {
  2071. function Axis() {
  2072. }
  2073. Axis.X = new Vector3(1, 0, 0);
  2074. Axis.Y = new Vector3(0, 1, 0);
  2075. Axis.Z = new Vector3(0, 0, 1);
  2076. return Axis;
  2077. })();
  2078. BABYLON.Axis = Axis;
  2079. ;
  2080. var BezierCurve = (function () {
  2081. function BezierCurve() {
  2082. }
  2083. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2084. // Extract X (which is equal to time here)
  2085. var f0 = 1 - 3 * x2 + 3 * x1;
  2086. var f1 = 3 * x2 - 6 * x1;
  2087. var f2 = 3 * x1;
  2088. var refinedT = t;
  2089. for (var i = 0; i < 5; i++) {
  2090. var refinedT2 = refinedT * refinedT;
  2091. var refinedT3 = refinedT2 * refinedT;
  2092. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2093. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2094. refinedT -= (x - t) * slope;
  2095. refinedT = Math.min(1, Math.max(0, refinedT));
  2096. }
  2097. // Resolve cubic bezier for the given x
  2098. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2099. };
  2100. return BezierCurve;
  2101. })();
  2102. BABYLON.BezierCurve = BezierCurve;
  2103. (function (Orientation) {
  2104. Orientation[Orientation["CW"] = 0] = "CW";
  2105. Orientation[Orientation["CCW"] = 1] = "CCW";
  2106. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2107. var Orientation = BABYLON.Orientation;
  2108. var Angle = (function () {
  2109. function Angle(radians) {
  2110. var _this = this;
  2111. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2112. this.radians = function () { return _this._radians; };
  2113. this._radians = radians;
  2114. if (this._radians < 0)
  2115. this._radians += (2 * Math.PI);
  2116. }
  2117. Angle.BetweenTwoPoints = function (a, b) {
  2118. var delta = b.subtract(a);
  2119. var theta = Math.atan2(delta.y, delta.x);
  2120. return new Angle(theta);
  2121. };
  2122. Angle.FromRadians = function (radians) {
  2123. return new Angle(radians);
  2124. };
  2125. Angle.FromDegrees = function (degrees) {
  2126. return new Angle(degrees * Math.PI / 180);
  2127. };
  2128. return Angle;
  2129. })();
  2130. BABYLON.Angle = Angle;
  2131. var Arc2 = (function () {
  2132. function Arc2(startPoint, midPoint, endPoint) {
  2133. this.startPoint = startPoint;
  2134. this.midPoint = midPoint;
  2135. this.endPoint = endPoint;
  2136. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2137. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2138. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2139. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2140. 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);
  2141. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2142. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2143. var a1 = this.startAngle.degrees();
  2144. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2145. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2146. // angles correction
  2147. if (a2 - a1 > +180.0)
  2148. a2 -= 360.0;
  2149. if (a2 - a1 < -180.0)
  2150. a2 += 360.0;
  2151. if (a3 - a2 > +180.0)
  2152. a3 -= 360.0;
  2153. if (a3 - a2 < -180.0)
  2154. a3 += 360.0;
  2155. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2156. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2157. }
  2158. return Arc2;
  2159. })();
  2160. BABYLON.Arc2 = Arc2;
  2161. var PathCursor = (function () {
  2162. function PathCursor(path) {
  2163. this.path = path;
  2164. this._onchange = new Array();
  2165. this.value = 0;
  2166. this.animations = new Array();
  2167. }
  2168. PathCursor.prototype.getPoint = function () {
  2169. var point = this.path.getPointAtLengthPosition(this.value);
  2170. return new Vector3(point.x, 0, point.y);
  2171. };
  2172. PathCursor.prototype.moveAhead = function (step) {
  2173. if (step === void 0) { step = 0.002; }
  2174. this.move(step);
  2175. };
  2176. PathCursor.prototype.moveBack = function (step) {
  2177. if (step === void 0) { step = 0.002; }
  2178. this.move(-step);
  2179. };
  2180. PathCursor.prototype.move = function (step) {
  2181. if (Math.abs(step) > 1) {
  2182. throw "step size should be less than 1.";
  2183. }
  2184. this.value += step;
  2185. this.ensureLimits();
  2186. this.raiseOnChange();
  2187. };
  2188. PathCursor.prototype.ensureLimits = function () {
  2189. while (this.value > 1) {
  2190. this.value -= 1;
  2191. }
  2192. while (this.value < 0) {
  2193. this.value += 1;
  2194. }
  2195. };
  2196. // used by animation engine
  2197. PathCursor.prototype.markAsDirty = function (propertyName) {
  2198. this.ensureLimits();
  2199. this.raiseOnChange();
  2200. };
  2201. PathCursor.prototype.raiseOnChange = function () {
  2202. var _this = this;
  2203. this._onchange.forEach(function (f) { return f(_this); });
  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 (numberOfSegments === void 0) { 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.mapvar BABYLON;
  2297. (function (BABYLON) {
  2298. // Screenshots
  2299. var screenshotCanvas;
  2300. var cloneValue = function (source, destinationObject) {
  2301. if (!source)
  2302. return null;
  2303. if (source instanceof BABYLON.Mesh) {
  2304. return null;
  2305. }
  2306. if (source instanceof BABYLON.SubMesh) {
  2307. return source.clone(destinationObject);
  2308. }
  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. }
  2409. else if (document.mozCancelFullScreen) {
  2410. document.mozCancelFullScreen();
  2411. }
  2412. else if (document.webkitCancelFullScreen) {
  2413. document.webkitCancelFullScreen();
  2414. }
  2415. else if (document.msCancelFullScreen) {
  2416. document.msCancelFullScreen();
  2417. }
  2418. };
  2419. // External files
  2420. Tools.CleanUrl = function (url) {
  2421. url = url.replace(/#/mg, "%23");
  2422. return url;
  2423. };
  2424. Tools.LoadImage = function (url, onload, onerror, database) {
  2425. url = Tools.CleanUrl(url);
  2426. var img = new Image();
  2427. if (url.substr(0, 5) != "data:")
  2428. img.crossOrigin = 'anonymous';
  2429. img.onload = function () {
  2430. onload(img);
  2431. };
  2432. img.onerror = function (err) {
  2433. onerror(img, err);
  2434. };
  2435. var noIndexedDB = function () {
  2436. img.src = url;
  2437. };
  2438. var loadFromIndexedDB = function () {
  2439. database.loadImageFromDB(url, img);
  2440. };
  2441. //ANY database to do!
  2442. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2443. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2444. }
  2445. else {
  2446. if (url.indexOf("file:") === -1) {
  2447. noIndexedDB();
  2448. }
  2449. else {
  2450. try {
  2451. var textureName = url.substring(5);
  2452. var blobURL;
  2453. try {
  2454. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2455. }
  2456. catch (ex) {
  2457. // Chrome doesn't support oneTimeOnly parameter
  2458. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2459. }
  2460. img.src = blobURL;
  2461. }
  2462. catch (e) {
  2463. Tools.Log("Error while trying to load texture: " + textureName);
  2464. img.src = null;
  2465. }
  2466. }
  2467. }
  2468. return img;
  2469. };
  2470. //ANY
  2471. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2472. url = Tools.CleanUrl(url);
  2473. var noIndexedDB = function () {
  2474. var request = new XMLHttpRequest();
  2475. var loadUrl = Tools.BaseUrl + url;
  2476. request.open('GET', loadUrl, true);
  2477. if (useArrayBuffer) {
  2478. request.responseType = "arraybuffer";
  2479. }
  2480. request.onprogress = progressCallBack;
  2481. request.onreadystatechange = function () {
  2482. if (request.readyState == 4) {
  2483. if (request.status == 200 || BABYLON.Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2484. callback(!useArrayBuffer ? request.responseText : request.response);
  2485. }
  2486. else {
  2487. if (onError) {
  2488. onError();
  2489. }
  2490. else {
  2491. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2492. }
  2493. }
  2494. }
  2495. };
  2496. request.send(null);
  2497. };
  2498. var loadFromIndexedDB = function () {
  2499. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2500. };
  2501. if (url.indexOf("file:") !== -1) {
  2502. var fileName = url.substring(5);
  2503. BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2504. }
  2505. else {
  2506. // Caching all files
  2507. if (database && database.enableSceneOffline) {
  2508. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2509. }
  2510. else {
  2511. noIndexedDB();
  2512. }
  2513. }
  2514. };
  2515. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2516. var reader = new FileReader();
  2517. reader.onload = function (e) {
  2518. callback(e.target.result);
  2519. };
  2520. reader.onprogress = progressCallback;
  2521. reader.readAsDataURL(fileToLoad);
  2522. };
  2523. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2524. var reader = new FileReader();
  2525. reader.onload = function (e) {
  2526. callback(e.target.result);
  2527. };
  2528. reader.onprogress = progressCallBack;
  2529. if (!useArrayBuffer) {
  2530. // Asynchronous read
  2531. reader.readAsText(fileToLoad);
  2532. }
  2533. else {
  2534. reader.readAsArrayBuffer(fileToLoad);
  2535. }
  2536. };
  2537. // Misc.
  2538. Tools.Clamp = function (value, min, max) {
  2539. if (min === void 0) { min = 0; }
  2540. if (max === void 0) { max = 1; }
  2541. return Math.min(max, Math.max(min, value));
  2542. };
  2543. // Returns -1 when value is a negative number and
  2544. // +1 when value is a positive number.
  2545. Tools.Sign = function (value) {
  2546. value = +value; // convert to a number
  2547. if (value === 0 || isNaN(value))
  2548. return value;
  2549. return value > 0 ? 1 : -1;
  2550. };
  2551. Tools.Format = function (value, decimals) {
  2552. if (decimals === void 0) { decimals = 2; }
  2553. return value.toFixed(decimals);
  2554. };
  2555. Tools.CheckExtends = function (v, min, max) {
  2556. if (v.x < min.x)
  2557. min.x = v.x;
  2558. if (v.y < min.y)
  2559. min.y = v.y;
  2560. if (v.z < min.z)
  2561. min.z = v.z;
  2562. if (v.x > max.x)
  2563. max.x = v.x;
  2564. if (v.y > max.y)
  2565. max.y = v.y;
  2566. if (v.z > max.z)
  2567. max.z = v.z;
  2568. };
  2569. Tools.WithinEpsilon = function (a, b, epsilon) {
  2570. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2571. var num = a - b;
  2572. return -epsilon <= num && num <= epsilon;
  2573. };
  2574. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2575. for (var prop in source) {
  2576. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2577. continue;
  2578. }
  2579. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2580. continue;
  2581. }
  2582. var sourceValue = source[prop];
  2583. var typeOfSourceValue = typeof sourceValue;
  2584. if (typeOfSourceValue == "function") {
  2585. continue;
  2586. }
  2587. if (typeOfSourceValue == "object") {
  2588. if (sourceValue instanceof Array) {
  2589. destination[prop] = [];
  2590. if (sourceValue.length > 0) {
  2591. if (typeof sourceValue[0] == "object") {
  2592. for (var index = 0; index < sourceValue.length; index++) {
  2593. var clonedValue = cloneValue(sourceValue[index], destination);
  2594. if (destination[prop].indexOf(clonedValue) === -1) {
  2595. destination[prop].push(clonedValue);
  2596. }
  2597. }
  2598. }
  2599. else {
  2600. destination[prop] = sourceValue.slice(0);
  2601. }
  2602. }
  2603. }
  2604. else {
  2605. destination[prop] = cloneValue(sourceValue, destination);
  2606. }
  2607. }
  2608. else {
  2609. destination[prop] = sourceValue;
  2610. }
  2611. }
  2612. };
  2613. Tools.IsEmpty = function (obj) {
  2614. for (var i in obj) {
  2615. return false;
  2616. }
  2617. return true;
  2618. };
  2619. Tools.RegisterTopRootEvents = function (events) {
  2620. for (var index = 0; index < events.length; index++) {
  2621. var event = events[index];
  2622. window.addEventListener(event.name, event.handler, false);
  2623. try {
  2624. if (window.parent) {
  2625. window.parent.addEventListener(event.name, event.handler, false);
  2626. }
  2627. }
  2628. catch (e) {
  2629. }
  2630. }
  2631. };
  2632. Tools.UnregisterTopRootEvents = function (events) {
  2633. for (var index = 0; index < events.length; index++) {
  2634. var event = events[index];
  2635. window.removeEventListener(event.name, event.handler);
  2636. try {
  2637. if (window.parent) {
  2638. window.parent.removeEventListener(event.name, event.handler);
  2639. }
  2640. }
  2641. catch (e) {
  2642. }
  2643. }
  2644. };
  2645. Tools.CreateScreenshot = function (engine, camera, size) {
  2646. var width;
  2647. var height;
  2648. var scene = camera.getScene();
  2649. var previousCamera = null;
  2650. if (scene.activeCamera !== camera) {
  2651. previousCamera = scene.activeCamera;
  2652. scene.activeCamera = camera;
  2653. }
  2654. //If a precision value is specified
  2655. if (size.precision) {
  2656. width = Math.round(engine.getRenderWidth() * size.precision);
  2657. height = Math.round(width / engine.getAspectRatio(camera));
  2658. size = { width: width, height: height };
  2659. }
  2660. else if (size.width && size.height) {
  2661. width = size.width;
  2662. height = size.height;
  2663. }
  2664. else if (size.width && !size.height) {
  2665. width = size.width;
  2666. height = Math.round(width / engine.getAspectRatio(camera));
  2667. size = { width: width, height: height };
  2668. }
  2669. else if (size.height && !size.width) {
  2670. height = size.height;
  2671. width = Math.round(height * engine.getAspectRatio(camera));
  2672. size = { width: width, height: height };
  2673. }
  2674. else if (!isNaN(size)) {
  2675. height = size;
  2676. width = size;
  2677. }
  2678. else {
  2679. Tools.Error("Invalid 'size' parameter !");
  2680. return;
  2681. }
  2682. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2683. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2684. texture.renderList = scene.meshes;
  2685. texture.onAfterRender = function () {
  2686. // Read the contents of the framebuffer
  2687. var numberOfChannelsByLine = width * 4;
  2688. var halfHeight = height / 2;
  2689. //Reading datas from WebGL
  2690. var data = engine.readPixels(0, 0, width, height);
  2691. for (var i = 0; i < halfHeight; i++) {
  2692. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2693. var currentCell = j + i * numberOfChannelsByLine;
  2694. var targetLine = height - i - 1;
  2695. var targetCell = j + targetLine * numberOfChannelsByLine;
  2696. var temp = data[currentCell];
  2697. data[currentCell] = data[targetCell];
  2698. data[targetCell] = temp;
  2699. }
  2700. }
  2701. // Create a 2D canvas to store the result
  2702. if (!screenshotCanvas) {
  2703. screenshotCanvas = document.createElement('canvas');
  2704. }
  2705. screenshotCanvas.width = width;
  2706. screenshotCanvas.height = height;
  2707. var context = screenshotCanvas.getContext('2d');
  2708. // Copy the pixels to a 2D canvas
  2709. var imageData = context.createImageData(width, height);
  2710. imageData.data.set(data);
  2711. context.putImageData(imageData, 0, 0);
  2712. var base64Image = screenshotCanvas.toDataURL();
  2713. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2714. if (("download" in document.createElement("a"))) {
  2715. var a = window.document.createElement("a");
  2716. a.href = base64Image;
  2717. var date = new Date();
  2718. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2719. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2720. window.document.body.appendChild(a);
  2721. a.addEventListener("click", function () {
  2722. a.parentElement.removeChild(a);
  2723. });
  2724. a.click();
  2725. }
  2726. else {
  2727. var newWindow = window.open("");
  2728. var img = newWindow.document.createElement("img");
  2729. img.src = base64Image;
  2730. newWindow.document.body.appendChild(img);
  2731. }
  2732. };
  2733. texture.render(true);
  2734. texture.dispose();
  2735. if (previousCamera) {
  2736. scene.activeCamera = previousCamera;
  2737. }
  2738. };
  2739. // XHR response validator for local file scenario
  2740. Tools.ValidateXHRData = function (xhr, dataType) {
  2741. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2742. if (dataType === void 0) { dataType = 7; }
  2743. try {
  2744. if (dataType & 1) {
  2745. if (xhr.responseText && xhr.responseText.length > 0) {
  2746. return true;
  2747. }
  2748. else if (dataType === 1) {
  2749. return false;
  2750. }
  2751. }
  2752. if (dataType & 2) {
  2753. // Check header width and height since there is no "TGA" magic number
  2754. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2755. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2756. return true;
  2757. }
  2758. else if (dataType === 2) {
  2759. return false;
  2760. }
  2761. }
  2762. if (dataType & 4) {
  2763. // Check for the "DDS" magic number
  2764. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2765. if (ddsHeader[0] == 68 && ddsHeader[1] == 68 && ddsHeader[2] == 83) {
  2766. return true;
  2767. }
  2768. else {
  2769. return false;
  2770. }
  2771. }
  2772. }
  2773. catch (e) {
  2774. }
  2775. return false;
  2776. };
  2777. Object.defineProperty(Tools, "NoneLogLevel", {
  2778. get: function () {
  2779. return Tools._NoneLogLevel;
  2780. },
  2781. enumerable: true,
  2782. configurable: true
  2783. });
  2784. Object.defineProperty(Tools, "MessageLogLevel", {
  2785. get: function () {
  2786. return Tools._MessageLogLevel;
  2787. },
  2788. enumerable: true,
  2789. configurable: true
  2790. });
  2791. Object.defineProperty(Tools, "WarningLogLevel", {
  2792. get: function () {
  2793. return Tools._WarningLogLevel;
  2794. },
  2795. enumerable: true,
  2796. configurable: true
  2797. });
  2798. Object.defineProperty(Tools, "ErrorLogLevel", {
  2799. get: function () {
  2800. return Tools._ErrorLogLevel;
  2801. },
  2802. enumerable: true,
  2803. configurable: true
  2804. });
  2805. Object.defineProperty(Tools, "AllLogLevel", {
  2806. get: function () {
  2807. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  2808. },
  2809. enumerable: true,
  2810. configurable: true
  2811. });
  2812. Tools._AddLogEntry = function (entry) {
  2813. Tools._LogCache = entry + Tools._LogCache;
  2814. if (Tools.OnNewCacheEntry) {
  2815. Tools.OnNewCacheEntry(entry);
  2816. }
  2817. };
  2818. Tools._FormatMessage = function (message) {
  2819. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  2820. var date = new Date();
  2821. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  2822. };
  2823. Tools._LogDisabled = function (message) {
  2824. // nothing to do
  2825. };
  2826. Tools._LogEnabled = function (message) {
  2827. var formattedMessage = Tools._FormatMessage(message);
  2828. console.log("BJS - " + formattedMessage);
  2829. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  2830. Tools._AddLogEntry(entry);
  2831. };
  2832. Tools._WarnDisabled = function (message) {
  2833. // nothing to do
  2834. };
  2835. Tools._WarnEnabled = function (message) {
  2836. var formattedMessage = Tools._FormatMessage(message);
  2837. console.warn("BJS - " + formattedMessage);
  2838. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  2839. Tools._AddLogEntry(entry);
  2840. };
  2841. Tools._ErrorDisabled = function (message) {
  2842. // nothing to do
  2843. };
  2844. Tools._ErrorEnabled = function (message) {
  2845. var formattedMessage = Tools._FormatMessage(message);
  2846. console.error("BJS - " + formattedMessage);
  2847. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  2848. Tools._AddLogEntry(entry);
  2849. };
  2850. Object.defineProperty(Tools, "LogCache", {
  2851. get: function () {
  2852. return Tools._LogCache;
  2853. },
  2854. enumerable: true,
  2855. configurable: true
  2856. });
  2857. Object.defineProperty(Tools, "LogLevels", {
  2858. set: function (level) {
  2859. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  2860. Tools.Log = Tools._LogEnabled;
  2861. }
  2862. else {
  2863. Tools.Log = Tools._LogDisabled;
  2864. }
  2865. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  2866. Tools.Warn = Tools._WarnEnabled;
  2867. }
  2868. else {
  2869. Tools.Warn = Tools._WarnDisabled;
  2870. }
  2871. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  2872. Tools.Error = Tools._ErrorEnabled;
  2873. }
  2874. else {
  2875. Tools.Error = Tools._ErrorDisabled;
  2876. }
  2877. },
  2878. enumerable: true,
  2879. configurable: true
  2880. });
  2881. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  2882. get: function () {
  2883. return Tools._PerformanceNoneLogLevel;
  2884. },
  2885. enumerable: true,
  2886. configurable: true
  2887. });
  2888. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  2889. get: function () {
  2890. return Tools._PerformanceUserMarkLogLevel;
  2891. },
  2892. enumerable: true,
  2893. configurable: true
  2894. });
  2895. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  2896. get: function () {
  2897. return Tools._PerformanceConsoleLogLevel;
  2898. },
  2899. enumerable: true,
  2900. configurable: true
  2901. });
  2902. Object.defineProperty(Tools, "PerformanceLogLevel", {
  2903. set: function (level) {
  2904. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  2905. Tools.StartPerformanceCounter = Tools._StartUserMark;
  2906. Tools.EndPerformanceCounter = Tools._EndUserMark;
  2907. return;
  2908. }
  2909. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  2910. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  2911. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  2912. return;
  2913. }
  2914. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2915. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  2916. },
  2917. enumerable: true,
  2918. configurable: true
  2919. });
  2920. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  2921. };
  2922. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  2923. };
  2924. Tools._StartUserMark = function (counterName, condition) {
  2925. if (condition === void 0) { condition = true; }
  2926. if (!condition || !Tools._performance.mark) {
  2927. return;
  2928. }
  2929. Tools._performance.mark(counterName + "-Begin");
  2930. };
  2931. Tools._EndUserMark = function (counterName, condition) {
  2932. if (condition === void 0) { condition = true; }
  2933. if (!condition || !Tools._performance.mark) {
  2934. return;
  2935. }
  2936. Tools._performance.mark(counterName + "-End");
  2937. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  2938. };
  2939. Tools._StartPerformanceConsole = function (counterName, condition) {
  2940. if (condition === void 0) { condition = true; }
  2941. if (!condition) {
  2942. return;
  2943. }
  2944. Tools._StartUserMark(counterName, condition);
  2945. if (console.time) {
  2946. console.time(counterName);
  2947. }
  2948. };
  2949. Tools._EndPerformanceConsole = function (counterName, condition) {
  2950. if (condition === void 0) { condition = true; }
  2951. if (!condition) {
  2952. return;
  2953. }
  2954. Tools._EndUserMark(counterName, condition);
  2955. if (console.time) {
  2956. console.timeEnd(counterName);
  2957. }
  2958. };
  2959. Object.defineProperty(Tools, "Now", {
  2960. get: function () {
  2961. if (window.performance && window.performance.now) {
  2962. return window.performance.now();
  2963. }
  2964. return new Date().getTime();
  2965. },
  2966. enumerable: true,
  2967. configurable: true
  2968. });
  2969. // Deprecated
  2970. Tools.GetFps = function () {
  2971. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  2972. return 0;
  2973. };
  2974. Tools.BaseUrl = "";
  2975. Tools.GetExponantOfTwo = function (value, max) {
  2976. var count = 1;
  2977. do {
  2978. count *= 2;
  2979. } while (count < value);
  2980. if (count > max)
  2981. count = max;
  2982. return count;
  2983. };
  2984. // Logs
  2985. Tools._NoneLogLevel = 0;
  2986. Tools._MessageLogLevel = 1;
  2987. Tools._WarningLogLevel = 2;
  2988. Tools._ErrorLogLevel = 4;
  2989. Tools._LogCache = "";
  2990. Tools.Log = Tools._LogEnabled;
  2991. Tools.Warn = Tools._WarnEnabled;
  2992. Tools.Error = Tools._ErrorEnabled;
  2993. // Performances
  2994. Tools._PerformanceNoneLogLevel = 0;
  2995. Tools._PerformanceUserMarkLogLevel = 1;
  2996. Tools._PerformanceConsoleLogLevel = 2;
  2997. Tools._performance = window.performance;
  2998. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  2999. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3000. return Tools;
  3001. })();
  3002. BABYLON.Tools = Tools;
  3003. /**
  3004. * An implementation of a loop for asynchronous functions.
  3005. */
  3006. var AsyncLoop = (function () {
  3007. /**
  3008. * Constroctor.
  3009. * @param iterations the number of iterations.
  3010. * @param _fn the function to run each iteration
  3011. * @param _successCallback the callback that will be called upon succesful execution
  3012. * @param offset starting offset.
  3013. */
  3014. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3015. if (offset === void 0) { offset = 0; }
  3016. this.iterations = iterations;
  3017. this._fn = _fn;
  3018. this._successCallback = _successCallback;
  3019. this.index = offset - 1;
  3020. this._done = false;
  3021. }
  3022. /**
  3023. * Execute the next iteration. Must be called after the last iteration was finished.
  3024. */
  3025. AsyncLoop.prototype.executeNext = function () {
  3026. if (!this._done) {
  3027. if (this.index + 1 < this.iterations) {
  3028. ++this.index;
  3029. this._fn(this);
  3030. }
  3031. else {
  3032. this.breakLoop();
  3033. }
  3034. }
  3035. };
  3036. /**
  3037. * Break the loop and run the success callback.
  3038. */
  3039. AsyncLoop.prototype.breakLoop = function () {
  3040. this._done = true;
  3041. this._successCallback();
  3042. };
  3043. /**
  3044. * Helper function
  3045. */
  3046. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3047. if (offset === void 0) { offset = 0; }
  3048. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3049. loop.executeNext();
  3050. return loop;
  3051. };
  3052. /**
  3053. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3054. * @param iterations total number of iterations
  3055. * @param syncedIterations number of synchronous iterations in each async iteration.
  3056. * @param fn the function to call each iteration.
  3057. * @param callback a success call back that will be called when iterating stops.
  3058. * @param breakFunction a break condition (optional)
  3059. * @param timeout timeout settings for the setTimeout function. default - 0.
  3060. * @constructor
  3061. */
  3062. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3063. if (timeout === void 0) { timeout = 0; }
  3064. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3065. if (breakFunction && breakFunction())
  3066. loop.breakLoop();
  3067. else {
  3068. setTimeout(function () {
  3069. for (var i = 0; i < syncedIterations; ++i) {
  3070. var iteration = (loop.index * syncedIterations) + i;
  3071. if (iteration >= iterations)
  3072. break;
  3073. fn(iteration);
  3074. if (breakFunction && breakFunction()) {
  3075. loop.breakLoop();
  3076. break;
  3077. }
  3078. }
  3079. loop.executeNext();
  3080. }, timeout);
  3081. }
  3082. }, callback);
  3083. };
  3084. return AsyncLoop;
  3085. })();
  3086. BABYLON.AsyncLoop = AsyncLoop;
  3087. })(BABYLON || (BABYLON = {}));
  3088. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3089. (function (BABYLON) {
  3090. var _DepthCullingState = (function () {
  3091. function _DepthCullingState() {
  3092. this._isDepthTestDirty = false;
  3093. this._isDepthMaskDirty = false;
  3094. this._isDepthFuncDirty = false;
  3095. this._isCullFaceDirty = false;
  3096. this._isCullDirty = false;
  3097. }
  3098. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3099. get: function () {
  3100. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3101. },
  3102. enumerable: true,
  3103. configurable: true
  3104. });
  3105. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3106. get: function () {
  3107. return this._cullFace;
  3108. },
  3109. set: function (value) {
  3110. if (this._cullFace === value) {
  3111. return;
  3112. }
  3113. this._cullFace = value;
  3114. this._isCullFaceDirty = true;
  3115. },
  3116. enumerable: true,
  3117. configurable: true
  3118. });
  3119. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3120. get: function () {
  3121. return this._cull;
  3122. },
  3123. set: function (value) {
  3124. if (this._cull === value) {
  3125. return;
  3126. }
  3127. this._cull = value;
  3128. this._isCullDirty = true;
  3129. },
  3130. enumerable: true,
  3131. configurable: true
  3132. });
  3133. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3134. get: function () {
  3135. return this._depthFunc;
  3136. },
  3137. set: function (value) {
  3138. if (this._depthFunc === value) {
  3139. return;
  3140. }
  3141. this._depthFunc = value;
  3142. this._isDepthFuncDirty = true;
  3143. },
  3144. enumerable: true,
  3145. configurable: true
  3146. });
  3147. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3148. get: function () {
  3149. return this._depthMask;
  3150. },
  3151. set: function (value) {
  3152. if (this._depthMask === value) {
  3153. return;
  3154. }
  3155. this._depthMask = value;
  3156. this._isDepthMaskDirty = true;
  3157. },
  3158. enumerable: true,
  3159. configurable: true
  3160. });
  3161. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3162. get: function () {
  3163. return this._depthTest;
  3164. },
  3165. set: function (value) {
  3166. if (this._depthTest === value) {
  3167. return;
  3168. }
  3169. this._depthTest = value;
  3170. this._isDepthTestDirty = true;
  3171. },
  3172. enumerable: true,
  3173. configurable: true
  3174. });
  3175. _DepthCullingState.prototype.reset = function () {
  3176. this._depthMask = true;
  3177. this._depthTest = true;
  3178. this._depthFunc = null;
  3179. this._cull = null;
  3180. this._cullFace = null;
  3181. this._isDepthTestDirty = true;
  3182. this._isDepthMaskDirty = true;
  3183. this._isDepthFuncDirty = false;
  3184. this._isCullFaceDirty = false;
  3185. this._isCullDirty = false;
  3186. };
  3187. _DepthCullingState.prototype.apply = function (gl) {
  3188. if (!this.isDirty) {
  3189. return;
  3190. }
  3191. // Cull
  3192. if (this._isCullDirty) {
  3193. if (this.cull) {
  3194. gl.enable(gl.CULL_FACE);
  3195. }
  3196. else {
  3197. gl.disable(gl.CULL_FACE);
  3198. }
  3199. this._isCullDirty = false;
  3200. }
  3201. // Cull face
  3202. if (this._isCullFaceDirty) {
  3203. gl.cullFace(this.cullFace);
  3204. this._isCullFaceDirty = false;
  3205. }
  3206. // Depth mask
  3207. if (this._isDepthMaskDirty) {
  3208. gl.depthMask(this.depthMask);
  3209. this._isDepthMaskDirty = false;
  3210. }
  3211. // Depth test
  3212. if (this._isDepthTestDirty) {
  3213. if (this.depthTest) {
  3214. gl.enable(gl.DEPTH_TEST);
  3215. }
  3216. else {
  3217. gl.disable(gl.DEPTH_TEST);
  3218. }
  3219. this._isDepthTestDirty = false;
  3220. }
  3221. // Depth func
  3222. if (this._isDepthFuncDirty) {
  3223. gl.depthFunc(this.depthFunc);
  3224. this._isDepthFuncDirty = false;
  3225. }
  3226. };
  3227. return _DepthCullingState;
  3228. })();
  3229. BABYLON._DepthCullingState = _DepthCullingState;
  3230. var _AlphaState = (function () {
  3231. function _AlphaState() {
  3232. this._isAlphaBlendDirty = false;
  3233. this._isBlendFunctionParametersDirty = false;
  3234. this._alphaBlend = false;
  3235. this._blendFunctionParameters = new Array(4);
  3236. }
  3237. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3238. get: function () {
  3239. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3240. },
  3241. enumerable: true,
  3242. configurable: true
  3243. });
  3244. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3245. get: function () {
  3246. return this._alphaBlend;
  3247. },
  3248. set: function (value) {
  3249. if (this._alphaBlend === value) {
  3250. return;
  3251. }
  3252. this._alphaBlend = value;
  3253. this._isAlphaBlendDirty = true;
  3254. },
  3255. enumerable: true,
  3256. configurable: true
  3257. });
  3258. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3259. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3260. return;
  3261. }
  3262. this._blendFunctionParameters[0] = value0;
  3263. this._blendFunctionParameters[1] = value1;
  3264. this._blendFunctionParameters[2] = value2;
  3265. this._blendFunctionParameters[3] = value3;
  3266. this._isBlendFunctionParametersDirty = true;
  3267. };
  3268. _AlphaState.prototype.reset = function () {
  3269. this._alphaBlend = false;
  3270. this._blendFunctionParameters[0] = null;
  3271. this._blendFunctionParameters[1] = null;
  3272. this._blendFunctionParameters[2] = null;
  3273. this._blendFunctionParameters[3] = null;
  3274. this._isAlphaBlendDirty = true;
  3275. this._isBlendFunctionParametersDirty = false;
  3276. };
  3277. _AlphaState.prototype.apply = function (gl) {
  3278. if (!this.isDirty) {
  3279. return;
  3280. }
  3281. // Alpha blend
  3282. if (this._isAlphaBlendDirty) {
  3283. if (this._alphaBlend) {
  3284. gl.enable(gl.BLEND);
  3285. }
  3286. else {
  3287. gl.disable(gl.BLEND);
  3288. }
  3289. this._isAlphaBlendDirty = false;
  3290. }
  3291. // Alpha function
  3292. if (this._isBlendFunctionParametersDirty) {
  3293. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3294. this._isBlendFunctionParametersDirty = false;
  3295. }
  3296. };
  3297. return _AlphaState;
  3298. })();
  3299. BABYLON._AlphaState = _AlphaState;
  3300. var compileShader = function (gl, source, type, defines) {
  3301. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3302. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3303. gl.compileShader(shader);
  3304. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3305. throw new Error(gl.getShaderInfoLog(shader));
  3306. }
  3307. return shader;
  3308. };
  3309. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3310. var magFilter = gl.NEAREST;
  3311. var minFilter = gl.NEAREST;
  3312. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3313. magFilter = gl.LINEAR;
  3314. if (generateMipMaps) {
  3315. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3316. }
  3317. else {
  3318. minFilter = gl.LINEAR;
  3319. }
  3320. }
  3321. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3322. magFilter = gl.LINEAR;
  3323. if (generateMipMaps) {
  3324. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3325. }
  3326. else {
  3327. minFilter = gl.LINEAR;
  3328. }
  3329. }
  3330. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3331. magFilter = gl.NEAREST;
  3332. if (generateMipMaps) {
  3333. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3334. }
  3335. else {
  3336. minFilter = gl.NEAREST;
  3337. }
  3338. }
  3339. return {
  3340. min: minFilter,
  3341. mag: magFilter
  3342. };
  3343. };
  3344. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3345. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3346. var engine = scene.getEngine();
  3347. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3348. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3349. gl.bindTexture(gl.TEXTURE_2D, texture);
  3350. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3351. processFunction(potWidth, potHeight);
  3352. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3353. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3354. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3355. if (!noMipmap && !isCompressed) {
  3356. gl.generateMipmap(gl.TEXTURE_2D);
  3357. }
  3358. gl.bindTexture(gl.TEXTURE_2D, null);
  3359. engine._activeTexturesCache = [];
  3360. texture._baseWidth = width;
  3361. texture._baseHeight = height;
  3362. texture._width = potWidth;
  3363. texture._height = potHeight;
  3364. texture.isReady = true;
  3365. texture.samplingMode = samplingMode;
  3366. scene._removePendingData(texture);
  3367. };
  3368. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3369. var onload = function () {
  3370. loadedImages[index] = img;
  3371. loadedImages._internalCount++;
  3372. scene._removePendingData(img);
  3373. if (loadedImages._internalCount === 6) {
  3374. onfinish(loadedImages);
  3375. }
  3376. };
  3377. var onerror = function () {
  3378. scene._removePendingData(img);
  3379. };
  3380. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3381. scene._addPendingData(img);
  3382. };
  3383. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3384. var loadedImages = [];
  3385. loadedImages._internalCount = 0;
  3386. for (var index = 0; index < 6; index++) {
  3387. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3388. }
  3389. };
  3390. var EngineCapabilities = (function () {
  3391. function EngineCapabilities() {
  3392. }
  3393. return EngineCapabilities;
  3394. })();
  3395. BABYLON.EngineCapabilities = EngineCapabilities;
  3396. var Engine = (function () {
  3397. function Engine(canvas, antialias, options) {
  3398. var _this = this;
  3399. // Public members
  3400. this.isFullscreen = false;
  3401. this.isPointerLock = false;
  3402. this.cullBackFaces = true;
  3403. this.renderEvenInBackground = true;
  3404. this.scenes = new Array();
  3405. this._windowIsBackground = false;
  3406. this._loadingDivBackgroundColor = "black";
  3407. this._drawCalls = 0;
  3408. this._renderingQueueLaunched = false;
  3409. this._activeRenderLoops = [];
  3410. // FPS
  3411. this.fpsRange = 60;
  3412. this.previousFramesDuration = [];
  3413. this.fps = 60;
  3414. this.deltaTime = 0;
  3415. // States
  3416. this._depthCullingState = new _DepthCullingState();
  3417. this._alphaState = new _AlphaState();
  3418. this._alphaMode = Engine.ALPHA_DISABLE;
  3419. // Cache
  3420. this._loadedTexturesCache = new Array();
  3421. this._activeTexturesCache = new Array();
  3422. this._compiledEffects = {};
  3423. this._uintIndicesCurrentlySet = false;
  3424. this._renderingCanvas = canvas;
  3425. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3426. options = options || {};
  3427. options.antialias = antialias;
  3428. try {
  3429. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3430. }
  3431. catch (e) {
  3432. throw new Error("WebGL not supported");
  3433. }
  3434. if (!this._gl) {
  3435. throw new Error("WebGL not supported");
  3436. }
  3437. this._onBlur = function () {
  3438. _this._windowIsBackground = true;
  3439. };
  3440. this._onFocus = function () {
  3441. _this._windowIsBackground = false;
  3442. };
  3443. window.addEventListener("blur", this._onBlur);
  3444. window.addEventListener("focus", this._onFocus);
  3445. // Textures
  3446. this._workingCanvas = document.createElement("canvas");
  3447. this._workingContext = this._workingCanvas.getContext("2d");
  3448. // Viewport
  3449. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3450. this.resize();
  3451. // Caps
  3452. this._caps = new EngineCapabilities();
  3453. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3454. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3455. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3456. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3457. // Infos
  3458. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3459. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3460. if (rendererInfo != null) {
  3461. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3462. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3463. }
  3464. if (!this._glVendor) {
  3465. this._glVendor = "Unknown vendor";
  3466. }
  3467. if (!this._glRenderer) {
  3468. this._glRenderer = "Unknown renderer";
  3469. }
  3470. // Extensions
  3471. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3472. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3473. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3474. 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');
  3475. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3476. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3477. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3478. // Depth buffer
  3479. this.setDepthBuffer(true);
  3480. this.setDepthFunctionToLessOrEqual();
  3481. this.setDepthWrite(true);
  3482. // Fullscreen
  3483. this._onFullscreenChange = function () {
  3484. if (document.fullscreen !== undefined) {
  3485. _this.isFullscreen = document.fullscreen;
  3486. }
  3487. else if (document.mozFullScreen !== undefined) {
  3488. _this.isFullscreen = document.mozFullScreen;
  3489. }
  3490. else if (document.webkitIsFullScreen !== undefined) {
  3491. _this.isFullscreen = document.webkitIsFullScreen;
  3492. }
  3493. else if (document.msIsFullScreen !== undefined) {
  3494. _this.isFullscreen = document.msIsFullScreen;
  3495. }
  3496. // Pointer lock
  3497. if (_this.isFullscreen && _this._pointerLockRequested) {
  3498. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3499. if (canvas.requestPointerLock) {
  3500. canvas.requestPointerLock();
  3501. }
  3502. }
  3503. };
  3504. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3505. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3506. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3507. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3508. // Pointer lock
  3509. this._onPointerLockChange = function () {
  3510. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3511. };
  3512. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3513. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3514. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3515. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3516. this._audioEngine = new BABYLON.AudioEngine();
  3517. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3518. }
  3519. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3520. get: function () {
  3521. return Engine._ALPHA_DISABLE;
  3522. },
  3523. enumerable: true,
  3524. configurable: true
  3525. });
  3526. Object.defineProperty(Engine, "ALPHA_ADD", {
  3527. get: function () {
  3528. return Engine._ALPHA_ADD;
  3529. },
  3530. enumerable: true,
  3531. configurable: true
  3532. });
  3533. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3534. get: function () {
  3535. return Engine._ALPHA_COMBINE;
  3536. },
  3537. enumerable: true,
  3538. configurable: true
  3539. });
  3540. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3541. get: function () {
  3542. return Engine._DELAYLOADSTATE_NONE;
  3543. },
  3544. enumerable: true,
  3545. configurable: true
  3546. });
  3547. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3548. get: function () {
  3549. return Engine._DELAYLOADSTATE_LOADED;
  3550. },
  3551. enumerable: true,
  3552. configurable: true
  3553. });
  3554. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3555. get: function () {
  3556. return Engine._DELAYLOADSTATE_LOADING;
  3557. },
  3558. enumerable: true,
  3559. configurable: true
  3560. });
  3561. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3562. get: function () {
  3563. return Engine._DELAYLOADSTATE_NOTLOADED;
  3564. },
  3565. enumerable: true,
  3566. configurable: true
  3567. });
  3568. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3569. get: function () {
  3570. return Engine._TEXTUREFORMAT_ALPHA;
  3571. },
  3572. enumerable: true,
  3573. configurable: true
  3574. });
  3575. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3576. get: function () {
  3577. return Engine._TEXTUREFORMAT_LUMINANCE;
  3578. },
  3579. enumerable: true,
  3580. configurable: true
  3581. });
  3582. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3583. get: function () {
  3584. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3585. },
  3586. enumerable: true,
  3587. configurable: true
  3588. });
  3589. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3590. get: function () {
  3591. return Engine._TEXTUREFORMAT_RGB;
  3592. },
  3593. enumerable: true,
  3594. configurable: true
  3595. });
  3596. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3597. get: function () {
  3598. return Engine._TEXTUREFORMAT_RGBA;
  3599. },
  3600. enumerable: true,
  3601. configurable: true
  3602. });
  3603. Object.defineProperty(Engine, "Version", {
  3604. get: function () {
  3605. return "2.0.0";
  3606. },
  3607. enumerable: true,
  3608. configurable: true
  3609. });
  3610. Engine.prototype.getGlInfo = function () {
  3611. return {
  3612. vendor: this._glVendor,
  3613. renderer: this._glRenderer,
  3614. version: this._glVersion
  3615. };
  3616. };
  3617. Engine.prototype.getAudioEngine = function () {
  3618. return this._audioEngine;
  3619. };
  3620. Engine.prototype.getAspectRatio = function (camera) {
  3621. var viewport = camera.viewport;
  3622. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3623. };
  3624. Engine.prototype.getRenderWidth = function () {
  3625. if (this._currentRenderTarget) {
  3626. return this._currentRenderTarget._width;
  3627. }
  3628. return this._renderingCanvas.width;
  3629. };
  3630. Engine.prototype.getRenderHeight = function () {
  3631. if (this._currentRenderTarget) {
  3632. return this._currentRenderTarget._height;
  3633. }
  3634. return this._renderingCanvas.height;
  3635. };
  3636. Engine.prototype.getRenderingCanvas = function () {
  3637. return this._renderingCanvas;
  3638. };
  3639. Engine.prototype.getRenderingCanvasClientRect = function () {
  3640. return this._renderingCanvas.getBoundingClientRect();
  3641. };
  3642. Engine.prototype.setHardwareScalingLevel = function (level) {
  3643. this._hardwareScalingLevel = level;
  3644. this.resize();
  3645. };
  3646. Engine.prototype.getHardwareScalingLevel = function () {
  3647. return this._hardwareScalingLevel;
  3648. };
  3649. Engine.prototype.getLoadedTexturesCache = function () {
  3650. return this._loadedTexturesCache;
  3651. };
  3652. Engine.prototype.getCaps = function () {
  3653. return this._caps;
  3654. };
  3655. Object.defineProperty(Engine.prototype, "drawCalls", {
  3656. get: function () {
  3657. return this._drawCalls;
  3658. },
  3659. enumerable: true,
  3660. configurable: true
  3661. });
  3662. // Methods
  3663. Engine.prototype.resetDrawCalls = function () {
  3664. this._drawCalls = 0;
  3665. };
  3666. Engine.prototype.setDepthFunctionToGreater = function () {
  3667. this._depthCullingState.depthFunc = this._gl.GREATER;
  3668. };
  3669. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3670. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3671. };
  3672. Engine.prototype.setDepthFunctionToLess = function () {
  3673. this._depthCullingState.depthFunc = this._gl.LESS;
  3674. };
  3675. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3676. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3677. };
  3678. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3679. if (!renderFunction) {
  3680. this._activeRenderLoops = [];
  3681. return;
  3682. }
  3683. var index = this._activeRenderLoops.indexOf(renderFunction);
  3684. if (index >= 0) {
  3685. this._activeRenderLoops.splice(index, 1);
  3686. }
  3687. };
  3688. Engine.prototype._renderLoop = function () {
  3689. var _this = this;
  3690. var shouldRender = true;
  3691. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3692. shouldRender = false;
  3693. }
  3694. if (shouldRender) {
  3695. // Start new frame
  3696. this.beginFrame();
  3697. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3698. var renderFunction = this._activeRenderLoops[index];
  3699. renderFunction();
  3700. }
  3701. // Present
  3702. this.endFrame();
  3703. }
  3704. if (this._activeRenderLoops.length > 0) {
  3705. // Register new frame
  3706. BABYLON.Tools.QueueNewFrame(function () {
  3707. _this._renderLoop();
  3708. });
  3709. }
  3710. else {
  3711. this._renderingQueueLaunched = false;
  3712. }
  3713. };
  3714. Engine.prototype.runRenderLoop = function (renderFunction) {
  3715. var _this = this;
  3716. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3717. return;
  3718. }
  3719. this._activeRenderLoops.push(renderFunction);
  3720. if (!this._renderingQueueLaunched) {
  3721. this._renderingQueueLaunched = true;
  3722. BABYLON.Tools.QueueNewFrame(function () {
  3723. _this._renderLoop();
  3724. });
  3725. }
  3726. };
  3727. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3728. if (this.isFullscreen) {
  3729. BABYLON.Tools.ExitFullscreen();
  3730. }
  3731. else {
  3732. this._pointerLockRequested = requestPointerLock;
  3733. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3734. }
  3735. };
  3736. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3737. this.applyStates();
  3738. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3739. if (this._depthCullingState.depthMask) {
  3740. this._gl.clearDepth(1.0);
  3741. }
  3742. var mode = 0;
  3743. if (backBuffer)
  3744. mode |= this._gl.COLOR_BUFFER_BIT;
  3745. if (depthStencil && this._depthCullingState.depthMask)
  3746. mode |= this._gl.DEPTH_BUFFER_BIT;
  3747. this._gl.clear(mode);
  3748. };
  3749. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  3750. var width = requiredWidth || this._renderingCanvas.width;
  3751. var height = requiredHeight || this._renderingCanvas.height;
  3752. var x = viewport.x || 0;
  3753. var y = viewport.y || 0;
  3754. this._cachedViewport = viewport;
  3755. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  3756. };
  3757. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  3758. this._cachedViewport = null;
  3759. this._gl.viewport(x, y, width, height);
  3760. };
  3761. Engine.prototype.beginFrame = function () {
  3762. this._measureFps();
  3763. };
  3764. Engine.prototype.endFrame = function () {
  3765. this.flushFramebuffer();
  3766. };
  3767. Engine.prototype.resize = function () {
  3768. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  3769. };
  3770. Engine.prototype.setSize = function (width, height) {
  3771. this._renderingCanvas.width = width;
  3772. this._renderingCanvas.height = height;
  3773. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3774. };
  3775. Engine.prototype.bindFramebuffer = function (texture) {
  3776. this._currentRenderTarget = texture;
  3777. var gl = this._gl;
  3778. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  3779. this._gl.viewport(0, 0, texture._width, texture._height);
  3780. this.wipeCaches();
  3781. };
  3782. Engine.prototype.unBindFramebuffer = function (texture) {
  3783. this._currentRenderTarget = null;
  3784. if (texture.generateMipMaps) {
  3785. var gl = this._gl;
  3786. gl.bindTexture(gl.TEXTURE_2D, texture);
  3787. gl.generateMipmap(gl.TEXTURE_2D);
  3788. gl.bindTexture(gl.TEXTURE_2D, null);
  3789. }
  3790. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3791. };
  3792. Engine.prototype.flushFramebuffer = function () {
  3793. // this._gl.flush();
  3794. };
  3795. Engine.prototype.restoreDefaultFramebuffer = function () {
  3796. this._currentRenderTarget = null;
  3797. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  3798. this.setViewport(this._cachedViewport);
  3799. this.wipeCaches();
  3800. };
  3801. // VBOs
  3802. Engine.prototype._resetVertexBufferBinding = function () {
  3803. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  3804. this._cachedVertexBuffers = null;
  3805. };
  3806. Engine.prototype.createVertexBuffer = function (vertices) {
  3807. var vbo = this._gl.createBuffer();
  3808. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3809. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  3810. this._resetVertexBufferBinding();
  3811. vbo.references = 1;
  3812. return vbo;
  3813. };
  3814. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  3815. var vbo = this._gl.createBuffer();
  3816. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  3817. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3818. this._resetVertexBufferBinding();
  3819. vbo.references = 1;
  3820. return vbo;
  3821. };
  3822. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  3823. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3824. if (offset === undefined) {
  3825. offset = 0;
  3826. }
  3827. if (vertices instanceof Float32Array) {
  3828. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  3829. }
  3830. else {
  3831. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  3832. }
  3833. this._resetVertexBufferBinding();
  3834. };
  3835. Engine.prototype._resetIndexBufferBinding = function () {
  3836. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  3837. this._cachedIndexBuffer = null;
  3838. };
  3839. Engine.prototype.createIndexBuffer = function (indices) {
  3840. var vbo = this._gl.createBuffer();
  3841. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  3842. // Check for 32 bits indices
  3843. var arrayBuffer;
  3844. var need32Bits = false;
  3845. if (this._caps.uintIndices) {
  3846. for (var index = 0; index < indices.length; index++) {
  3847. if (indices[index] > 65535) {
  3848. need32Bits = true;
  3849. break;
  3850. }
  3851. }
  3852. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  3853. }
  3854. else {
  3855. arrayBuffer = new Uint16Array(indices);
  3856. }
  3857. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  3858. this._resetIndexBufferBinding();
  3859. vbo.references = 1;
  3860. vbo.is32Bits = need32Bits;
  3861. return vbo;
  3862. };
  3863. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  3864. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  3865. this._cachedVertexBuffers = vertexBuffer;
  3866. this._cachedEffectForVertexBuffers = effect;
  3867. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  3868. var offset = 0;
  3869. for (var index = 0; index < vertexDeclaration.length; index++) {
  3870. var order = effect.getAttributeLocation(index);
  3871. if (order >= 0) {
  3872. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  3873. }
  3874. offset += vertexDeclaration[index] * 4;
  3875. }
  3876. }
  3877. if (this._cachedIndexBuffer !== indexBuffer) {
  3878. this._cachedIndexBuffer = indexBuffer;
  3879. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3880. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3881. }
  3882. };
  3883. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  3884. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  3885. this._cachedVertexBuffers = vertexBuffers;
  3886. this._cachedEffectForVertexBuffers = effect;
  3887. var attributes = effect.getAttributesNames();
  3888. for (var index = 0; index < attributes.length; index++) {
  3889. var order = effect.getAttributeLocation(index);
  3890. if (order >= 0) {
  3891. var vertexBuffer = vertexBuffers[attributes[index]];
  3892. if (!vertexBuffer) {
  3893. continue;
  3894. }
  3895. var stride = vertexBuffer.getStrideSize();
  3896. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  3897. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  3898. }
  3899. }
  3900. }
  3901. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  3902. this._cachedIndexBuffer = indexBuffer;
  3903. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  3904. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  3905. }
  3906. };
  3907. Engine.prototype._releaseBuffer = function (buffer) {
  3908. buffer.references--;
  3909. if (buffer.references === 0) {
  3910. this._gl.deleteBuffer(buffer);
  3911. return true;
  3912. }
  3913. return false;
  3914. };
  3915. Engine.prototype.createInstancesBuffer = function (capacity) {
  3916. var buffer = this._gl.createBuffer();
  3917. buffer.capacity = capacity;
  3918. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  3919. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  3920. return buffer;
  3921. };
  3922. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  3923. this._gl.deleteBuffer(buffer);
  3924. };
  3925. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  3926. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3927. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  3928. for (var index = 0; index < 4; index++) {
  3929. var offsetLocation = offsetLocations[index];
  3930. this._gl.enableVertexAttribArray(offsetLocation);
  3931. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  3932. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  3933. }
  3934. };
  3935. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  3936. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  3937. for (var index = 0; index < 4; index++) {
  3938. var offsetLocation = offsetLocations[index];
  3939. this._gl.disableVertexAttribArray(offsetLocation);
  3940. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  3941. }
  3942. };
  3943. Engine.prototype.applyStates = function () {
  3944. this._depthCullingState.apply(this._gl);
  3945. this._alphaState.apply(this._gl);
  3946. };
  3947. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  3948. // Apply states
  3949. this.applyStates();
  3950. this._drawCalls++;
  3951. // Render
  3952. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  3953. if (instancesCount) {
  3954. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  3955. return;
  3956. }
  3957. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  3958. };
  3959. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  3960. // Apply states
  3961. this.applyStates();
  3962. this._drawCalls++;
  3963. if (instancesCount) {
  3964. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  3965. return;
  3966. }
  3967. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  3968. };
  3969. // Shaders
  3970. Engine.prototype._releaseEffect = function (effect) {
  3971. if (this._compiledEffects[effect._key]) {
  3972. delete this._compiledEffects[effect._key];
  3973. if (effect.getProgram()) {
  3974. this._gl.deleteProgram(effect.getProgram());
  3975. }
  3976. }
  3977. };
  3978. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3979. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  3980. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  3981. var name = vertex + "+" + fragment + "@" + defines;
  3982. if (this._compiledEffects[name]) {
  3983. return this._compiledEffects[name];
  3984. }
  3985. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  3986. effect._key = name;
  3987. this._compiledEffects[name] = effect;
  3988. return effect;
  3989. };
  3990. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  3991. if (uniformsNames === void 0) { uniformsNames = []; }
  3992. if (samplers === void 0) { samplers = []; }
  3993. if (defines === void 0) { defines = ""; }
  3994. return this.createEffect({
  3995. vertex: "particles",
  3996. fragmentElement: fragmentName
  3997. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  3998. };
  3999. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4000. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4001. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4002. var shaderProgram = this._gl.createProgram();
  4003. this._gl.attachShader(shaderProgram, vertexShader);
  4004. this._gl.attachShader(shaderProgram, fragmentShader);
  4005. this._gl.linkProgram(shaderProgram);
  4006. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4007. if (!linked) {
  4008. var error = this._gl.getProgramInfoLog(shaderProgram);
  4009. if (error) {
  4010. throw new Error(error);
  4011. }
  4012. }
  4013. this._gl.deleteShader(vertexShader);
  4014. this._gl.deleteShader(fragmentShader);
  4015. return shaderProgram;
  4016. };
  4017. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4018. var results = [];
  4019. for (var index = 0; index < uniformsNames.length; index++) {
  4020. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4021. }
  4022. return results;
  4023. };
  4024. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4025. var results = [];
  4026. for (var index = 0; index < attributesNames.length; index++) {
  4027. try {
  4028. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4029. }
  4030. catch (e) {
  4031. results.push(-1);
  4032. }
  4033. }
  4034. return results;
  4035. };
  4036. Engine.prototype.enableEffect = function (effect) {
  4037. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4038. if (effect && effect.onBind) {
  4039. effect.onBind(effect);
  4040. }
  4041. return;
  4042. }
  4043. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4044. // Use program
  4045. this._gl.useProgram(effect.getProgram());
  4046. for (var i in this._vertexAttribArrays) {
  4047. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4048. continue;
  4049. }
  4050. this._vertexAttribArrays[i] = false;
  4051. this._gl.disableVertexAttribArray(i);
  4052. }
  4053. var attributesCount = effect.getAttributesCount();
  4054. for (var index = 0; index < attributesCount; index++) {
  4055. // Attributes
  4056. var order = effect.getAttributeLocation(index);
  4057. if (order >= 0) {
  4058. this._vertexAttribArrays[order] = true;
  4059. this._gl.enableVertexAttribArray(order);
  4060. }
  4061. }
  4062. this._currentEffect = effect;
  4063. if (effect.onBind) {
  4064. effect.onBind(effect);
  4065. }
  4066. };
  4067. Engine.prototype.setArray = function (uniform, array) {
  4068. if (!uniform)
  4069. return;
  4070. this._gl.uniform1fv(uniform, array);
  4071. };
  4072. Engine.prototype.setMatrices = function (uniform, matrices) {
  4073. if (!uniform)
  4074. return;
  4075. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4076. };
  4077. Engine.prototype.setMatrix = function (uniform, matrix) {
  4078. if (!uniform)
  4079. return;
  4080. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4081. };
  4082. Engine.prototype.setFloat = function (uniform, value) {
  4083. if (!uniform)
  4084. return;
  4085. this._gl.uniform1f(uniform, value);
  4086. };
  4087. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4088. if (!uniform)
  4089. return;
  4090. this._gl.uniform2f(uniform, x, y);
  4091. };
  4092. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4093. if (!uniform)
  4094. return;
  4095. this._gl.uniform3f(uniform, x, y, z);
  4096. };
  4097. Engine.prototype.setBool = function (uniform, bool) {
  4098. if (!uniform)
  4099. return;
  4100. this._gl.uniform1i(uniform, bool);
  4101. };
  4102. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4103. if (!uniform)
  4104. return;
  4105. this._gl.uniform4f(uniform, x, y, z, w);
  4106. };
  4107. Engine.prototype.setColor3 = function (uniform, color3) {
  4108. if (!uniform)
  4109. return;
  4110. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4111. };
  4112. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4113. if (!uniform)
  4114. return;
  4115. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4116. };
  4117. // States
  4118. Engine.prototype.setState = function (culling, force) {
  4119. // Culling
  4120. if (this._depthCullingState.cull !== culling || force) {
  4121. if (culling) {
  4122. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4123. this._depthCullingState.cull = true;
  4124. }
  4125. else {
  4126. this._depthCullingState.cull = false;
  4127. }
  4128. }
  4129. };
  4130. Engine.prototype.setDepthBuffer = function (enable) {
  4131. this._depthCullingState.depthTest = enable;
  4132. };
  4133. Engine.prototype.getDepthWrite = function () {
  4134. return this._depthCullingState.depthMask;
  4135. };
  4136. Engine.prototype.setDepthWrite = function (enable) {
  4137. this._depthCullingState.depthMask = enable;
  4138. };
  4139. Engine.prototype.setColorWrite = function (enable) {
  4140. this._gl.colorMask(enable, enable, enable, enable);
  4141. };
  4142. Engine.prototype.setAlphaMode = function (mode) {
  4143. switch (mode) {
  4144. case Engine.ALPHA_DISABLE:
  4145. this.setDepthWrite(true);
  4146. this._alphaState.alphaBlend = false;
  4147. break;
  4148. case Engine.ALPHA_COMBINE:
  4149. this.setDepthWrite(false);
  4150. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4151. this._alphaState.alphaBlend = true;
  4152. break;
  4153. case Engine.ALPHA_ADD:
  4154. this.setDepthWrite(false);
  4155. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4156. this._alphaState.alphaBlend = true;
  4157. break;
  4158. }
  4159. this._alphaMode = mode;
  4160. };
  4161. Engine.prototype.getAlphaMode = function () {
  4162. return this._alphaMode;
  4163. };
  4164. Engine.prototype.setAlphaTesting = function (enable) {
  4165. this._alphaTest = enable;
  4166. };
  4167. Engine.prototype.getAlphaTesting = function () {
  4168. return this._alphaTest;
  4169. };
  4170. // Textures
  4171. Engine.prototype.wipeCaches = function () {
  4172. this._activeTexturesCache = [];
  4173. this._currentEffect = null;
  4174. this._depthCullingState.reset();
  4175. this._alphaState.reset();
  4176. this._cachedVertexBuffers = null;
  4177. this._cachedIndexBuffer = null;
  4178. this._cachedEffectForVertexBuffers = null;
  4179. };
  4180. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4181. var gl = this._gl;
  4182. gl.bindTexture(gl.TEXTURE_2D, texture);
  4183. var magFilter = gl.NEAREST;
  4184. var minFilter = gl.NEAREST;
  4185. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4186. magFilter = gl.LINEAR;
  4187. minFilter = gl.LINEAR;
  4188. }
  4189. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4190. magFilter = gl.LINEAR;
  4191. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4192. }
  4193. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4195. gl.bindTexture(gl.TEXTURE_2D, null);
  4196. texture.samplingMode = samplingMode;
  4197. };
  4198. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4199. var _this = this;
  4200. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4201. if (onLoad === void 0) { onLoad = null; }
  4202. if (onError === void 0) { onError = null; }
  4203. if (buffer === void 0) { buffer = null; }
  4204. var texture = this._gl.createTexture();
  4205. var extension;
  4206. var fromData = false;
  4207. if (url.substr(0, 5) === "data:") {
  4208. fromData = true;
  4209. }
  4210. if (!fromData)
  4211. extension = url.substr(url.length - 4, 4).toLowerCase();
  4212. else {
  4213. var oldUrl = url;
  4214. fromData = oldUrl.split(':');
  4215. url = oldUrl;
  4216. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4217. }
  4218. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4219. var isTGA = (extension === ".tga");
  4220. scene._addPendingData(texture);
  4221. texture.url = url;
  4222. texture.noMipmap = noMipmap;
  4223. texture.references = 1;
  4224. this._loadedTexturesCache.push(texture);
  4225. var onerror = function () {
  4226. scene._removePendingData(texture);
  4227. if (onError) {
  4228. onError();
  4229. }
  4230. };
  4231. if (isTGA) {
  4232. var callback = function (arrayBuffer) {
  4233. var data = new Uint8Array(arrayBuffer);
  4234. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4235. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4236. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4237. if (onLoad) {
  4238. onLoad();
  4239. }
  4240. }, samplingMode);
  4241. };
  4242. if (!(fromData instanceof Array))
  4243. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4244. callback(arrayBuffer);
  4245. }, onerror, scene.database, true);
  4246. else
  4247. callback(buffer);
  4248. }
  4249. else if (isDDS) {
  4250. callback = function (data) {
  4251. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4252. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4253. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4254. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4255. if (onLoad) {
  4256. onLoad();
  4257. }
  4258. }, samplingMode);
  4259. };
  4260. if (!(fromData instanceof Array))
  4261. BABYLON.Tools.LoadFile(url, function (data) {
  4262. callback(data);
  4263. }, onerror, scene.database, true);
  4264. else
  4265. callback(buffer);
  4266. }
  4267. else {
  4268. var onload = function (img) {
  4269. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4270. var isPot = (img.width === potWidth && img.height === potHeight);
  4271. if (!isPot) {
  4272. _this._workingCanvas.width = potWidth;
  4273. _this._workingCanvas.height = potHeight;
  4274. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4275. _this._workingContext.imageSmoothingEnabled = false;
  4276. _this._workingContext.mozImageSmoothingEnabled = false;
  4277. _this._workingContext.oImageSmoothingEnabled = false;
  4278. _this._workingContext.webkitImageSmoothingEnabled = false;
  4279. _this._workingContext.msImageSmoothingEnabled = false;
  4280. }
  4281. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4282. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4283. _this._workingContext.imageSmoothingEnabled = true;
  4284. _this._workingContext.mozImageSmoothingEnabled = true;
  4285. _this._workingContext.oImageSmoothingEnabled = true;
  4286. _this._workingContext.webkitImageSmoothingEnabled = true;
  4287. _this._workingContext.msImageSmoothingEnabled = true;
  4288. }
  4289. }
  4290. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4291. if (onLoad) {
  4292. onLoad();
  4293. }
  4294. }, samplingMode);
  4295. };
  4296. if (!(fromData instanceof Array))
  4297. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4298. else
  4299. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4300. }
  4301. return texture;
  4302. };
  4303. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4304. var texture = this._gl.createTexture();
  4305. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4306. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4307. // Format
  4308. var internalFormat = this._gl.RGBA;
  4309. switch (format) {
  4310. case Engine.TEXTUREFORMAT_ALPHA:
  4311. internalFormat = this._gl.ALPHA;
  4312. break;
  4313. case Engine.TEXTUREFORMAT_LUMINANCE:
  4314. internalFormat = this._gl.LUMINANCE;
  4315. break;
  4316. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4317. internalFormat = this._gl.LUMINANCE_ALPHA;
  4318. break;
  4319. case Engine.TEXTUREFORMAT_RGB:
  4320. internalFormat = this._gl.RGB;
  4321. break;
  4322. case Engine.TEXTUREFORMAT_RGBA:
  4323. internalFormat = this._gl.RGBA;
  4324. break;
  4325. }
  4326. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4327. if (generateMipMaps) {
  4328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4329. }
  4330. // Filters
  4331. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4333. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4334. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4335. this._activeTexturesCache = [];
  4336. texture._baseWidth = width;
  4337. texture._baseHeight = height;
  4338. texture._width = width;
  4339. texture._height = height;
  4340. texture.isReady = true;
  4341. texture.references = 1;
  4342. texture.samplingMode = samplingMode;
  4343. this._loadedTexturesCache.push(texture);
  4344. return texture;
  4345. };
  4346. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4347. var texture = this._gl.createTexture();
  4348. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4349. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4350. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4351. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4352. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4353. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4354. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4355. this._activeTexturesCache = [];
  4356. texture._baseWidth = width;
  4357. texture._baseHeight = height;
  4358. texture._width = width;
  4359. texture._height = height;
  4360. texture.isReady = false;
  4361. texture.generateMipMaps = generateMipMaps;
  4362. texture.references = 1;
  4363. texture.samplingMode = samplingMode;
  4364. this._loadedTexturesCache.push(texture);
  4365. return texture;
  4366. };
  4367. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4368. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4369. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4370. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4371. if (texture.generateMipMaps) {
  4372. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4373. }
  4374. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4375. this._activeTexturesCache = [];
  4376. texture.isReady = true;
  4377. };
  4378. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4379. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4380. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4381. // Scale the video if it is a NPOT using the current working canvas
  4382. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4383. if (!texture._workingCanvas) {
  4384. texture._workingCanvas = document.createElement("canvas");
  4385. texture._workingContext = texture._workingCanvas.getContext("2d");
  4386. texture._workingCanvas.width = texture._width;
  4387. texture._workingCanvas.height = texture._height;
  4388. }
  4389. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4390. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4391. }
  4392. else {
  4393. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4394. }
  4395. if (texture.generateMipMaps) {
  4396. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4397. }
  4398. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4399. this._activeTexturesCache = [];
  4400. texture.isReady = true;
  4401. };
  4402. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4403. // old version had a "generateMipMaps" arg instead of options.
  4404. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4405. // in the same way, generateDepthBuffer is defaulted to true
  4406. var generateMipMaps = false;
  4407. var generateDepthBuffer = true;
  4408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4409. if (options !== undefined) {
  4410. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4412. if (options.samplingMode !== undefined) {
  4413. samplingMode = options.samplingMode;
  4414. }
  4415. }
  4416. var gl = this._gl;
  4417. var texture = gl.createTexture();
  4418. gl.bindTexture(gl.TEXTURE_2D, texture);
  4419. var width = size.width || size;
  4420. var height = size.height || size;
  4421. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4422. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4423. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4424. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4425. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4426. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  4427. var depthBuffer;
  4428. // Create the depth buffer
  4429. if (generateDepthBuffer) {
  4430. depthBuffer = gl.createRenderbuffer();
  4431. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4432. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4433. }
  4434. // Create the framebuffer
  4435. var framebuffer = gl.createFramebuffer();
  4436. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4437. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4438. if (generateDepthBuffer) {
  4439. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4440. }
  4441. // Unbind
  4442. gl.bindTexture(gl.TEXTURE_2D, null);
  4443. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4444. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4445. texture._framebuffer = framebuffer;
  4446. if (generateDepthBuffer) {
  4447. texture._depthBuffer = depthBuffer;
  4448. }
  4449. texture._width = width;
  4450. texture._height = height;
  4451. texture.isReady = true;
  4452. texture.generateMipMaps = generateMipMaps;
  4453. texture.references = 1;
  4454. texture.samplingMode = samplingMode;
  4455. this._activeTexturesCache = [];
  4456. this._loadedTexturesCache.push(texture);
  4457. return texture;
  4458. };
  4459. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4460. var _this = this;
  4461. var gl = this._gl;
  4462. var texture = gl.createTexture();
  4463. texture.isCube = true;
  4464. texture.url = rootUrl;
  4465. texture.references = 1;
  4466. this._loadedTexturesCache.push(texture);
  4467. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4468. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4469. if (isDDS) {
  4470. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4471. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4472. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4473. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4474. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4475. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4476. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4477. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4478. }
  4479. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4480. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4481. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4482. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4483. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4484. _this._activeTexturesCache = [];
  4485. texture._width = info.width;
  4486. texture._height = info.height;
  4487. texture.isReady = true;
  4488. }, null, null, true);
  4489. }
  4490. else {
  4491. cascadeLoad(rootUrl, scene, function (imgs) {
  4492. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4493. var height = width;
  4494. _this._workingCanvas.width = width;
  4495. _this._workingCanvas.height = height;
  4496. var faces = [
  4497. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4498. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4499. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4500. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4501. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4502. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4503. ];
  4504. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4505. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4506. for (var index = 0; index < faces.length; index++) {
  4507. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4508. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4509. }
  4510. if (!noMipmap) {
  4511. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4512. }
  4513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4517. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4518. _this._activeTexturesCache = [];
  4519. texture._width = width;
  4520. texture._height = height;
  4521. texture.isReady = true;
  4522. }, extensions);
  4523. }
  4524. return texture;
  4525. };
  4526. Engine.prototype._releaseTexture = function (texture) {
  4527. var gl = this._gl;
  4528. if (texture._framebuffer) {
  4529. gl.deleteFramebuffer(texture._framebuffer);
  4530. }
  4531. if (texture._depthBuffer) {
  4532. gl.deleteRenderbuffer(texture._depthBuffer);
  4533. }
  4534. gl.deleteTexture(texture);
  4535. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4536. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4537. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4538. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4539. this._activeTexturesCache[channel] = null;
  4540. }
  4541. var index = this._loadedTexturesCache.indexOf(texture);
  4542. if (index !== -1) {
  4543. this._loadedTexturesCache.splice(index, 1);
  4544. }
  4545. };
  4546. Engine.prototype.bindSamplers = function (effect) {
  4547. this._gl.useProgram(effect.getProgram());
  4548. var samplers = effect.getSamplers();
  4549. for (var index = 0; index < samplers.length; index++) {
  4550. var uniform = effect.getUniform(samplers[index]);
  4551. this._gl.uniform1i(uniform, index);
  4552. }
  4553. this._currentEffect = null;
  4554. };
  4555. Engine.prototype._bindTexture = function (channel, texture) {
  4556. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4557. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4558. this._activeTexturesCache[channel] = null;
  4559. };
  4560. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4561. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4562. };
  4563. Engine.prototype.setTexture = function (channel, texture) {
  4564. if (channel < 0) {
  4565. return;
  4566. }
  4567. // Not ready?
  4568. if (!texture || !texture.isReady()) {
  4569. if (this._activeTexturesCache[channel] != null) {
  4570. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4571. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4572. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4573. this._activeTexturesCache[channel] = null;
  4574. }
  4575. return;
  4576. }
  4577. // Video
  4578. if (texture instanceof BABYLON.VideoTexture) {
  4579. if (texture.update()) {
  4580. this._activeTexturesCache[channel] = null;
  4581. }
  4582. }
  4583. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4584. texture.delayLoad();
  4585. return;
  4586. }
  4587. if (this._activeTexturesCache[channel] === texture) {
  4588. return;
  4589. }
  4590. this._activeTexturesCache[channel] = texture;
  4591. var internalTexture = texture.getInternalTexture();
  4592. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4593. if (internalTexture.isCube) {
  4594. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4595. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4596. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4597. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4598. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4599. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4600. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4601. }
  4602. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4603. }
  4604. else {
  4605. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4606. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4607. internalTexture._cachedWrapU = texture.wrapU;
  4608. switch (texture.wrapU) {
  4609. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4610. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4611. break;
  4612. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4613. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4614. break;
  4615. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4616. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4617. break;
  4618. }
  4619. }
  4620. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4621. internalTexture._cachedWrapV = texture.wrapV;
  4622. switch (texture.wrapV) {
  4623. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4625. break;
  4626. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4627. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4628. break;
  4629. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4630. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4631. break;
  4632. }
  4633. }
  4634. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4635. }
  4636. };
  4637. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4638. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4639. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4640. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4641. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4642. }
  4643. };
  4644. Engine.prototype.readPixels = function (x, y, width, height) {
  4645. var data = new Uint8Array(height * width * 4);
  4646. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4647. return data;
  4648. };
  4649. // Dispose
  4650. Engine.prototype.dispose = function () {
  4651. this.hideLoadingUI();
  4652. this.stopRenderLoop();
  4653. while (this.scenes.length) {
  4654. this.scenes[0].dispose();
  4655. }
  4656. for (var name in this._compiledEffects) {
  4657. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4658. }
  4659. for (var i in this._vertexAttribArrays) {
  4660. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4661. continue;
  4662. }
  4663. this._gl.disableVertexAttribArray(i);
  4664. }
  4665. // Events
  4666. window.removeEventListener("blur", this._onBlur);
  4667. window.removeEventListener("focus", this._onFocus);
  4668. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4669. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4670. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4671. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4672. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4673. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4674. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4675. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4676. };
  4677. // Loading screen
  4678. Engine.prototype.displayLoadingUI = function () {
  4679. var _this = this;
  4680. this._loadingDiv = document.createElement("div");
  4681. this._loadingDiv.style.opacity = "0";
  4682. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4683. // Loading text
  4684. this._loadingTextDiv = document.createElement("div");
  4685. this._loadingTextDiv.style.position = "absolute";
  4686. this._loadingTextDiv.style.left = "0";
  4687. this._loadingTextDiv.style.top = "50%";
  4688. this._loadingTextDiv.style.marginTop = "80px";
  4689. this._loadingTextDiv.style.width = "100%";
  4690. this._loadingTextDiv.style.height = "20px";
  4691. this._loadingTextDiv.style.fontFamily = "Arial";
  4692. this._loadingTextDiv.style.fontSize = "14px";
  4693. this._loadingTextDiv.style.color = "white";
  4694. this._loadingTextDiv.style.textAlign = "center";
  4695. this._loadingTextDiv.innerHTML = "Loading";
  4696. this._loadingDiv.appendChild(this._loadingTextDiv);
  4697. // Loading img
  4698. var imgBack = new Image();
  4699. 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==";
  4700. imgBack.style.position = "absolute";
  4701. imgBack.style.left = "50%";
  4702. imgBack.style.top = "50%";
  4703. imgBack.style.marginLeft = "-50px";
  4704. imgBack.style.marginTop = "-50px";
  4705. imgBack.style.transition = "transform 1.0s ease";
  4706. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  4707. var deg = 360;
  4708. var onTransitionEnd = function () {
  4709. deg += 360;
  4710. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  4711. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  4712. };
  4713. imgBack.addEventListener("transitionend", onTransitionEnd);
  4714. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  4715. this._loadingDiv.appendChild(imgBack);
  4716. // front image
  4717. var imgFront = new Image();
  4718. 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=";
  4719. imgFront.style.position = "absolute";
  4720. imgFront.style.left = "50%";
  4721. imgFront.style.top = "50%";
  4722. imgFront.style.marginLeft = "-50px";
  4723. imgFront.style.marginTop = "-50px";
  4724. this._loadingDiv.appendChild(imgFront);
  4725. // Resize
  4726. this._resizeLoadingUI = function () {
  4727. var canvasRect = _this.getRenderingCanvasClientRect();
  4728. _this._loadingDiv.style.position = "absolute";
  4729. _this._loadingDiv.style.left = canvasRect.left + "px";
  4730. _this._loadingDiv.style.top = canvasRect.top + "px";
  4731. _this._loadingDiv.style.width = canvasRect.width + "px";
  4732. _this._loadingDiv.style.height = canvasRect.height + "px";
  4733. };
  4734. this._resizeLoadingUI();
  4735. window.addEventListener("resize", this._resizeLoadingUI);
  4736. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4737. document.body.appendChild(this._loadingDiv);
  4738. setTimeout(function () {
  4739. _this._loadingDiv.style.opacity = "1";
  4740. imgBack.style.transform = "rotateZ(360deg)";
  4741. imgBack.style.webkitTransform = "rotateZ(360deg)";
  4742. }, 0);
  4743. };
  4744. Object.defineProperty(Engine.prototype, "loadingUIText", {
  4745. set: function (text) {
  4746. if (!this._loadingDiv) {
  4747. return;
  4748. }
  4749. this._loadingTextDiv.innerHTML = text;
  4750. },
  4751. enumerable: true,
  4752. configurable: true
  4753. });
  4754. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  4755. get: function () {
  4756. return this._loadingDivBackgroundColor;
  4757. },
  4758. set: function (color) {
  4759. this._loadingDivBackgroundColor = color;
  4760. if (!this._loadingDiv) {
  4761. return;
  4762. }
  4763. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  4764. },
  4765. enumerable: true,
  4766. configurable: true
  4767. });
  4768. Engine.prototype.hideLoadingUI = function () {
  4769. var _this = this;
  4770. if (!this._loadingDiv) {
  4771. return;
  4772. }
  4773. var onTransitionEnd = function () {
  4774. if (!_this._loadingDiv) {
  4775. return;
  4776. }
  4777. document.body.removeChild(_this._loadingDiv);
  4778. window.removeEventListener("resize", _this._resizeLoadingUI);
  4779. _this._loadingDiv = null;
  4780. };
  4781. this._loadingDiv.style.opacity = "0";
  4782. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  4783. };
  4784. // FPS
  4785. Engine.prototype.getFps = function () {
  4786. return this.fps;
  4787. };
  4788. Engine.prototype.getDeltaTime = function () {
  4789. return this.deltaTime;
  4790. };
  4791. Engine.prototype._measureFps = function () {
  4792. this.previousFramesDuration.push(BABYLON.Tools.Now);
  4793. var length = this.previousFramesDuration.length;
  4794. if (length >= 2) {
  4795. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  4796. }
  4797. if (length >= this.fpsRange) {
  4798. if (length > this.fpsRange) {
  4799. this.previousFramesDuration.splice(0, 1);
  4800. length = this.previousFramesDuration.length;
  4801. }
  4802. var sum = 0;
  4803. for (var id = 0; id < length - 1; id++) {
  4804. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  4805. }
  4806. this.fps = 1000.0 / (sum / (length - 1));
  4807. }
  4808. };
  4809. // Statics
  4810. Engine.isSupported = function () {
  4811. try {
  4812. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  4813. if (navigator.isCocoonJS) {
  4814. return true;
  4815. }
  4816. var tempcanvas = document.createElement("canvas");
  4817. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  4818. return gl != null && !!window.WebGLRenderingContext;
  4819. }
  4820. catch (e) {
  4821. return false;
  4822. }
  4823. };
  4824. // Const statics
  4825. Engine._ALPHA_DISABLE = 0;
  4826. Engine._ALPHA_ADD = 1;
  4827. Engine._ALPHA_COMBINE = 2;
  4828. Engine._DELAYLOADSTATE_NONE = 0;
  4829. Engine._DELAYLOADSTATE_LOADED = 1;
  4830. Engine._DELAYLOADSTATE_LOADING = 2;
  4831. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  4832. Engine._TEXTUREFORMAT_ALPHA = 0;
  4833. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  4834. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  4835. Engine._TEXTUREFORMAT_RGB = 4;
  4836. Engine._TEXTUREFORMAT_RGBA = 4;
  4837. // Updatable statics so stick with vars here
  4838. Engine.Epsilon = 0.001;
  4839. Engine.CollisionsEpsilon = 0.001;
  4840. Engine.ShadersRepository = "Babylon/Shaders/";
  4841. return Engine;
  4842. })();
  4843. BABYLON.Engine = Engine;
  4844. })(BABYLON || (BABYLON = {}));
  4845. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  4846. (function (BABYLON) {
  4847. var Node = (function () {
  4848. function Node(name, scene) {
  4849. this.state = "";
  4850. this.animations = new Array();
  4851. this._childrenFlag = -1;
  4852. this._isEnabled = true;
  4853. this._isReady = true;
  4854. this._currentRenderId = -1;
  4855. this.name = name;
  4856. this.id = name;
  4857. this._scene = scene;
  4858. this._initCache();
  4859. }
  4860. Node.prototype.getScene = function () {
  4861. return this._scene;
  4862. };
  4863. Node.prototype.getEngine = function () {
  4864. return this._scene.getEngine();
  4865. };
  4866. // override it in derived class
  4867. Node.prototype.getWorldMatrix = function () {
  4868. return BABYLON.Matrix.Identity();
  4869. };
  4870. // override it in derived class if you add new variables to the cache
  4871. // and call the parent class method
  4872. Node.prototype._initCache = function () {
  4873. this._cache = {};
  4874. this._cache.parent = undefined;
  4875. };
  4876. Node.prototype.updateCache = function (force) {
  4877. if (!force && this.isSynchronized())
  4878. return;
  4879. this._cache.parent = this.parent;
  4880. this._updateCache();
  4881. };
  4882. // override it in derived class if you add new variables to the cache
  4883. // and call the parent class method if !ignoreParentClass
  4884. Node.prototype._updateCache = function (ignoreParentClass) {
  4885. };
  4886. // override it in derived class if you add new variables to the cache
  4887. Node.prototype._isSynchronized = function () {
  4888. return true;
  4889. };
  4890. Node.prototype.isSynchronizedWithParent = function () {
  4891. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  4892. };
  4893. Node.prototype.isSynchronized = function (updateCache) {
  4894. var check = this.hasNewParent();
  4895. check = check || !this.isSynchronizedWithParent();
  4896. check = check || !this._isSynchronized();
  4897. if (updateCache)
  4898. this.updateCache(true);
  4899. return !check;
  4900. };
  4901. Node.prototype.hasNewParent = function (update) {
  4902. if (this._cache.parent === this.parent)
  4903. return false;
  4904. if (update)
  4905. this._cache.parent = this.parent;
  4906. return true;
  4907. };
  4908. Node.prototype.isReady = function () {
  4909. return this._isReady;
  4910. };
  4911. Node.prototype.isEnabled = function () {
  4912. if (!this._isEnabled) {
  4913. return false;
  4914. }
  4915. if (this.parent) {
  4916. return this.parent.isEnabled();
  4917. }
  4918. return true;
  4919. };
  4920. Node.prototype.setEnabled = function (value) {
  4921. this._isEnabled = value;
  4922. };
  4923. Node.prototype.isDescendantOf = function (ancestor) {
  4924. if (this.parent) {
  4925. if (this.parent === ancestor) {
  4926. return true;
  4927. }
  4928. return this.parent.isDescendantOf(ancestor);
  4929. }
  4930. return false;
  4931. };
  4932. Node.prototype._getDescendants = function (list, results) {
  4933. for (var index = 0; index < list.length; index++) {
  4934. var item = list[index];
  4935. if (item.isDescendantOf(this)) {
  4936. results.push(item);
  4937. }
  4938. }
  4939. };
  4940. Node.prototype.getDescendants = function () {
  4941. var results = [];
  4942. this._getDescendants(this._scene.meshes, results);
  4943. this._getDescendants(this._scene.lights, results);
  4944. this._getDescendants(this._scene.cameras, results);
  4945. return results;
  4946. };
  4947. Node.prototype._setReady = function (state) {
  4948. if (state == this._isReady) {
  4949. return;
  4950. }
  4951. if (!state) {
  4952. this._isReady = false;
  4953. return;
  4954. }
  4955. this._isReady = true;
  4956. if (this.onReady) {
  4957. this.onReady(this);
  4958. }
  4959. };
  4960. return Node;
  4961. })();
  4962. BABYLON.Node = Node;
  4963. })(BABYLON || (BABYLON = {}));
  4964. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  4965. (function (BABYLON) {
  4966. var BoundingSphere = (function () {
  4967. function BoundingSphere(minimum, maximum) {
  4968. this.minimum = minimum;
  4969. this.maximum = maximum;
  4970. this._tempRadiusVector = BABYLON.Vector3.Zero();
  4971. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  4972. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  4973. this.radius = distance * 0.5;
  4974. this.centerWorld = BABYLON.Vector3.Zero();
  4975. this._update(BABYLON.Matrix.Identity());
  4976. }
  4977. // Methods
  4978. BoundingSphere.prototype._update = function (world) {
  4979. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  4980. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  4981. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  4982. };
  4983. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  4984. for (var i = 0; i < 6; i++) {
  4985. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  4986. return false;
  4987. }
  4988. return true;
  4989. };
  4990. BoundingSphere.prototype.intersectsPoint = function (point) {
  4991. var x = this.centerWorld.x - point.x;
  4992. var y = this.centerWorld.y - point.y;
  4993. var z = this.centerWorld.z - point.z;
  4994. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  4995. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  4996. return false;
  4997. return true;
  4998. };
  4999. // Statics
  5000. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5001. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5002. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5003. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5004. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5005. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5006. return false;
  5007. return true;
  5008. };
  5009. return BoundingSphere;
  5010. })();
  5011. BABYLON.BoundingSphere = BoundingSphere;
  5012. })(BABYLON || (BABYLON = {}));
  5013. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5014. (function (BABYLON) {
  5015. var BoundingBox = (function () {
  5016. function BoundingBox(minimum, maximum) {
  5017. this.minimum = minimum;
  5018. this.maximum = maximum;
  5019. this.vectors = new Array();
  5020. this.vectorsWorld = new Array();
  5021. // Bounding vectors
  5022. this.vectors.push(this.minimum.clone());
  5023. this.vectors.push(this.maximum.clone());
  5024. this.vectors.push(this.minimum.clone());
  5025. this.vectors[2].x = this.maximum.x;
  5026. this.vectors.push(this.minimum.clone());
  5027. this.vectors[3].y = this.maximum.y;
  5028. this.vectors.push(this.minimum.clone());
  5029. this.vectors[4].z = this.maximum.z;
  5030. this.vectors.push(this.maximum.clone());
  5031. this.vectors[5].z = this.minimum.z;
  5032. this.vectors.push(this.maximum.clone());
  5033. this.vectors[6].x = this.minimum.x;
  5034. this.vectors.push(this.maximum.clone());
  5035. this.vectors[7].y = this.minimum.y;
  5036. // OBB
  5037. this.center = this.maximum.add(this.minimum).scale(0.5);
  5038. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5039. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5040. for (var index = 0; index < this.vectors.length; index++) {
  5041. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5042. }
  5043. this.minimumWorld = BABYLON.Vector3.Zero();
  5044. this.maximumWorld = BABYLON.Vector3.Zero();
  5045. this._update(BABYLON.Matrix.Identity());
  5046. }
  5047. // Methods
  5048. BoundingBox.prototype.getWorldMatrix = function () {
  5049. return this._worldMatrix;
  5050. };
  5051. BoundingBox.prototype._update = function (world) {
  5052. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5053. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5054. for (var index = 0; index < this.vectors.length; index++) {
  5055. var v = this.vectorsWorld[index];
  5056. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5057. if (v.x < this.minimumWorld.x)
  5058. this.minimumWorld.x = v.x;
  5059. if (v.y < this.minimumWorld.y)
  5060. this.minimumWorld.y = v.y;
  5061. if (v.z < this.minimumWorld.z)
  5062. this.minimumWorld.z = v.z;
  5063. if (v.x > this.maximumWorld.x)
  5064. this.maximumWorld.x = v.x;
  5065. if (v.y > this.maximumWorld.y)
  5066. this.maximumWorld.y = v.y;
  5067. if (v.z > this.maximumWorld.z)
  5068. this.maximumWorld.z = v.z;
  5069. }
  5070. // OBB
  5071. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5072. this.center.scaleInPlace(0.5);
  5073. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5074. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5075. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5076. this._worldMatrix = world;
  5077. };
  5078. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5079. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5080. };
  5081. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5082. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5083. };
  5084. BoundingBox.prototype.intersectsPoint = function (point) {
  5085. var delta = BABYLON.Engine.Epsilon;
  5086. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5087. return false;
  5088. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5089. return false;
  5090. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5091. return false;
  5092. return true;
  5093. };
  5094. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5095. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5096. };
  5097. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5098. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5099. return false;
  5100. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5101. return false;
  5102. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5103. return false;
  5104. return true;
  5105. };
  5106. // Statics
  5107. BoundingBox.Intersects = function (box0, box1) {
  5108. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5109. return false;
  5110. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5111. return false;
  5112. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5113. return false;
  5114. return true;
  5115. };
  5116. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5117. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5118. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5119. return (num <= (sphereRadius * sphereRadius));
  5120. };
  5121. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5122. for (var p = 0; p < 6; p++) {
  5123. for (var i = 0; i < 8; i++) {
  5124. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5125. return false;
  5126. }
  5127. }
  5128. }
  5129. return true;
  5130. };
  5131. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5132. for (var p = 0; p < 6; p++) {
  5133. var inCount = 8;
  5134. for (var i = 0; i < 8; i++) {
  5135. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5136. --inCount;
  5137. }
  5138. else {
  5139. break;
  5140. }
  5141. }
  5142. if (inCount == 0)
  5143. return false;
  5144. }
  5145. return true;
  5146. };
  5147. return BoundingBox;
  5148. })();
  5149. BABYLON.BoundingBox = BoundingBox;
  5150. })(BABYLON || (BABYLON = {}));
  5151. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5152. (function (BABYLON) {
  5153. var computeBoxExtents = function (axis, box) {
  5154. var p = BABYLON.Vector3.Dot(box.center, axis);
  5155. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5156. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5157. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5158. var r = r0 + r1 + r2;
  5159. return {
  5160. min: p - r,
  5161. max: p + r
  5162. };
  5163. };
  5164. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5165. var axisOverlap = function (axis, box0, box1) {
  5166. var result0 = computeBoxExtents(axis, box0);
  5167. var result1 = computeBoxExtents(axis, box1);
  5168. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5169. };
  5170. var BoundingInfo = (function () {
  5171. function BoundingInfo(minimum, maximum) {
  5172. this.minimum = minimum;
  5173. this.maximum = maximum;
  5174. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5175. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5176. }
  5177. // Methods
  5178. BoundingInfo.prototype._update = function (world) {
  5179. this.boundingBox._update(world);
  5180. this.boundingSphere._update(world);
  5181. };
  5182. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5183. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5184. return false;
  5185. return this.boundingBox.isInFrustum(frustumPlanes);
  5186. };
  5187. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5188. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5189. };
  5190. BoundingInfo.prototype._checkCollision = function (collider) {
  5191. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5192. };
  5193. BoundingInfo.prototype.intersectsPoint = function (point) {
  5194. if (!this.boundingSphere.centerWorld) {
  5195. return false;
  5196. }
  5197. if (!this.boundingSphere.intersectsPoint(point)) {
  5198. return false;
  5199. }
  5200. if (!this.boundingBox.intersectsPoint(point)) {
  5201. return false;
  5202. }
  5203. return true;
  5204. };
  5205. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5206. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5207. return false;
  5208. }
  5209. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5210. return false;
  5211. }
  5212. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5213. return false;
  5214. }
  5215. if (!precise) {
  5216. return true;
  5217. }
  5218. var box0 = this.boundingBox;
  5219. var box1 = boundingInfo.boundingBox;
  5220. if (!axisOverlap(box0.directions[0], box0, box1))
  5221. return false;
  5222. if (!axisOverlap(box0.directions[1], box0, box1))
  5223. return false;
  5224. if (!axisOverlap(box0.directions[2], box0, box1))
  5225. return false;
  5226. if (!axisOverlap(box1.directions[0], box0, box1))
  5227. return false;
  5228. if (!axisOverlap(box1.directions[1], box0, box1))
  5229. return false;
  5230. if (!axisOverlap(box1.directions[2], box0, box1))
  5231. return false;
  5232. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5233. return false;
  5234. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5235. return false;
  5236. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5237. return false;
  5238. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5239. return false;
  5240. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5241. return false;
  5242. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5243. return false;
  5244. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5245. return false;
  5246. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5247. return false;
  5248. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5249. return false;
  5250. return true;
  5251. };
  5252. return BoundingInfo;
  5253. })();
  5254. BABYLON.BoundingInfo = BoundingInfo;
  5255. })(BABYLON || (BABYLON = {}));
  5256. //# sourceMappingURL=babylon.boundingInfo.js.map
  5257. var BABYLON;
  5258. (function (BABYLON) {
  5259. var Light = (function (_super) {
  5260. __extends(Light, _super);
  5261. function Light(name, scene) {
  5262. _super.call(this, name, scene);
  5263. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5264. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5265. this.intensity = 1.0;
  5266. this.range = Number.MAX_VALUE;
  5267. this.includedOnlyMeshes = new Array();
  5268. this.excludedMeshes = new Array();
  5269. this._excludedMeshesIds = new Array();
  5270. this._includedOnlyMeshesIds = new Array();
  5271. scene.lights.push(this);
  5272. }
  5273. Light.prototype.getShadowGenerator = function () {
  5274. return this._shadowGenerator;
  5275. };
  5276. Light.prototype.getAbsolutePosition = function () {
  5277. return BABYLON.Vector3.Zero();
  5278. };
  5279. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5280. };
  5281. Light.prototype._getWorldMatrix = function () {
  5282. return BABYLON.Matrix.Identity();
  5283. };
  5284. Light.prototype.canAffectMesh = function (mesh) {
  5285. if (!mesh) {
  5286. return true;
  5287. }
  5288. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5289. return false;
  5290. }
  5291. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5292. return false;
  5293. }
  5294. return true;
  5295. };
  5296. Light.prototype.getWorldMatrix = function () {
  5297. this._currentRenderId = this.getScene().getRenderId();
  5298. var worldMatrix = this._getWorldMatrix();
  5299. if (this.parent && this.parent.getWorldMatrix) {
  5300. if (!this._parentedWorldMatrix) {
  5301. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5302. }
  5303. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5304. return this._parentedWorldMatrix;
  5305. }
  5306. return worldMatrix;
  5307. };
  5308. Light.prototype.dispose = function () {
  5309. if (this._shadowGenerator) {
  5310. this._shadowGenerator.dispose();
  5311. this._shadowGenerator = null;
  5312. }
  5313. // Remove from scene
  5314. var index = this.getScene().lights.indexOf(this);
  5315. this.getScene().lights.splice(index, 1);
  5316. };
  5317. return Light;
  5318. })(BABYLON.Node);
  5319. BABYLON.Light = Light;
  5320. })(BABYLON || (BABYLON = {}));
  5321. //# sourceMappingURL=babylon.light.js.map
  5322. var BABYLON;
  5323. (function (BABYLON) {
  5324. var PointLight = (function (_super) {
  5325. __extends(PointLight, _super);
  5326. function PointLight(name, position, scene) {
  5327. _super.call(this, name, scene);
  5328. this.position = position;
  5329. }
  5330. PointLight.prototype.getAbsolutePosition = function () {
  5331. return this._transformedPosition ? this._transformedPosition : this.position;
  5332. };
  5333. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5334. if (this.parent && this.parent.getWorldMatrix) {
  5335. if (!this._transformedPosition) {
  5336. this._transformedPosition = BABYLON.Vector3.Zero();
  5337. }
  5338. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5339. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5340. return;
  5341. }
  5342. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5343. };
  5344. PointLight.prototype.getShadowGenerator = function () {
  5345. return null;
  5346. };
  5347. PointLight.prototype._getWorldMatrix = function () {
  5348. if (!this._worldMatrix) {
  5349. this._worldMatrix = BABYLON.Matrix.Identity();
  5350. }
  5351. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5352. return this._worldMatrix;
  5353. };
  5354. return PointLight;
  5355. })(BABYLON.Light);
  5356. BABYLON.PointLight = PointLight;
  5357. })(BABYLON || (BABYLON = {}));
  5358. //# sourceMappingURL=babylon.pointLight.js.map
  5359. var BABYLON;
  5360. (function (BABYLON) {
  5361. var SpotLight = (function (_super) {
  5362. __extends(SpotLight, _super);
  5363. function SpotLight(name, position, direction, angle, exponent, scene) {
  5364. _super.call(this, name, scene);
  5365. this.position = position;
  5366. this.direction = direction;
  5367. this.angle = angle;
  5368. this.exponent = exponent;
  5369. }
  5370. SpotLight.prototype.getAbsolutePosition = function () {
  5371. return this.transformedPosition ? this.transformedPosition : this.position;
  5372. };
  5373. SpotLight.prototype.setDirectionToTarget = function (target) {
  5374. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5375. return this.direction;
  5376. };
  5377. SpotLight.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. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5388. var normalizeDirection;
  5389. if (this.parent && this.parent.getWorldMatrix) {
  5390. if (!this._transformedDirection) {
  5391. this._transformedDirection = BABYLON.Vector3.Zero();
  5392. }
  5393. this.computeTransformedPosition();
  5394. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5395. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5396. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5397. }
  5398. else {
  5399. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5400. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5401. }
  5402. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5403. };
  5404. SpotLight.prototype._getWorldMatrix = function () {
  5405. if (!this._worldMatrix) {
  5406. this._worldMatrix = BABYLON.Matrix.Identity();
  5407. }
  5408. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5409. return this._worldMatrix;
  5410. };
  5411. return SpotLight;
  5412. })(BABYLON.Light);
  5413. BABYLON.SpotLight = SpotLight;
  5414. })(BABYLON || (BABYLON = {}));
  5415. //# sourceMappingURL=babylon.spotLight.js.map
  5416. var BABYLON;
  5417. (function (BABYLON) {
  5418. var DirectionalLight = (function (_super) {
  5419. __extends(DirectionalLight, _super);
  5420. function DirectionalLight(name, direction, scene) {
  5421. _super.call(this, name, scene);
  5422. this.direction = direction;
  5423. this.position = direction.scale(-1);
  5424. }
  5425. DirectionalLight.prototype.getAbsolutePosition = function () {
  5426. return this.transformedPosition ? this.transformedPosition : this.position;
  5427. };
  5428. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5429. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5430. return this.direction;
  5431. };
  5432. DirectionalLight.prototype.computeTransformedPosition = function () {
  5433. if (this.parent && this.parent.getWorldMatrix) {
  5434. if (!this.transformedPosition) {
  5435. this.transformedPosition = BABYLON.Vector3.Zero();
  5436. }
  5437. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5438. return true;
  5439. }
  5440. return false;
  5441. };
  5442. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5443. if (this.parent && this.parent.getWorldMatrix) {
  5444. if (!this._transformedDirection) {
  5445. this._transformedDirection = BABYLON.Vector3.Zero();
  5446. }
  5447. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5448. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5449. return;
  5450. }
  5451. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5452. };
  5453. DirectionalLight.prototype._getWorldMatrix = function () {
  5454. if (!this._worldMatrix) {
  5455. this._worldMatrix = BABYLON.Matrix.Identity();
  5456. }
  5457. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5458. return this._worldMatrix;
  5459. };
  5460. return DirectionalLight;
  5461. })(BABYLON.Light);
  5462. BABYLON.DirectionalLight = DirectionalLight;
  5463. })(BABYLON || (BABYLON = {}));
  5464. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5465. (function (BABYLON) {
  5466. var ShadowGenerator = (function () {
  5467. function ShadowGenerator(mapSize, light) {
  5468. var _this = this;
  5469. // Members
  5470. this.filter = ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5471. this._darkness = 0;
  5472. this._transparencyShadow = false;
  5473. this._viewMatrix = BABYLON.Matrix.Zero();
  5474. this._projectionMatrix = BABYLON.Matrix.Zero();
  5475. this._transformMatrix = BABYLON.Matrix.Zero();
  5476. this._worldViewProjection = BABYLON.Matrix.Zero();
  5477. this._light = light;
  5478. this._scene = light.getScene();
  5479. light._shadowGenerator = this;
  5480. // Render target
  5481. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5482. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5483. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5484. this._shadowMap.renderParticles = false;
  5485. // Custom render function
  5486. var renderSubMesh = function (subMesh) {
  5487. var mesh = subMesh.getRenderingMesh();
  5488. var scene = _this._scene;
  5489. var engine = scene.getEngine();
  5490. // Culling
  5491. engine.setState(subMesh.getMaterial().backFaceCulling);
  5492. // Managing instances
  5493. var batch = mesh._getInstancesRenderList(subMesh._id);
  5494. if (batch.mustReturn) {
  5495. return;
  5496. }
  5497. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5498. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5499. engine.enableEffect(_this._effect);
  5500. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5501. var material = subMesh.getMaterial();
  5502. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5503. // Alpha test
  5504. if (material && material.needAlphaTesting()) {
  5505. var alphaTexture = material.getAlphaTestTexture();
  5506. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5507. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5508. }
  5509. // Bones
  5510. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  5511. if (useBones) {
  5512. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5513. }
  5514. if (hardwareInstancedRendering) {
  5515. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, _this._effect, engine);
  5516. }
  5517. else {
  5518. if (batch.renderSelf[subMesh._id]) {
  5519. _this._effect.setMatrix("world", mesh.getWorldMatrix());
  5520. // Draw
  5521. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5522. }
  5523. if (batch.visibleInstances[subMesh._id]) {
  5524. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  5525. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  5526. _this._effect.setMatrix("world", instance.getWorldMatrix());
  5527. // Draw
  5528. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  5529. }
  5530. }
  5531. }
  5532. }
  5533. else {
  5534. // Need to reset refresh rate of the shadowMap
  5535. _this._shadowMap.resetRefreshCounter();
  5536. }
  5537. };
  5538. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5539. var index;
  5540. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5541. renderSubMesh(opaqueSubMeshes.data[index]);
  5542. }
  5543. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5544. renderSubMesh(alphaTestSubMeshes.data[index]);
  5545. }
  5546. if (_this._transparencyShadow) {
  5547. for (index = 0; index < transparentSubMeshes.length; index++) {
  5548. renderSubMesh(transparentSubMeshes.data[index]);
  5549. }
  5550. }
  5551. };
  5552. }
  5553. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5554. // Static
  5555. get: function () {
  5556. return ShadowGenerator._FILTER_NONE;
  5557. },
  5558. enumerable: true,
  5559. configurable: true
  5560. });
  5561. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5562. get: function () {
  5563. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5564. },
  5565. enumerable: true,
  5566. configurable: true
  5567. });
  5568. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5569. get: function () {
  5570. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5571. },
  5572. enumerable: true,
  5573. configurable: true
  5574. });
  5575. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5576. get: function () {
  5577. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP;
  5578. },
  5579. set: function (value) {
  5580. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5581. },
  5582. enumerable: true,
  5583. configurable: true
  5584. });
  5585. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5586. get: function () {
  5587. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  5588. },
  5589. set: function (value) {
  5590. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5591. },
  5592. enumerable: true,
  5593. configurable: true
  5594. });
  5595. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5596. var defines = [];
  5597. if (this.useVarianceShadowMap) {
  5598. defines.push("#define VSM");
  5599. }
  5600. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5601. var mesh = subMesh.getMesh();
  5602. var scene = mesh.getScene();
  5603. var material = subMesh.getMaterial();
  5604. // Alpha test
  5605. if (material && material.needAlphaTesting()) {
  5606. defines.push("#define ALPHATEST");
  5607. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5608. attribs.push(BABYLON.VertexBuffer.UVKind);
  5609. defines.push("#define UV1");
  5610. }
  5611. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5612. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5613. defines.push("#define UV2");
  5614. }
  5615. }
  5616. // Bones
  5617. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  5618. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5619. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5620. defines.push("#define BONES");
  5621. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5622. }
  5623. // Instances
  5624. if (useInstances) {
  5625. defines.push("#define INSTANCES");
  5626. attribs.push("world0");
  5627. attribs.push("world1");
  5628. attribs.push("world2");
  5629. attribs.push("world3");
  5630. }
  5631. // Get correct effect
  5632. var join = defines.join("\n");
  5633. if (this._cachedDefines !== join) {
  5634. this._cachedDefines = join;
  5635. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5636. }
  5637. return this._effect.isReady();
  5638. };
  5639. ShadowGenerator.prototype.getShadowMap = function () {
  5640. return this._shadowMap;
  5641. };
  5642. ShadowGenerator.prototype.getLight = function () {
  5643. return this._light;
  5644. };
  5645. // Methods
  5646. ShadowGenerator.prototype.getTransformMatrix = function () {
  5647. var lightPosition = this._light.position;
  5648. var lightDirection = this._light.direction;
  5649. if (this._light.computeTransformedPosition()) {
  5650. lightPosition = this._light.transformedPosition;
  5651. }
  5652. if (!this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  5653. this._cachedPosition = lightPosition.clone();
  5654. this._cachedDirection = lightDirection.clone();
  5655. var activeCamera = this._scene.activeCamera;
  5656. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  5657. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2.0, 1.0, activeCamera.minZ, activeCamera.maxZ, this._projectionMatrix);
  5658. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  5659. }
  5660. return this._transformMatrix;
  5661. };
  5662. ShadowGenerator.prototype.getDarkness = function () {
  5663. return this._darkness;
  5664. };
  5665. ShadowGenerator.prototype.setDarkness = function (darkness) {
  5666. if (darkness >= 1.0)
  5667. this._darkness = 1.0;
  5668. else if (darkness <= 0.0)
  5669. this._darkness = 0.0;
  5670. else
  5671. this._darkness = darkness;
  5672. };
  5673. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  5674. this._transparencyShadow = hasShadow;
  5675. };
  5676. ShadowGenerator.prototype.dispose = function () {
  5677. this._shadowMap.dispose();
  5678. };
  5679. ShadowGenerator._FILTER_NONE = 0;
  5680. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  5681. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  5682. return ShadowGenerator;
  5683. })();
  5684. BABYLON.ShadowGenerator = ShadowGenerator;
  5685. })(BABYLON || (BABYLON = {}));
  5686. //# sourceMappingURL=babylon.shadowGenerator.js.map
  5687. var BABYLON;
  5688. (function (BABYLON) {
  5689. var HemisphericLight = (function (_super) {
  5690. __extends(HemisphericLight, _super);
  5691. function HemisphericLight(name, direction, scene) {
  5692. _super.call(this, name, scene);
  5693. this.direction = direction;
  5694. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  5695. }
  5696. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  5697. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  5698. return this.direction;
  5699. };
  5700. HemisphericLight.prototype.getShadowGenerator = function () {
  5701. return null;
  5702. };
  5703. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  5704. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5705. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  5706. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  5707. };
  5708. HemisphericLight.prototype._getWorldMatrix = function () {
  5709. if (!this._worldMatrix) {
  5710. this._worldMatrix = BABYLON.Matrix.Identity();
  5711. }
  5712. return this._worldMatrix;
  5713. };
  5714. return HemisphericLight;
  5715. })(BABYLON.Light);
  5716. BABYLON.HemisphericLight = HemisphericLight;
  5717. })(BABYLON || (BABYLON = {}));
  5718. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  5719. (function (BABYLON) {
  5720. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  5721. if (boxMin.x > sphereCenter.x + sphereRadius)
  5722. return false;
  5723. if (sphereCenter.x - sphereRadius > boxMax.x)
  5724. return false;
  5725. if (boxMin.y > sphereCenter.y + sphereRadius)
  5726. return false;
  5727. if (sphereCenter.y - sphereRadius > boxMax.y)
  5728. return false;
  5729. if (boxMin.z > sphereCenter.z + sphereRadius)
  5730. return false;
  5731. if (sphereCenter.z - sphereRadius > boxMax.z)
  5732. return false;
  5733. return true;
  5734. };
  5735. var getLowestRoot = function (a, b, c, maxR) {
  5736. var determinant = b * b - 4.0 * a * c;
  5737. var result = { root: 0, found: false };
  5738. if (determinant < 0)
  5739. return result;
  5740. var sqrtD = Math.sqrt(determinant);
  5741. var r1 = (-b - sqrtD) / (2.0 * a);
  5742. var r2 = (-b + sqrtD) / (2.0 * a);
  5743. if (r1 > r2) {
  5744. var temp = r2;
  5745. r2 = r1;
  5746. r1 = temp;
  5747. }
  5748. if (r1 > 0 && r1 < maxR) {
  5749. result.root = r1;
  5750. result.found = true;
  5751. return result;
  5752. }
  5753. if (r2 > 0 && r2 < maxR) {
  5754. result.root = r2;
  5755. result.found = true;
  5756. return result;
  5757. }
  5758. return result;
  5759. };
  5760. var Collider = (function () {
  5761. function Collider() {
  5762. this.radius = new BABYLON.Vector3(1, 1, 1);
  5763. this.retry = 0;
  5764. this.basePointWorld = BABYLON.Vector3.Zero();
  5765. this.velocityWorld = BABYLON.Vector3.Zero();
  5766. this.normalizedVelocity = BABYLON.Vector3.Zero();
  5767. this._collisionPoint = BABYLON.Vector3.Zero();
  5768. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  5769. this._tempVector = BABYLON.Vector3.Zero();
  5770. this._tempVector2 = BABYLON.Vector3.Zero();
  5771. this._tempVector3 = BABYLON.Vector3.Zero();
  5772. this._tempVector4 = BABYLON.Vector3.Zero();
  5773. this._edge = BABYLON.Vector3.Zero();
  5774. this._baseToVertex = BABYLON.Vector3.Zero();
  5775. this._destinationPoint = BABYLON.Vector3.Zero();
  5776. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  5777. this._displacementVector = BABYLON.Vector3.Zero();
  5778. }
  5779. // Methods
  5780. Collider.prototype._initialize = function (source, dir, e) {
  5781. this.velocity = dir;
  5782. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  5783. this.basePoint = source;
  5784. source.multiplyToRef(this.radius, this.basePointWorld);
  5785. dir.multiplyToRef(this.radius, this.velocityWorld);
  5786. this.velocityWorldLength = this.velocityWorld.length();
  5787. this.epsilon = e;
  5788. this.collisionFound = false;
  5789. };
  5790. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  5791. pa.subtractToRef(point, this._tempVector);
  5792. pb.subtractToRef(point, this._tempVector2);
  5793. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  5794. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5795. if (d < 0)
  5796. return false;
  5797. pc.subtractToRef(point, this._tempVector3);
  5798. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  5799. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5800. if (d < 0)
  5801. return false;
  5802. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  5803. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  5804. return d >= 0;
  5805. };
  5806. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  5807. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  5808. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  5809. if (distance > this.velocityWorldLength + max + sphereRadius) {
  5810. return false;
  5811. }
  5812. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  5813. return false;
  5814. return true;
  5815. };
  5816. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  5817. var t0;
  5818. var embeddedInPlane = false;
  5819. if (!subMesh._trianglePlanes) {
  5820. subMesh._trianglePlanes = [];
  5821. }
  5822. if (!subMesh._trianglePlanes[faceIndex]) {
  5823. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  5824. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  5825. }
  5826. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  5827. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  5828. return;
  5829. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  5830. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  5831. if (normalDotVelocity == 0) {
  5832. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  5833. return;
  5834. embeddedInPlane = true;
  5835. t0 = 0;
  5836. }
  5837. else {
  5838. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5839. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  5840. if (t0 > t1) {
  5841. var temp = t1;
  5842. t1 = t0;
  5843. t0 = temp;
  5844. }
  5845. if (t0 > 1.0 || t1 < 0.0)
  5846. return;
  5847. if (t0 < 0)
  5848. t0 = 0;
  5849. if (t0 > 1.0)
  5850. t0 = 1.0;
  5851. }
  5852. this._collisionPoint.copyFromFloats(0, 0, 0);
  5853. var found = false;
  5854. var t = 1.0;
  5855. if (!embeddedInPlane) {
  5856. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  5857. this.velocity.scaleToRef(t0, this._tempVector);
  5858. this._planeIntersectionPoint.addInPlace(this._tempVector);
  5859. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  5860. found = true;
  5861. t = t0;
  5862. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  5863. }
  5864. }
  5865. if (!found) {
  5866. var velocitySquaredLength = this.velocity.lengthSquared();
  5867. var a = velocitySquaredLength;
  5868. this.basePoint.subtractToRef(p1, this._tempVector);
  5869. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5870. var c = this._tempVector.lengthSquared() - 1.0;
  5871. var lowestRoot = getLowestRoot(a, b, c, t);
  5872. if (lowestRoot.found) {
  5873. t = lowestRoot.root;
  5874. found = true;
  5875. this._collisionPoint.copyFrom(p1);
  5876. }
  5877. this.basePoint.subtractToRef(p2, this._tempVector);
  5878. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5879. c = this._tempVector.lengthSquared() - 1.0;
  5880. lowestRoot = getLowestRoot(a, b, c, t);
  5881. if (lowestRoot.found) {
  5882. t = lowestRoot.root;
  5883. found = true;
  5884. this._collisionPoint.copyFrom(p2);
  5885. }
  5886. this.basePoint.subtractToRef(p3, this._tempVector);
  5887. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  5888. c = this._tempVector.lengthSquared() - 1.0;
  5889. lowestRoot = getLowestRoot(a, b, c, t);
  5890. if (lowestRoot.found) {
  5891. t = lowestRoot.root;
  5892. found = true;
  5893. this._collisionPoint.copyFrom(p3);
  5894. }
  5895. p2.subtractToRef(p1, this._edge);
  5896. p1.subtractToRef(this.basePoint, this._baseToVertex);
  5897. var edgeSquaredLength = this._edge.lengthSquared();
  5898. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5899. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5900. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5901. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5902. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5903. lowestRoot = getLowestRoot(a, b, c, t);
  5904. if (lowestRoot.found) {
  5905. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5906. if (f >= 0.0 && f <= 1.0) {
  5907. t = lowestRoot.root;
  5908. found = true;
  5909. this._edge.scaleInPlace(f);
  5910. p1.addToRef(this._edge, this._collisionPoint);
  5911. }
  5912. }
  5913. p3.subtractToRef(p2, this._edge);
  5914. p2.subtractToRef(this.basePoint, this._baseToVertex);
  5915. edgeSquaredLength = this._edge.lengthSquared();
  5916. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5917. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5918. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5919. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5920. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5921. lowestRoot = getLowestRoot(a, b, c, t);
  5922. if (lowestRoot.found) {
  5923. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5924. if (f >= 0.0 && f <= 1.0) {
  5925. t = lowestRoot.root;
  5926. found = true;
  5927. this._edge.scaleInPlace(f);
  5928. p2.addToRef(this._edge, this._collisionPoint);
  5929. }
  5930. }
  5931. p1.subtractToRef(p3, this._edge);
  5932. p3.subtractToRef(this.basePoint, this._baseToVertex);
  5933. edgeSquaredLength = this._edge.lengthSquared();
  5934. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  5935. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  5936. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  5937. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  5938. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  5939. lowestRoot = getLowestRoot(a, b, c, t);
  5940. if (lowestRoot.found) {
  5941. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  5942. if (f >= 0.0 && f <= 1.0) {
  5943. t = lowestRoot.root;
  5944. found = true;
  5945. this._edge.scaleInPlace(f);
  5946. p3.addToRef(this._edge, this._collisionPoint);
  5947. }
  5948. }
  5949. }
  5950. if (found) {
  5951. var distToCollision = t * this.velocity.length();
  5952. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  5953. if (!this.intersectionPoint) {
  5954. this.intersectionPoint = this._collisionPoint.clone();
  5955. }
  5956. else {
  5957. this.intersectionPoint.copyFrom(this._collisionPoint);
  5958. }
  5959. this.nearestDistance = distToCollision;
  5960. this.collisionFound = true;
  5961. this.collidedMesh = subMesh.getMesh();
  5962. }
  5963. }
  5964. };
  5965. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  5966. for (var i = indexStart; i < indexEnd; i += 3) {
  5967. var p1 = pts[indices[i] - decal];
  5968. var p2 = pts[indices[i + 1] - decal];
  5969. var p3 = pts[indices[i + 2] - decal];
  5970. this._testTriangle(i, subMesh, p3, p2, p1);
  5971. }
  5972. };
  5973. Collider.prototype._getResponse = function (pos, vel) {
  5974. pos.addToRef(vel, this._destinationPoint);
  5975. vel.scaleInPlace((this.nearestDistance / vel.length()));
  5976. this.basePoint.addToRef(vel, pos);
  5977. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  5978. this._slidePlaneNormal.normalize();
  5979. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  5980. pos.addInPlace(this._displacementVector);
  5981. this.intersectionPoint.addInPlace(this._displacementVector);
  5982. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  5983. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  5984. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  5985. };
  5986. return Collider;
  5987. })();
  5988. BABYLON.Collider = Collider;
  5989. })(BABYLON || (BABYLON = {}));
  5990. //# sourceMappingURL=babylon.collider.js.map
  5991. var BABYLON;
  5992. (function (BABYLON) {
  5993. var Camera = (function (_super) {
  5994. __extends(Camera, _super);
  5995. function Camera(name, position, scene) {
  5996. _super.call(this, name, scene);
  5997. this.position = position;
  5998. // Members
  5999. this.upVector = BABYLON.Vector3.Up();
  6000. this.orthoLeft = null;
  6001. this.orthoRight = null;
  6002. this.orthoBottom = null;
  6003. this.orthoTop = null;
  6004. this.fov = 0.8;
  6005. this.minZ = 1.0;
  6006. this.maxZ = 10000.0;
  6007. this.inertia = 0.9;
  6008. this.mode = Camera.PERSPECTIVE_CAMERA;
  6009. this.isIntermediate = false;
  6010. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6011. this.subCameras = [];
  6012. this.layerMask = 0xFFFFFFFF;
  6013. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6014. this._projectionMatrix = new BABYLON.Matrix();
  6015. this._postProcesses = new Array();
  6016. this._postProcessesTakenIndices = [];
  6017. scene.cameras.push(this);
  6018. if (!scene.activeCamera) {
  6019. scene.activeCamera = this;
  6020. }
  6021. }
  6022. //Cache
  6023. Camera.prototype._initCache = function () {
  6024. _super.prototype._initCache.call(this);
  6025. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6026. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6027. this._cache.mode = undefined;
  6028. this._cache.minZ = undefined;
  6029. this._cache.maxZ = undefined;
  6030. this._cache.fov = undefined;
  6031. this._cache.aspectRatio = undefined;
  6032. this._cache.orthoLeft = undefined;
  6033. this._cache.orthoRight = undefined;
  6034. this._cache.orthoBottom = undefined;
  6035. this._cache.orthoTop = undefined;
  6036. this._cache.renderWidth = undefined;
  6037. this._cache.renderHeight = undefined;
  6038. };
  6039. Camera.prototype._updateCache = function (ignoreParentClass) {
  6040. if (!ignoreParentClass) {
  6041. _super.prototype._updateCache.call(this);
  6042. }
  6043. var engine = this.getEngine();
  6044. this._cache.position.copyFrom(this.position);
  6045. this._cache.upVector.copyFrom(this.upVector);
  6046. this._cache.mode = this.mode;
  6047. this._cache.minZ = this.minZ;
  6048. this._cache.maxZ = this.maxZ;
  6049. this._cache.fov = this.fov;
  6050. this._cache.aspectRatio = engine.getAspectRatio(this);
  6051. this._cache.orthoLeft = this.orthoLeft;
  6052. this._cache.orthoRight = this.orthoRight;
  6053. this._cache.orthoBottom = this.orthoBottom;
  6054. this._cache.orthoTop = this.orthoTop;
  6055. this._cache.renderWidth = engine.getRenderWidth();
  6056. this._cache.renderHeight = engine.getRenderHeight();
  6057. };
  6058. Camera.prototype._updateFromScene = function () {
  6059. this.updateCache();
  6060. this._update();
  6061. };
  6062. // Synchronized
  6063. Camera.prototype._isSynchronized = function () {
  6064. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6065. };
  6066. Camera.prototype._isSynchronizedViewMatrix = function () {
  6067. if (!_super.prototype._isSynchronized.call(this))
  6068. return false;
  6069. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6070. };
  6071. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6072. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6073. if (!check) {
  6074. return false;
  6075. }
  6076. var engine = this.getEngine();
  6077. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6078. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6079. }
  6080. else {
  6081. 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();
  6082. }
  6083. return check;
  6084. };
  6085. // Controls
  6086. Camera.prototype.attachControl = function (element) {
  6087. };
  6088. Camera.prototype.detachControl = function (element) {
  6089. };
  6090. Camera.prototype._update = function () {
  6091. };
  6092. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6093. if (insertAt === void 0) { insertAt = null; }
  6094. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6095. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6096. return 0;
  6097. }
  6098. if (insertAt == null || insertAt < 0) {
  6099. this._postProcesses.push(postProcess);
  6100. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6101. return this._postProcesses.length - 1;
  6102. }
  6103. var add = 0;
  6104. if (this._postProcesses[insertAt]) {
  6105. var start = this._postProcesses.length - 1;
  6106. for (var i = start; i >= insertAt + 1; --i) {
  6107. this._postProcesses[i + 1] = this._postProcesses[i];
  6108. }
  6109. add = 1;
  6110. }
  6111. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6112. if (this._postProcessesTakenIndices[i] < insertAt) {
  6113. continue;
  6114. }
  6115. start = this._postProcessesTakenIndices.length - 1;
  6116. for (var j = start; j >= i; --j) {
  6117. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6118. }
  6119. this._postProcessesTakenIndices[i] = insertAt;
  6120. break;
  6121. }
  6122. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6123. this._postProcessesTakenIndices.push(insertAt);
  6124. }
  6125. var result = insertAt + add;
  6126. this._postProcesses[result] = postProcess;
  6127. return result;
  6128. };
  6129. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6130. if (atIndices === void 0) { atIndices = null; }
  6131. var result = [];
  6132. if (!atIndices) {
  6133. var length = this._postProcesses.length;
  6134. for (var i = 0; i < length; i++) {
  6135. if (this._postProcesses[i] !== postProcess) {
  6136. continue;
  6137. }
  6138. delete this._postProcesses[i];
  6139. var index = this._postProcessesTakenIndices.indexOf(i);
  6140. this._postProcessesTakenIndices.splice(index, 1);
  6141. }
  6142. }
  6143. else {
  6144. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6145. for (i = 0; i < atIndices.length; i++) {
  6146. var foundPostProcess = this._postProcesses[atIndices[i]];
  6147. if (foundPostProcess !== postProcess) {
  6148. result.push(i);
  6149. continue;
  6150. }
  6151. delete this._postProcesses[atIndices[i]];
  6152. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6153. this._postProcessesTakenIndices.splice(index, 1);
  6154. }
  6155. }
  6156. return result;
  6157. };
  6158. Camera.prototype.getWorldMatrix = function () {
  6159. if (!this._worldMatrix) {
  6160. this._worldMatrix = BABYLON.Matrix.Identity();
  6161. }
  6162. var viewMatrix = this.getViewMatrix();
  6163. viewMatrix.invertToRef(this._worldMatrix);
  6164. return this._worldMatrix;
  6165. };
  6166. Camera.prototype._getViewMatrix = function () {
  6167. return BABYLON.Matrix.Identity();
  6168. };
  6169. Camera.prototype.getViewMatrix = function () {
  6170. this._computedViewMatrix = this._computeViewMatrix();
  6171. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6172. return this._computedViewMatrix;
  6173. }
  6174. if (!this._worldMatrix) {
  6175. this._worldMatrix = BABYLON.Matrix.Identity();
  6176. }
  6177. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6178. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6179. this._computedViewMatrix.invert();
  6180. this._currentRenderId = this.getScene().getRenderId();
  6181. return this._computedViewMatrix;
  6182. };
  6183. Camera.prototype._computeViewMatrix = function (force) {
  6184. if (!force && this._isSynchronizedViewMatrix()) {
  6185. return this._computedViewMatrix;
  6186. }
  6187. this._computedViewMatrix = this._getViewMatrix();
  6188. if (!this.parent || !this.parent.getWorldMatrix) {
  6189. this._currentRenderId = this.getScene().getRenderId();
  6190. }
  6191. return this._computedViewMatrix;
  6192. };
  6193. Camera.prototype.getProjectionMatrix = function (force) {
  6194. if (!force && this._isSynchronizedProjectionMatrix()) {
  6195. return this._projectionMatrix;
  6196. }
  6197. var engine = this.getEngine();
  6198. if (this.mode === BABYLON.Camera.PERSPECTIVE_CAMERA) {
  6199. if (this.minZ <= 0) {
  6200. this.minZ = 0.1;
  6201. }
  6202. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix);
  6203. return this._projectionMatrix;
  6204. }
  6205. var halfWidth = engine.getRenderWidth() / 2.0;
  6206. var halfHeight = engine.getRenderHeight() / 2.0;
  6207. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6208. return this._projectionMatrix;
  6209. };
  6210. Camera.prototype.dispose = function () {
  6211. // Remove from scene
  6212. var index = this.getScene().cameras.indexOf(this);
  6213. this.getScene().cameras.splice(index, 1);
  6214. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6215. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6216. }
  6217. };
  6218. // Statics
  6219. Camera.PERSPECTIVE_CAMERA = 0;
  6220. Camera.ORTHOGRAPHIC_CAMERA = 1;
  6221. return Camera;
  6222. })(BABYLON.Node);
  6223. BABYLON.Camera = Camera;
  6224. })(BABYLON || (BABYLON = {}));
  6225. //# sourceMappingURL=babylon.camera.js.map
  6226. var BABYLON;
  6227. (function (BABYLON) {
  6228. var TargetCamera = (function (_super) {
  6229. __extends(TargetCamera, _super);
  6230. function TargetCamera(name, position, scene) {
  6231. _super.call(this, name, position, scene);
  6232. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6233. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6234. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6235. this.speed = 2.0;
  6236. this.noRotationConstraint = false;
  6237. this.lockedTarget = null;
  6238. this._currentTarget = BABYLON.Vector3.Zero();
  6239. this._viewMatrix = BABYLON.Matrix.Zero();
  6240. this._camMatrix = BABYLON.Matrix.Zero();
  6241. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6242. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6243. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6244. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6245. this._lookAtTemp = BABYLON.Matrix.Zero();
  6246. this._tempMatrix = BABYLON.Matrix.Zero();
  6247. }
  6248. TargetCamera.prototype._getLockedTargetPosition = function () {
  6249. if (!this.lockedTarget) {
  6250. return null;
  6251. }
  6252. return this.lockedTarget.position || this.lockedTarget;
  6253. };
  6254. // Cache
  6255. TargetCamera.prototype._initCache = function () {
  6256. _super.prototype._initCache.call(this);
  6257. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6258. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6259. };
  6260. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6261. if (!ignoreParentClass) {
  6262. _super.prototype._updateCache.call(this);
  6263. }
  6264. var lockedTargetPosition = this._getLockedTargetPosition();
  6265. if (!lockedTargetPosition) {
  6266. this._cache.lockedTarget = null;
  6267. }
  6268. else {
  6269. if (!this._cache.lockedTarget) {
  6270. this._cache.lockedTarget = lockedTargetPosition.clone();
  6271. }
  6272. else {
  6273. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6274. }
  6275. }
  6276. this._cache.rotation.copyFrom(this.rotation);
  6277. };
  6278. // Synchronized
  6279. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6280. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6281. return false;
  6282. }
  6283. var lockedTargetPosition = this._getLockedTargetPosition();
  6284. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6285. };
  6286. // Methods
  6287. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6288. var engine = this.getEngine();
  6289. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6290. };
  6291. // Target
  6292. TargetCamera.prototype.setTarget = function (target) {
  6293. this.upVector.normalize();
  6294. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6295. this._camMatrix.invert();
  6296. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6297. var vDir = target.subtract(this.position);
  6298. if (vDir.x >= 0.0) {
  6299. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6300. }
  6301. else {
  6302. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6303. }
  6304. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6305. if (isNaN(this.rotation.x)) {
  6306. this.rotation.x = 0;
  6307. }
  6308. if (isNaN(this.rotation.y)) {
  6309. this.rotation.y = 0;
  6310. }
  6311. if (isNaN(this.rotation.z)) {
  6312. this.rotation.z = 0;
  6313. }
  6314. };
  6315. TargetCamera.prototype.getTarget = function () {
  6316. return this._currentTarget;
  6317. };
  6318. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6319. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6320. };
  6321. TargetCamera.prototype._updatePosition = function () {
  6322. this.position.addInPlace(this.cameraDirection);
  6323. };
  6324. TargetCamera.prototype._update = function () {
  6325. var needToMove = this._decideIfNeedsToMove();
  6326. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6327. // Move
  6328. if (needToMove) {
  6329. this._updatePosition();
  6330. }
  6331. // Rotate
  6332. if (needToRotate) {
  6333. this.rotation.x += this.cameraRotation.x;
  6334. this.rotation.y += this.cameraRotation.y;
  6335. if (!this.noRotationConstraint) {
  6336. var limit = (Math.PI / 2) * 0.95;
  6337. if (this.rotation.x > limit)
  6338. this.rotation.x = limit;
  6339. if (this.rotation.x < -limit)
  6340. this.rotation.x = -limit;
  6341. }
  6342. }
  6343. // Inertia
  6344. if (needToMove) {
  6345. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6346. this.cameraDirection.x = 0;
  6347. }
  6348. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6349. this.cameraDirection.y = 0;
  6350. }
  6351. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6352. this.cameraDirection.z = 0;
  6353. }
  6354. this.cameraDirection.scaleInPlace(this.inertia);
  6355. }
  6356. if (needToRotate) {
  6357. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6358. this.cameraRotation.x = 0;
  6359. }
  6360. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6361. this.cameraRotation.y = 0;
  6362. }
  6363. this.cameraRotation.scaleInPlace(this.inertia);
  6364. }
  6365. };
  6366. TargetCamera.prototype._getViewMatrix = function () {
  6367. if (!this.lockedTarget) {
  6368. // Compute
  6369. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6370. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6371. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6372. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6373. this._lookAtTemp.invert();
  6374. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6375. }
  6376. else {
  6377. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6378. }
  6379. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6380. // Computing target and final matrix
  6381. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6382. }
  6383. else {
  6384. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6385. }
  6386. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6387. return this._viewMatrix;
  6388. };
  6389. return TargetCamera;
  6390. })(BABYLON.Camera);
  6391. BABYLON.TargetCamera = TargetCamera;
  6392. })(BABYLON || (BABYLON = {}));
  6393. //# sourceMappingURL=babylon.targetCamera.js.map
  6394. var BABYLON;
  6395. (function (BABYLON) {
  6396. var FollowCamera = (function (_super) {
  6397. __extends(FollowCamera, _super);
  6398. function FollowCamera(name, position, scene) {
  6399. _super.call(this, name, position, scene);
  6400. this.radius = 12;
  6401. this.rotationOffset = 0;
  6402. this.heightOffset = 4;
  6403. this.cameraAcceleration = 0.05;
  6404. this.maxCameraSpeed = 20;
  6405. }
  6406. FollowCamera.prototype.getRadians = function (degrees) {
  6407. return degrees * Math.PI / 180;
  6408. };
  6409. FollowCamera.prototype.follow = function (cameraTarget) {
  6410. if (!cameraTarget)
  6411. return;
  6412. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6413. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6414. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6415. var dx = targetX - this.position.x;
  6416. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6417. var dz = (targetZ) - this.position.z;
  6418. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6419. var vy = dy * this.cameraAcceleration;
  6420. var vz = dz * this.cameraAcceleration * 2;
  6421. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6422. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6423. }
  6424. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6425. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6426. }
  6427. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6428. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6429. }
  6430. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6431. this.setTarget(cameraTarget.position);
  6432. };
  6433. FollowCamera.prototype._update = function () {
  6434. _super.prototype._update.call(this);
  6435. this.follow(this.target);
  6436. };
  6437. return FollowCamera;
  6438. })(BABYLON.TargetCamera);
  6439. BABYLON.FollowCamera = FollowCamera;
  6440. })(BABYLON || (BABYLON = {}));
  6441. //# sourceMappingURL=babylon.followCamera.js.map
  6442. var BABYLON;
  6443. (function (BABYLON) {
  6444. var FreeCamera = (function (_super) {
  6445. __extends(FreeCamera, _super);
  6446. function FreeCamera(name, position, scene) {
  6447. _super.call(this, name, position, scene);
  6448. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6449. this.keysUp = [38];
  6450. this.keysDown = [40];
  6451. this.keysLeft = [37];
  6452. this.keysRight = [39];
  6453. this.checkCollisions = false;
  6454. this.applyGravity = false;
  6455. this.angularSensibility = 2000.0;
  6456. this._keys = [];
  6457. this._collider = new BABYLON.Collider();
  6458. this._needMoveForGravity = true;
  6459. this._oldPosition = BABYLON.Vector3.Zero();
  6460. this._diffPosition = BABYLON.Vector3.Zero();
  6461. this._newPosition = BABYLON.Vector3.Zero();
  6462. }
  6463. // Controls
  6464. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6465. var _this = this;
  6466. var previousPosition;
  6467. var engine = this.getEngine();
  6468. if (this._attachedElement) {
  6469. return;
  6470. }
  6471. this._attachedElement = element;
  6472. if (this._onMouseDown === undefined) {
  6473. this._onMouseDown = function (evt) {
  6474. previousPosition = {
  6475. x: evt.clientX,
  6476. y: evt.clientY
  6477. };
  6478. if (!noPreventDefault) {
  6479. evt.preventDefault();
  6480. }
  6481. };
  6482. this._onMouseUp = function (evt) {
  6483. previousPosition = null;
  6484. if (!noPreventDefault) {
  6485. evt.preventDefault();
  6486. }
  6487. };
  6488. this._onMouseOut = function (evt) {
  6489. previousPosition = null;
  6490. _this._keys = [];
  6491. if (!noPreventDefault) {
  6492. evt.preventDefault();
  6493. }
  6494. };
  6495. this._onMouseMove = function (evt) {
  6496. if (!previousPosition && !engine.isPointerLock) {
  6497. return;
  6498. }
  6499. var offsetX;
  6500. var offsetY;
  6501. if (!engine.isPointerLock) {
  6502. offsetX = evt.clientX - previousPosition.x;
  6503. offsetY = evt.clientY - previousPosition.y;
  6504. }
  6505. else {
  6506. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6507. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6508. }
  6509. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6510. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6511. previousPosition = {
  6512. x: evt.clientX,
  6513. y: evt.clientY
  6514. };
  6515. if (!noPreventDefault) {
  6516. evt.preventDefault();
  6517. }
  6518. };
  6519. this._onKeyDown = function (evt) {
  6520. 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) {
  6521. var index = _this._keys.indexOf(evt.keyCode);
  6522. if (index === -1) {
  6523. _this._keys.push(evt.keyCode);
  6524. }
  6525. if (!noPreventDefault) {
  6526. evt.preventDefault();
  6527. }
  6528. }
  6529. };
  6530. this._onKeyUp = function (evt) {
  6531. 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) {
  6532. var index = _this._keys.indexOf(evt.keyCode);
  6533. if (index >= 0) {
  6534. _this._keys.splice(index, 1);
  6535. }
  6536. if (!noPreventDefault) {
  6537. evt.preventDefault();
  6538. }
  6539. }
  6540. };
  6541. this._onLostFocus = function () {
  6542. _this._keys = [];
  6543. };
  6544. this._reset = function () {
  6545. _this._keys = [];
  6546. previousPosition = null;
  6547. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6548. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6549. };
  6550. }
  6551. element.addEventListener("mousedown", this._onMouseDown, false);
  6552. element.addEventListener("mouseup", this._onMouseUp, false);
  6553. element.addEventListener("mouseout", this._onMouseOut, false);
  6554. element.addEventListener("mousemove", this._onMouseMove, false);
  6555. BABYLON.Tools.RegisterTopRootEvents([
  6556. { name: "keydown", handler: this._onKeyDown },
  6557. { name: "keyup", handler: this._onKeyUp },
  6558. { name: "blur", handler: this._onLostFocus }
  6559. ]);
  6560. };
  6561. FreeCamera.prototype.detachControl = function (element) {
  6562. if (this._attachedElement != element) {
  6563. return;
  6564. }
  6565. element.removeEventListener("mousedown", this._onMouseDown);
  6566. element.removeEventListener("mouseup", this._onMouseUp);
  6567. element.removeEventListener("mouseout", this._onMouseOut);
  6568. element.removeEventListener("mousemove", this._onMouseMove);
  6569. BABYLON.Tools.UnregisterTopRootEvents([
  6570. { name: "keydown", handler: this._onKeyDown },
  6571. { name: "keyup", handler: this._onKeyUp },
  6572. { name: "blur", handler: this._onLostFocus }
  6573. ]);
  6574. this._attachedElement = null;
  6575. if (this._reset) {
  6576. this._reset();
  6577. }
  6578. };
  6579. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6580. var globalPosition;
  6581. if (this.parent) {
  6582. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6583. }
  6584. else {
  6585. globalPosition = this.position;
  6586. }
  6587. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6588. this._collider.radius = this.ellipsoid;
  6589. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  6590. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  6591. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  6592. this.position.addInPlace(this._diffPosition);
  6593. if (this.onCollide) {
  6594. this.onCollide(this._collider.collidedMesh);
  6595. }
  6596. }
  6597. };
  6598. FreeCamera.prototype._checkInputs = function () {
  6599. if (!this._localDirection) {
  6600. this._localDirection = BABYLON.Vector3.Zero();
  6601. this._transformedDirection = BABYLON.Vector3.Zero();
  6602. }
  6603. for (var index = 0; index < this._keys.length; index++) {
  6604. var keyCode = this._keys[index];
  6605. var speed = this._computeLocalCameraSpeed();
  6606. if (this.keysLeft.indexOf(keyCode) !== -1) {
  6607. this._localDirection.copyFromFloats(-speed, 0, 0);
  6608. }
  6609. else if (this.keysUp.indexOf(keyCode) !== -1) {
  6610. this._localDirection.copyFromFloats(0, 0, speed);
  6611. }
  6612. else if (this.keysRight.indexOf(keyCode) !== -1) {
  6613. this._localDirection.copyFromFloats(speed, 0, 0);
  6614. }
  6615. else if (this.keysDown.indexOf(keyCode) !== -1) {
  6616. this._localDirection.copyFromFloats(0, 0, -speed);
  6617. }
  6618. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  6619. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  6620. this.cameraDirection.addInPlace(this._transformedDirection);
  6621. }
  6622. };
  6623. FreeCamera.prototype._decideIfNeedsToMove = function () {
  6624. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6625. };
  6626. FreeCamera.prototype._updatePosition = function () {
  6627. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  6628. this._collideWithWorld(this.cameraDirection);
  6629. if (this.applyGravity) {
  6630. var oldPosition = this.position;
  6631. this._collideWithWorld(this.getScene().gravity);
  6632. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  6633. }
  6634. }
  6635. else {
  6636. this.position.addInPlace(this.cameraDirection);
  6637. }
  6638. };
  6639. FreeCamera.prototype._update = function () {
  6640. this._checkInputs();
  6641. _super.prototype._update.call(this);
  6642. };
  6643. return FreeCamera;
  6644. })(BABYLON.TargetCamera);
  6645. BABYLON.FreeCamera = FreeCamera;
  6646. })(BABYLON || (BABYLON = {}));
  6647. //# sourceMappingURL=babylon.freeCamera.js.map
  6648. var BABYLON;
  6649. (function (BABYLON) {
  6650. // We're mainly based on the logic defined into the FreeCamera code
  6651. var TouchCamera = (function (_super) {
  6652. __extends(TouchCamera, _super);
  6653. function TouchCamera(name, position, scene) {
  6654. _super.call(this, name, position, scene);
  6655. this._offsetX = null;
  6656. this._offsetY = null;
  6657. this._pointerCount = 0;
  6658. this._pointerPressed = [];
  6659. this.angularSensibility = 200000.0;
  6660. this.moveSensibility = 500.0;
  6661. }
  6662. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6663. var _this = this;
  6664. var previousPosition;
  6665. if (this._attachedCanvas) {
  6666. return;
  6667. }
  6668. this._attachedCanvas = canvas;
  6669. if (this._onPointerDown === undefined) {
  6670. this._onPointerDown = function (evt) {
  6671. if (!noPreventDefault) {
  6672. evt.preventDefault();
  6673. }
  6674. _this._pointerPressed.push(evt.pointerId);
  6675. if (_this._pointerPressed.length !== 1) {
  6676. return;
  6677. }
  6678. previousPosition = {
  6679. x: evt.clientX,
  6680. y: evt.clientY
  6681. };
  6682. };
  6683. this._onPointerUp = function (evt) {
  6684. if (!noPreventDefault) {
  6685. evt.preventDefault();
  6686. }
  6687. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6688. if (index === -1) {
  6689. return;
  6690. }
  6691. _this._pointerPressed.splice(index, 1);
  6692. if (index != 0) {
  6693. return;
  6694. }
  6695. previousPosition = null;
  6696. _this._offsetX = null;
  6697. _this._offsetY = null;
  6698. };
  6699. this._onPointerMove = function (evt) {
  6700. if (!noPreventDefault) {
  6701. evt.preventDefault();
  6702. }
  6703. if (!previousPosition) {
  6704. return;
  6705. }
  6706. var index = _this._pointerPressed.indexOf(evt.pointerId);
  6707. if (index != 0) {
  6708. return;
  6709. }
  6710. _this._offsetX = evt.clientX - previousPosition.x;
  6711. _this._offsetY = -(evt.clientY - previousPosition.y);
  6712. };
  6713. this._onLostFocus = function () {
  6714. _this._offsetX = null;
  6715. _this._offsetY = null;
  6716. };
  6717. }
  6718. canvas.addEventListener("pointerdown", this._onPointerDown);
  6719. canvas.addEventListener("pointerup", this._onPointerUp);
  6720. canvas.addEventListener("pointerout", this._onPointerUp);
  6721. canvas.addEventListener("pointermove", this._onPointerMove);
  6722. BABYLON.Tools.RegisterTopRootEvents([
  6723. { name: "blur", handler: this._onLostFocus }
  6724. ]);
  6725. };
  6726. TouchCamera.prototype.detachControl = function (canvas) {
  6727. if (this._attachedCanvas != canvas) {
  6728. return;
  6729. }
  6730. canvas.removeEventListener("pointerdown", this._onPointerDown);
  6731. canvas.removeEventListener("pointerup", this._onPointerUp);
  6732. canvas.removeEventListener("pointerout", this._onPointerUp);
  6733. canvas.removeEventListener("pointermove", this._onPointerMove);
  6734. BABYLON.Tools.UnregisterTopRootEvents([
  6735. { name: "blur", handler: this._onLostFocus }
  6736. ]);
  6737. this._attachedCanvas = null;
  6738. };
  6739. TouchCamera.prototype._checkInputs = function () {
  6740. if (!this._offsetX) {
  6741. return;
  6742. }
  6743. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  6744. if (this._pointerPressed.length > 1) {
  6745. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  6746. }
  6747. else {
  6748. var speed = this._computeLocalCameraSpeed();
  6749. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6750. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6751. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6752. }
  6753. };
  6754. return TouchCamera;
  6755. })(BABYLON.FreeCamera);
  6756. BABYLON.TouchCamera = TouchCamera;
  6757. })(BABYLON || (BABYLON = {}));
  6758. //# sourceMappingURL=babylon.touchCamera.js.map
  6759. var BABYLON;
  6760. (function (BABYLON) {
  6761. // We're mainly based on the logic defined into the FreeCamera code
  6762. var DeviceOrientationCamera = (function (_super) {
  6763. __extends(DeviceOrientationCamera, _super);
  6764. function DeviceOrientationCamera(name, position, scene) {
  6765. var _this = this;
  6766. _super.call(this, name, position, scene);
  6767. this._offsetX = null;
  6768. this._offsetY = null;
  6769. this._orientationGamma = 0;
  6770. this._orientationBeta = 0;
  6771. this._initialOrientationGamma = 0;
  6772. this._initialOrientationBeta = 0;
  6773. this.angularSensibility = 10000.0;
  6774. this.moveSensibility = 50.0;
  6775. window.addEventListener("resize", function () {
  6776. _this._initialOrientationGamma = null;
  6777. }, false);
  6778. }
  6779. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  6780. var _this = this;
  6781. if (this._attachedCanvas) {
  6782. return;
  6783. }
  6784. this._attachedCanvas = canvas;
  6785. if (!this._orientationChanged) {
  6786. this._orientationChanged = function (evt) {
  6787. if (!_this._initialOrientationGamma) {
  6788. _this._initialOrientationGamma = evt.gamma;
  6789. _this._initialOrientationBeta = evt.beta;
  6790. }
  6791. _this._orientationGamma = evt.gamma;
  6792. _this._orientationBeta = evt.beta;
  6793. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  6794. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  6795. };
  6796. }
  6797. window.addEventListener("deviceorientation", this._orientationChanged);
  6798. };
  6799. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  6800. if (this._attachedCanvas != canvas) {
  6801. return;
  6802. }
  6803. window.removeEventListener("deviceorientation", this._orientationChanged);
  6804. this._attachedCanvas = null;
  6805. this._orientationGamma = 0;
  6806. this._orientationBeta = 0;
  6807. this._initialOrientationGamma = 0;
  6808. this._initialOrientationBeta = 0;
  6809. };
  6810. DeviceOrientationCamera.prototype._checkInputs = function () {
  6811. if (!this._offsetX) {
  6812. return;
  6813. }
  6814. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  6815. var speed = this._computeLocalCameraSpeed();
  6816. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  6817. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  6818. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  6819. };
  6820. return DeviceOrientationCamera;
  6821. })(BABYLON.FreeCamera);
  6822. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  6823. })(BABYLON || (BABYLON = {}));
  6824. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  6825. var BABYLON;
  6826. (function (BABYLON) {
  6827. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  6828. var ArcRotateCamera = (function (_super) {
  6829. __extends(ArcRotateCamera, _super);
  6830. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  6831. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  6832. this.alpha = alpha;
  6833. this.beta = beta;
  6834. this.radius = radius;
  6835. this.target = target;
  6836. this.inertialAlphaOffset = 0;
  6837. this.inertialBetaOffset = 0;
  6838. this.inertialRadiusOffset = 0;
  6839. this.lowerAlphaLimit = null;
  6840. this.upperAlphaLimit = null;
  6841. this.lowerBetaLimit = 0.01;
  6842. this.upperBetaLimit = Math.PI;
  6843. this.lowerRadiusLimit = null;
  6844. this.upperRadiusLimit = null;
  6845. this.angularSensibility = 1000.0;
  6846. this.wheelPrecision = 3.0;
  6847. this.keysUp = [38];
  6848. this.keysDown = [40];
  6849. this.keysLeft = [37];
  6850. this.keysRight = [39];
  6851. this.zoomOnFactor = 1;
  6852. this.targetScreenOffset = BABYLON.Vector2.Zero();
  6853. this._keys = [];
  6854. this._viewMatrix = new BABYLON.Matrix();
  6855. this.checkCollisions = false;
  6856. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  6857. this._collider = new BABYLON.Collider();
  6858. this._previousPosition = BABYLON.Vector3.Zero();
  6859. this._collisionVelocity = BABYLON.Vector3.Zero();
  6860. this._newPosition = BABYLON.Vector3.Zero();
  6861. // Pinch
  6862. // value for pinch step scaling
  6863. // set to 20 by default
  6864. this.pinchPrecision = 20;
  6865. this.getViewMatrix();
  6866. }
  6867. ArcRotateCamera.prototype._getTargetPosition = function () {
  6868. return this.target.position || this.target;
  6869. };
  6870. // Cache
  6871. ArcRotateCamera.prototype._initCache = function () {
  6872. _super.prototype._initCache.call(this);
  6873. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6874. this._cache.alpha = undefined;
  6875. this._cache.beta = undefined;
  6876. this._cache.radius = undefined;
  6877. this._cache.targetScreenOffset = undefined;
  6878. };
  6879. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  6880. if (!ignoreParentClass) {
  6881. _super.prototype._updateCache.call(this);
  6882. }
  6883. this._cache.target.copyFrom(this._getTargetPosition());
  6884. this._cache.alpha = this.alpha;
  6885. this._cache.beta = this.beta;
  6886. this._cache.radius = this.radius;
  6887. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  6888. };
  6889. // Synchronized
  6890. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  6891. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  6892. return false;
  6893. 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);
  6894. };
  6895. // Methods
  6896. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  6897. var _this = this;
  6898. var previousPosition;
  6899. var pointerId;
  6900. // to know if pinch started
  6901. var pinchStarted = false;
  6902. // two pinch point on X
  6903. // that will use for find if user action is pinch open or pinch close
  6904. var pinchPointX1, pinchPointX2;
  6905. if (this._attachedElement) {
  6906. return;
  6907. }
  6908. this._attachedElement = element;
  6909. var engine = this.getEngine();
  6910. if (this._onPointerDown === undefined) {
  6911. this._onPointerDown = function (evt) {
  6912. if (pointerId) {
  6913. return;
  6914. }
  6915. pointerId = evt.pointerId;
  6916. previousPosition = {
  6917. x: evt.clientX,
  6918. y: evt.clientY
  6919. };
  6920. if (!noPreventDefault) {
  6921. evt.preventDefault();
  6922. }
  6923. };
  6924. this._onPointerUp = function (evt) {
  6925. previousPosition = null;
  6926. pointerId = null;
  6927. if (!noPreventDefault) {
  6928. evt.preventDefault();
  6929. }
  6930. };
  6931. this._onPointerMove = function (evt) {
  6932. if (!previousPosition) {
  6933. return;
  6934. }
  6935. if (pointerId !== evt.pointerId) {
  6936. return;
  6937. }
  6938. // return pinch is started
  6939. if (pinchStarted) {
  6940. return;
  6941. }
  6942. var offsetX = evt.clientX - previousPosition.x;
  6943. var offsetY = evt.clientY - previousPosition.y;
  6944. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6945. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6946. previousPosition = {
  6947. x: evt.clientX,
  6948. y: evt.clientY
  6949. };
  6950. if (!noPreventDefault) {
  6951. evt.preventDefault();
  6952. }
  6953. };
  6954. this._onMouseMove = function (evt) {
  6955. if (!engine.isPointerLock) {
  6956. return;
  6957. }
  6958. // return pinch is started
  6959. if (pinchStarted) {
  6960. return;
  6961. }
  6962. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6963. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6964. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  6965. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  6966. if (!noPreventDefault) {
  6967. evt.preventDefault();
  6968. }
  6969. };
  6970. this._wheel = function (event) {
  6971. var delta = 0;
  6972. if (event.wheelDelta) {
  6973. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  6974. }
  6975. else if (event.detail) {
  6976. delta = -event.detail / _this.wheelPrecision;
  6977. }
  6978. if (delta)
  6979. _this.inertialRadiusOffset += delta;
  6980. if (event.preventDefault) {
  6981. if (!noPreventDefault) {
  6982. event.preventDefault();
  6983. }
  6984. }
  6985. };
  6986. this._onKeyDown = function (evt) {
  6987. 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) {
  6988. var index = _this._keys.indexOf(evt.keyCode);
  6989. if (index === -1) {
  6990. _this._keys.push(evt.keyCode);
  6991. }
  6992. if (evt.preventDefault) {
  6993. if (!noPreventDefault) {
  6994. evt.preventDefault();
  6995. }
  6996. }
  6997. }
  6998. };
  6999. this._onKeyUp = function (evt) {
  7000. 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) {
  7001. var index = _this._keys.indexOf(evt.keyCode);
  7002. if (index >= 0) {
  7003. _this._keys.splice(index, 1);
  7004. }
  7005. if (evt.preventDefault) {
  7006. if (!noPreventDefault) {
  7007. evt.preventDefault();
  7008. }
  7009. }
  7010. }
  7011. };
  7012. this._onLostFocus = function () {
  7013. _this._keys = [];
  7014. pointerId = null;
  7015. };
  7016. this._onGestureStart = function (e) {
  7017. if (window.MSGesture === undefined) {
  7018. return;
  7019. }
  7020. if (!_this._MSGestureHandler) {
  7021. _this._MSGestureHandler = new MSGesture();
  7022. _this._MSGestureHandler.target = element;
  7023. }
  7024. _this._MSGestureHandler.addPointer(e.pointerId);
  7025. };
  7026. this._onGesture = function (e) {
  7027. _this.radius *= e.scale;
  7028. if (e.preventDefault) {
  7029. if (!noPreventDefault) {
  7030. e.stopPropagation();
  7031. e.preventDefault();
  7032. }
  7033. }
  7034. };
  7035. this._reset = function () {
  7036. _this._keys = [];
  7037. _this.inertialAlphaOffset = 0;
  7038. _this.inertialBetaOffset = 0;
  7039. _this.inertialRadiusOffset = 0;
  7040. previousPosition = null;
  7041. pointerId = null;
  7042. };
  7043. this._touchStart = function (event) {
  7044. if (event.touches.length === 2) {
  7045. //-- start pinch if two fingers on the screen
  7046. pinchStarted = true;
  7047. _this._pinchStart(event);
  7048. }
  7049. };
  7050. this._touchMove = function (event) {
  7051. if (pinchStarted) {
  7052. //-- make scaling
  7053. _this._pinchMove(event);
  7054. }
  7055. };
  7056. this._touchEnd = function (event) {
  7057. if (pinchStarted) {
  7058. //-- end of pinch
  7059. _this._pinchEnd(event);
  7060. }
  7061. };
  7062. this._pinchStart = function (event) {
  7063. // save origin touch point
  7064. pinchPointX1 = event.touches[0].clientX;
  7065. pinchPointX2 = event.touches[1].clientX;
  7066. // block the camera
  7067. // if not it rotate around target during pinch
  7068. pinchStarted = true;
  7069. };
  7070. this._pinchMove = function (event) {
  7071. // variable for new camera's radius
  7072. var delta = 0;
  7073. // variables to know if pinch open or pinch close
  7074. var direction = 1;
  7075. var distanceXOrigine, distanceXNow;
  7076. if (event.touches.length !== 2)
  7077. return;
  7078. // calculate absolute distances of the two fingers
  7079. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7080. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7081. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7082. if (distanceXNow < distanceXOrigine) {
  7083. direction = -1;
  7084. }
  7085. // calculate new radius
  7086. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7087. // set new radius
  7088. _this.inertialRadiusOffset -= delta;
  7089. // save origin touch point
  7090. pinchPointX1 = event.touches[0].clientX;
  7091. pinchPointX2 = event.touches[1].clientX;
  7092. };
  7093. this._pinchEnd = function (event) {
  7094. // cancel pinch and deblock camera rotation
  7095. pinchStarted = false;
  7096. };
  7097. }
  7098. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7099. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7100. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7101. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7102. element.addEventListener("mousemove", this._onMouseMove, false);
  7103. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7104. element.addEventListener("MSGestureChange", this._onGesture, false);
  7105. element.addEventListener('mousewheel', this._wheel, false);
  7106. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7107. // pinch
  7108. element.addEventListener('touchstart', this._touchStart, false);
  7109. element.addEventListener('touchmove', this._touchMove, false);
  7110. element.addEventListener('touchend', this._touchEnd, false);
  7111. BABYLON.Tools.RegisterTopRootEvents([
  7112. { name: "keydown", handler: this._onKeyDown },
  7113. { name: "keyup", handler: this._onKeyUp },
  7114. { name: "blur", handler: this._onLostFocus }
  7115. ]);
  7116. };
  7117. ArcRotateCamera.prototype.detachControl = function (element) {
  7118. if (this._attachedElement != element) {
  7119. return;
  7120. }
  7121. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7122. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7123. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7124. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7125. element.removeEventListener("mousemove", this._onMouseMove);
  7126. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7127. element.removeEventListener("MSGestureChange", this._onGesture);
  7128. element.removeEventListener('mousewheel', this._wheel);
  7129. element.removeEventListener('DOMMouseScroll', this._wheel);
  7130. // pinch
  7131. element.removeEventListener('touchstart', this._touchStart);
  7132. element.removeEventListener('touchmove', this._touchMove);
  7133. element.removeEventListener('touchend', this._touchEnd);
  7134. BABYLON.Tools.UnregisterTopRootEvents([
  7135. { name: "keydown", handler: this._onKeyDown },
  7136. { name: "keyup", handler: this._onKeyUp },
  7137. { name: "blur", handler: this._onLostFocus }
  7138. ]);
  7139. this._MSGestureHandler = null;
  7140. this._attachedElement = null;
  7141. if (this._reset) {
  7142. this._reset();
  7143. }
  7144. };
  7145. ArcRotateCamera.prototype._update = function () {
  7146. for (var index = 0; index < this._keys.length; index++) {
  7147. var keyCode = this._keys[index];
  7148. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7149. this.inertialAlphaOffset -= 0.01;
  7150. }
  7151. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7152. this.inertialBetaOffset -= 0.01;
  7153. }
  7154. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7155. this.inertialAlphaOffset += 0.01;
  7156. }
  7157. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7158. this.inertialBetaOffset += 0.01;
  7159. }
  7160. }
  7161. // Inertia
  7162. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7163. this.alpha += this.inertialAlphaOffset;
  7164. this.beta += this.inertialBetaOffset;
  7165. this.radius -= this.inertialRadiusOffset;
  7166. this.inertialAlphaOffset *= this.inertia;
  7167. this.inertialBetaOffset *= this.inertia;
  7168. this.inertialRadiusOffset *= this.inertia;
  7169. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7170. this.inertialAlphaOffset = 0;
  7171. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7172. this.inertialBetaOffset = 0;
  7173. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7174. this.inertialRadiusOffset = 0;
  7175. }
  7176. // Limits
  7177. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7178. this.alpha = this.lowerAlphaLimit;
  7179. }
  7180. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7181. this.alpha = this.upperAlphaLimit;
  7182. }
  7183. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7184. this.beta = this.lowerBetaLimit;
  7185. }
  7186. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7187. this.beta = this.upperBetaLimit;
  7188. }
  7189. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7190. this.radius = this.lowerRadiusLimit;
  7191. }
  7192. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7193. this.radius = this.upperRadiusLimit;
  7194. }
  7195. };
  7196. ArcRotateCamera.prototype.setPosition = function (position) {
  7197. var radiusv3 = position.subtract(this._getTargetPosition());
  7198. this.radius = radiusv3.length();
  7199. // Alpha
  7200. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7201. if (radiusv3.z < 0) {
  7202. this.alpha = 2 * Math.PI - this.alpha;
  7203. }
  7204. // Beta
  7205. this.beta = Math.acos(radiusv3.y / this.radius);
  7206. };
  7207. ArcRotateCamera.prototype._getViewMatrix = function () {
  7208. // Compute
  7209. var cosa = Math.cos(this.alpha);
  7210. var sina = Math.sin(this.alpha);
  7211. var cosb = Math.cos(this.beta);
  7212. var sinb = Math.sin(this.beta);
  7213. var target = this._getTargetPosition();
  7214. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7215. if (this.checkCollisions) {
  7216. this._collider.radius = this.collisionRadius;
  7217. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7218. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7219. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7220. this.position.copyFrom(this._previousPosition);
  7221. this.alpha = this._previousAlpha;
  7222. this.beta = this._previousBeta;
  7223. this.radius = this._previousRadius;
  7224. if (this.onCollide) {
  7225. this.onCollide(this._collider.collidedMesh);
  7226. }
  7227. }
  7228. }
  7229. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7230. this._previousAlpha = this.alpha;
  7231. this._previousBeta = this.beta;
  7232. this._previousRadius = this.radius;
  7233. this._previousPosition.copyFrom(this.position);
  7234. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7235. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7236. return this._viewMatrix;
  7237. };
  7238. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7239. meshes = meshes || this.getScene().meshes;
  7240. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7241. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7242. this.radius = distance * this.zoomOnFactor;
  7243. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7244. };
  7245. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7246. var meshesOrMinMaxVector;
  7247. var distance;
  7248. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7249. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7250. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7251. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7252. }
  7253. else {
  7254. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7255. distance = meshesOrMinMaxVectorAndDistance.distance;
  7256. }
  7257. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7258. this.maxZ = distance * 2;
  7259. };
  7260. return ArcRotateCamera;
  7261. })(BABYLON.Camera);
  7262. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7263. })(BABYLON || (BABYLON = {}));
  7264. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7265. (function (BABYLON) {
  7266. var Scene = (function () {
  7267. // Constructor
  7268. function Scene(engine) {
  7269. // Members
  7270. this.autoClear = true;
  7271. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7272. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7273. this.forceWireframe = false;
  7274. this.forcePointsCloud = false;
  7275. this.forceShowBoundingBoxes = false;
  7276. this.animationsEnabled = true;
  7277. this.cameraToUseForPointers = null; // Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position
  7278. // Fog
  7279. this.fogEnabled = true;
  7280. this.fogMode = Scene.FOGMODE_NONE;
  7281. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7282. this.fogDensity = 0.1;
  7283. this.fogStart = 0;
  7284. this.fogEnd = 1000.0;
  7285. // Lights
  7286. this.shadowsEnabled = true;
  7287. this.lightsEnabled = true;
  7288. this.lights = new Array();
  7289. // Cameras
  7290. this.cameras = new Array();
  7291. this.activeCameras = new Array();
  7292. // Meshes
  7293. this.meshes = new Array();
  7294. // Geometries
  7295. this._geometries = new Array();
  7296. this.materials = new Array();
  7297. this.multiMaterials = new Array();
  7298. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7299. // Textures
  7300. this.texturesEnabled = true;
  7301. this.textures = new Array();
  7302. // Particles
  7303. this.particlesEnabled = true;
  7304. this.particleSystems = new Array();
  7305. // Sprites
  7306. this.spriteManagers = new Array();
  7307. // Layers
  7308. this.layers = new Array();
  7309. // Skeletons
  7310. this.skeletonsEnabled = true;
  7311. this.skeletons = new Array();
  7312. // Lens flares
  7313. this.lensFlaresEnabled = true;
  7314. this.lensFlareSystems = new Array();
  7315. // Collisions
  7316. this.collisionsEnabled = true;
  7317. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7318. // Postprocesses
  7319. this.postProcessesEnabled = true;
  7320. // Customs render targets
  7321. this.renderTargetsEnabled = true;
  7322. this.customRenderTargets = new Array();
  7323. // Imported meshes
  7324. this.importedMeshesFiles = new Array();
  7325. this._actionManagers = new Array();
  7326. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7327. // Procedural textures
  7328. this.proceduralTexturesEnabled = true;
  7329. this._proceduralTextures = new Array();
  7330. this.soundTracks = new Array();
  7331. this._totalVertices = 0;
  7332. this._activeVertices = 0;
  7333. this._activeParticles = 0;
  7334. this._lastFrameDuration = 0;
  7335. this._evaluateActiveMeshesDuration = 0;
  7336. this._renderTargetsDuration = 0;
  7337. this._particlesDuration = 0;
  7338. this._renderDuration = 0;
  7339. this._spritesDuration = 0;
  7340. this._animationRatio = 0;
  7341. this._renderId = 0;
  7342. this._executeWhenReadyTimeoutId = -1;
  7343. this._toBeDisposed = new BABYLON.SmartArray(256);
  7344. this._onReadyCallbacks = new Array();
  7345. this._pendingData = []; //ANY
  7346. this._onBeforeRenderCallbacks = new Array();
  7347. this._onAfterRenderCallbacks = new Array();
  7348. this._activeMeshes = new BABYLON.SmartArray(256);
  7349. this._processedMaterials = new BABYLON.SmartArray(256);
  7350. this._renderTargets = new BABYLON.SmartArray(256);
  7351. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7352. this._activeSkeletons = new BABYLON.SmartArray(32);
  7353. this._activeBones = 0;
  7354. this._activeAnimatables = new Array();
  7355. this._transformMatrix = BABYLON.Matrix.Zero();
  7356. this._scaledPosition = BABYLON.Vector3.Zero();
  7357. this._scaledVelocity = BABYLON.Vector3.Zero();
  7358. this._engine = engine;
  7359. engine.scenes.push(this);
  7360. this._renderingManager = new BABYLON.RenderingManager(this);
  7361. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7362. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7363. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7364. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7365. this.attachControl();
  7366. this._debugLayer = new BABYLON.DebugLayer(this);
  7367. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7368. }
  7369. Object.defineProperty(Scene.prototype, "debugLayer", {
  7370. // Properties
  7371. get: function () {
  7372. return this._debugLayer;
  7373. },
  7374. enumerable: true,
  7375. configurable: true
  7376. });
  7377. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7378. get: function () {
  7379. return this._meshUnderPointer;
  7380. },
  7381. enumerable: true,
  7382. configurable: true
  7383. });
  7384. Object.defineProperty(Scene.prototype, "pointerX", {
  7385. get: function () {
  7386. return this._pointerX;
  7387. },
  7388. enumerable: true,
  7389. configurable: true
  7390. });
  7391. Object.defineProperty(Scene.prototype, "pointerY", {
  7392. get: function () {
  7393. return this._pointerY;
  7394. },
  7395. enumerable: true,
  7396. configurable: true
  7397. });
  7398. Scene.prototype.getCachedMaterial = function () {
  7399. return this._cachedMaterial;
  7400. };
  7401. Scene.prototype.getBoundingBoxRenderer = function () {
  7402. return this._boundingBoxRenderer;
  7403. };
  7404. Scene.prototype.getOutlineRenderer = function () {
  7405. return this._outlineRenderer;
  7406. };
  7407. Scene.prototype.getEngine = function () {
  7408. return this._engine;
  7409. };
  7410. Scene.prototype.getTotalVertices = function () {
  7411. return this._totalVertices;
  7412. };
  7413. Scene.prototype.getActiveVertices = function () {
  7414. return this._activeVertices;
  7415. };
  7416. Scene.prototype.getActiveParticles = function () {
  7417. return this._activeParticles;
  7418. };
  7419. Scene.prototype.getActiveBones = function () {
  7420. return this._activeBones;
  7421. };
  7422. // Stats
  7423. Scene.prototype.getLastFrameDuration = function () {
  7424. return this._lastFrameDuration;
  7425. };
  7426. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7427. return this._evaluateActiveMeshesDuration;
  7428. };
  7429. Scene.prototype.getActiveMeshes = function () {
  7430. return this._activeMeshes;
  7431. };
  7432. Scene.prototype.getRenderTargetsDuration = function () {
  7433. return this._renderTargetsDuration;
  7434. };
  7435. Scene.prototype.getRenderDuration = function () {
  7436. return this._renderDuration;
  7437. };
  7438. Scene.prototype.getParticlesDuration = function () {
  7439. return this._particlesDuration;
  7440. };
  7441. Scene.prototype.getSpritesDuration = function () {
  7442. return this._spritesDuration;
  7443. };
  7444. Scene.prototype.getAnimationRatio = function () {
  7445. return this._animationRatio;
  7446. };
  7447. Scene.prototype.getRenderId = function () {
  7448. return this._renderId;
  7449. };
  7450. Scene.prototype._updatePointerPosition = function (evt) {
  7451. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7452. this._pointerX = evt.clientX - canvasRect.left;
  7453. this._pointerY = evt.clientY - canvasRect.top;
  7454. if (this.cameraToUseForPointers) {
  7455. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7456. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7457. }
  7458. };
  7459. // Pointers handling
  7460. Scene.prototype.attachControl = function () {
  7461. var _this = this;
  7462. this._onPointerMove = function (evt) {
  7463. var canvas = _this._engine.getRenderingCanvas();
  7464. _this._updatePointerPosition(evt);
  7465. var pickResult = _this.pick(_this._pointerX, _this._pointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPointerTriggers; }, false, _this.cameraToUseForPointers);
  7466. if (pickResult.hit) {
  7467. _this._meshUnderPointer = pickResult.pickedMesh;
  7468. _this.setPointerOverMesh(pickResult.pickedMesh);
  7469. canvas.style.cursor = "pointer";
  7470. }
  7471. else {
  7472. _this.setPointerOverMesh(null);
  7473. canvas.style.cursor = "";
  7474. _this._meshUnderPointer = null;
  7475. }
  7476. };
  7477. this._onPointerDown = function (evt) {
  7478. var predicate = null;
  7479. if (!_this.onPointerDown) {
  7480. predicate = function (mesh) {
  7481. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7482. };
  7483. }
  7484. _this._updatePointerPosition(evt);
  7485. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7486. if (pickResult.hit) {
  7487. if (pickResult.pickedMesh.actionManager) {
  7488. switch (evt.button) {
  7489. case 0:
  7490. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7491. break;
  7492. case 1:
  7493. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7494. break;
  7495. case 2:
  7496. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7497. break;
  7498. }
  7499. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7500. }
  7501. }
  7502. if (_this.onPointerDown) {
  7503. _this.onPointerDown(evt, pickResult);
  7504. }
  7505. };
  7506. this._onKeyDown = function (evt) {
  7507. if (_this.actionManager) {
  7508. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7509. }
  7510. };
  7511. this._onKeyUp = function (evt) {
  7512. if (_this.actionManager) {
  7513. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  7514. }
  7515. };
  7516. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7517. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7518. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7519. window.addEventListener("keydown", this._onKeyDown, false);
  7520. window.addEventListener("keyup", this._onKeyUp, false);
  7521. };
  7522. Scene.prototype.detachControl = function () {
  7523. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7524. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  7525. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  7526. window.removeEventListener("keydown", this._onKeyDown);
  7527. window.removeEventListener("keyup", this._onKeyUp);
  7528. };
  7529. // Ready
  7530. Scene.prototype.isReady = function () {
  7531. if (this._pendingData.length > 0) {
  7532. return false;
  7533. }
  7534. for (var index = 0; index < this._geometries.length; index++) {
  7535. var geometry = this._geometries[index];
  7536. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  7537. return false;
  7538. }
  7539. }
  7540. for (index = 0; index < this.meshes.length; index++) {
  7541. var mesh = this.meshes[index];
  7542. if (!mesh.isReady()) {
  7543. return false;
  7544. }
  7545. var mat = mesh.material;
  7546. if (mat) {
  7547. if (!mat.isReady(mesh)) {
  7548. return false;
  7549. }
  7550. }
  7551. }
  7552. return true;
  7553. };
  7554. Scene.prototype.resetCachedMaterial = function () {
  7555. this._cachedMaterial = null;
  7556. };
  7557. Scene.prototype.registerBeforeRender = function (func) {
  7558. this._onBeforeRenderCallbacks.push(func);
  7559. };
  7560. Scene.prototype.unregisterBeforeRender = function (func) {
  7561. var index = this._onBeforeRenderCallbacks.indexOf(func);
  7562. if (index > -1) {
  7563. this._onBeforeRenderCallbacks.splice(index, 1);
  7564. }
  7565. };
  7566. Scene.prototype.registerAfterRender = function (func) {
  7567. this._onAfterRenderCallbacks.push(func);
  7568. };
  7569. Scene.prototype.unregisterAfterRender = function (func) {
  7570. var index = this._onAfterRenderCallbacks.indexOf(func);
  7571. if (index > -1) {
  7572. this._onAfterRenderCallbacks.splice(index, 1);
  7573. }
  7574. };
  7575. Scene.prototype._addPendingData = function (data) {
  7576. this._pendingData.push(data);
  7577. };
  7578. Scene.prototype._removePendingData = function (data) {
  7579. var index = this._pendingData.indexOf(data);
  7580. if (index !== -1) {
  7581. this._pendingData.splice(index, 1);
  7582. }
  7583. };
  7584. Scene.prototype.getWaitingItemsCount = function () {
  7585. return this._pendingData.length;
  7586. };
  7587. Scene.prototype.executeWhenReady = function (func) {
  7588. var _this = this;
  7589. this._onReadyCallbacks.push(func);
  7590. if (this._executeWhenReadyTimeoutId !== -1) {
  7591. return;
  7592. }
  7593. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7594. _this._checkIsReady();
  7595. }, 150);
  7596. };
  7597. Scene.prototype._checkIsReady = function () {
  7598. var _this = this;
  7599. if (this.isReady()) {
  7600. this._onReadyCallbacks.forEach(function (func) {
  7601. func();
  7602. });
  7603. this._onReadyCallbacks = [];
  7604. this._executeWhenReadyTimeoutId = -1;
  7605. return;
  7606. }
  7607. this._executeWhenReadyTimeoutId = setTimeout(function () {
  7608. _this._checkIsReady();
  7609. }, 150);
  7610. };
  7611. // Animations
  7612. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  7613. if (speedRatio === undefined) {
  7614. speedRatio = 1.0;
  7615. }
  7616. this.stopAnimation(target);
  7617. if (!animatable) {
  7618. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  7619. }
  7620. // Local animations
  7621. if (target.animations) {
  7622. animatable.appendAnimations(target, target.animations);
  7623. }
  7624. // Children animations
  7625. if (target.getAnimatables) {
  7626. var animatables = target.getAnimatables();
  7627. for (var index = 0; index < animatables.length; index++) {
  7628. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  7629. }
  7630. }
  7631. return animatable;
  7632. };
  7633. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  7634. if (speedRatio === undefined) {
  7635. speedRatio = 1.0;
  7636. }
  7637. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  7638. return animatable;
  7639. };
  7640. Scene.prototype.getAnimatableByTarget = function (target) {
  7641. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7642. if (this._activeAnimatables[index].target === target) {
  7643. return this._activeAnimatables[index];
  7644. }
  7645. }
  7646. return null;
  7647. };
  7648. Scene.prototype.stopAnimation = function (target) {
  7649. var animatable = this.getAnimatableByTarget(target);
  7650. if (animatable) {
  7651. animatable.stop();
  7652. }
  7653. };
  7654. Scene.prototype._animate = function () {
  7655. if (!this.animationsEnabled) {
  7656. return;
  7657. }
  7658. if (!this._animationStartDate) {
  7659. this._animationStartDate = BABYLON.Tools.Now;
  7660. }
  7661. // Getting time
  7662. var now = BABYLON.Tools.Now;
  7663. var delay = now - this._animationStartDate;
  7664. for (var index = 0; index < this._activeAnimatables.length; index++) {
  7665. if (!this._activeAnimatables[index]._animate(delay)) {
  7666. this._activeAnimatables.splice(index, 1);
  7667. index--;
  7668. }
  7669. }
  7670. };
  7671. // Matrix
  7672. Scene.prototype.getViewMatrix = function () {
  7673. return this._viewMatrix;
  7674. };
  7675. Scene.prototype.getProjectionMatrix = function () {
  7676. return this._projectionMatrix;
  7677. };
  7678. Scene.prototype.getTransformMatrix = function () {
  7679. return this._transformMatrix;
  7680. };
  7681. Scene.prototype.setTransformMatrix = function (view, projection) {
  7682. this._viewMatrix = view;
  7683. this._projectionMatrix = projection;
  7684. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  7685. };
  7686. // Methods
  7687. Scene.prototype.setActiveCameraByID = function (id) {
  7688. var camera = this.getCameraByID(id);
  7689. if (camera) {
  7690. this.activeCamera = camera;
  7691. return camera;
  7692. }
  7693. return null;
  7694. };
  7695. Scene.prototype.setActiveCameraByName = function (name) {
  7696. var camera = this.getCameraByName(name);
  7697. if (camera) {
  7698. this.activeCamera = camera;
  7699. return camera;
  7700. }
  7701. return null;
  7702. };
  7703. Scene.prototype.getMaterialByID = function (id) {
  7704. for (var index = 0; index < this.materials.length; index++) {
  7705. if (this.materials[index].id === id) {
  7706. return this.materials[index];
  7707. }
  7708. }
  7709. return null;
  7710. };
  7711. Scene.prototype.getMaterialByName = function (name) {
  7712. for (var index = 0; index < this.materials.length; index++) {
  7713. if (this.materials[index].name === name) {
  7714. return this.materials[index];
  7715. }
  7716. }
  7717. return null;
  7718. };
  7719. Scene.prototype.getCameraByID = function (id) {
  7720. for (var index = 0; index < this.cameras.length; index++) {
  7721. if (this.cameras[index].id === id) {
  7722. return this.cameras[index];
  7723. }
  7724. }
  7725. return null;
  7726. };
  7727. Scene.prototype.getCameraByName = function (name) {
  7728. for (var index = 0; index < this.cameras.length; index++) {
  7729. if (this.cameras[index].name === name) {
  7730. return this.cameras[index];
  7731. }
  7732. }
  7733. return null;
  7734. };
  7735. Scene.prototype.getLightByName = function (name) {
  7736. for (var index = 0; index < this.lights.length; index++) {
  7737. if (this.lights[index].name === name) {
  7738. return this.lights[index];
  7739. }
  7740. }
  7741. return null;
  7742. };
  7743. Scene.prototype.getLightByID = function (id) {
  7744. for (var index = 0; index < this.lights.length; index++) {
  7745. if (this.lights[index].id === id) {
  7746. return this.lights[index];
  7747. }
  7748. }
  7749. return null;
  7750. };
  7751. Scene.prototype.getGeometryByID = function (id) {
  7752. for (var index = 0; index < this._geometries.length; index++) {
  7753. if (this._geometries[index].id === id) {
  7754. return this._geometries[index];
  7755. }
  7756. }
  7757. return null;
  7758. };
  7759. Scene.prototype.pushGeometry = function (geometry, force) {
  7760. if (!force && this.getGeometryByID(geometry.id)) {
  7761. return false;
  7762. }
  7763. this._geometries.push(geometry);
  7764. return true;
  7765. };
  7766. Scene.prototype.getGeometries = function () {
  7767. return this._geometries;
  7768. };
  7769. Scene.prototype.getMeshByID = function (id) {
  7770. for (var index = 0; index < this.meshes.length; index++) {
  7771. if (this.meshes[index].id === id) {
  7772. return this.meshes[index];
  7773. }
  7774. }
  7775. return null;
  7776. };
  7777. Scene.prototype.getLastMeshByID = function (id) {
  7778. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7779. if (this.meshes[index].id === id) {
  7780. return this.meshes[index];
  7781. }
  7782. }
  7783. return null;
  7784. };
  7785. Scene.prototype.getLastEntryByID = function (id) {
  7786. for (var index = this.meshes.length - 1; index >= 0; index--) {
  7787. if (this.meshes[index].id === id) {
  7788. return this.meshes[index];
  7789. }
  7790. }
  7791. for (index = this.cameras.length - 1; index >= 0; index--) {
  7792. if (this.cameras[index].id === id) {
  7793. return this.cameras[index];
  7794. }
  7795. }
  7796. for (index = this.lights.length - 1; index >= 0; index--) {
  7797. if (this.lights[index].id === id) {
  7798. return this.lights[index];
  7799. }
  7800. }
  7801. return null;
  7802. };
  7803. Scene.prototype.getNodeByName = function (name) {
  7804. var mesh = this.getMeshByName(name);
  7805. if (mesh) {
  7806. return mesh;
  7807. }
  7808. var light = this.getLightByName(name);
  7809. if (light) {
  7810. return light;
  7811. }
  7812. return this.getCameraByName(name);
  7813. };
  7814. Scene.prototype.getMeshByName = function (name) {
  7815. for (var index = 0; index < this.meshes.length; index++) {
  7816. if (this.meshes[index].name === name) {
  7817. return this.meshes[index];
  7818. }
  7819. }
  7820. return null;
  7821. };
  7822. Scene.prototype.getLastSkeletonByID = function (id) {
  7823. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  7824. if (this.skeletons[index].id === id) {
  7825. return this.skeletons[index];
  7826. }
  7827. }
  7828. return null;
  7829. };
  7830. Scene.prototype.getSkeletonById = function (id) {
  7831. for (var index = 0; index < this.skeletons.length; index++) {
  7832. if (this.skeletons[index].id === id) {
  7833. return this.skeletons[index];
  7834. }
  7835. }
  7836. return null;
  7837. };
  7838. Scene.prototype.getSkeletonByName = function (name) {
  7839. for (var index = 0; index < this.skeletons.length; index++) {
  7840. if (this.skeletons[index].name === name) {
  7841. return this.skeletons[index];
  7842. }
  7843. }
  7844. return null;
  7845. };
  7846. Scene.prototype.isActiveMesh = function (mesh) {
  7847. return (this._activeMeshes.indexOf(mesh) !== -1);
  7848. };
  7849. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  7850. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  7851. var material = subMesh.getMaterial();
  7852. if (mesh.showSubMeshesBoundingBox) {
  7853. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  7854. }
  7855. if (material) {
  7856. // Render targets
  7857. if (material.getRenderTargetTextures) {
  7858. if (this._processedMaterials.indexOf(material) === -1) {
  7859. this._processedMaterials.push(material);
  7860. this._renderTargets.concat(material.getRenderTargetTextures());
  7861. }
  7862. }
  7863. // Dispatch
  7864. this._activeVertices += subMesh.indexCount;
  7865. this._renderingManager.dispatch(subMesh);
  7866. }
  7867. }
  7868. };
  7869. Scene.prototype._evaluateActiveMeshes = function () {
  7870. this._activeMeshes.reset();
  7871. this._renderingManager.reset();
  7872. this._processedMaterials.reset();
  7873. this._activeParticleSystems.reset();
  7874. this._activeSkeletons.reset();
  7875. this._boundingBoxRenderer.reset();
  7876. if (!this._frustumPlanes) {
  7877. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  7878. }
  7879. else {
  7880. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  7881. }
  7882. // Meshes
  7883. var meshes;
  7884. var len;
  7885. if (this._selectionOctree) {
  7886. var selection = this._selectionOctree.select(this._frustumPlanes);
  7887. meshes = selection.data;
  7888. len = selection.length;
  7889. }
  7890. else {
  7891. len = this.meshes.length;
  7892. meshes = this.meshes;
  7893. }
  7894. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  7895. var mesh = meshes[meshIndex];
  7896. if (mesh.isBlocked) {
  7897. continue;
  7898. }
  7899. this._totalVertices += mesh.getTotalVertices();
  7900. if (!mesh.isReady()) {
  7901. continue;
  7902. }
  7903. mesh.computeWorldMatrix();
  7904. // Intersections
  7905. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  7906. this._meshesForIntersections.pushNoDuplicate(mesh);
  7907. }
  7908. // Switch to current LOD
  7909. var meshLOD = mesh.getLOD(this.activeCamera);
  7910. if (!meshLOD) {
  7911. continue;
  7912. }
  7913. mesh._preActivate();
  7914. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  7915. this._activeMeshes.push(mesh);
  7916. mesh._activate(this._renderId);
  7917. this._activeMesh(meshLOD);
  7918. }
  7919. }
  7920. // Particle systems
  7921. var beforeParticlesDate = BABYLON.Tools.Now;
  7922. if (this.particlesEnabled) {
  7923. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  7924. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  7925. var particleSystem = this.particleSystems[particleIndex];
  7926. if (!particleSystem.isStarted()) {
  7927. continue;
  7928. }
  7929. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  7930. this._activeParticleSystems.push(particleSystem);
  7931. particleSystem.animate();
  7932. }
  7933. }
  7934. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  7935. }
  7936. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  7937. };
  7938. Scene.prototype._activeMesh = function (mesh) {
  7939. if (mesh.skeleton && this.skeletonsEnabled) {
  7940. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  7941. }
  7942. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  7943. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  7944. }
  7945. if (mesh && mesh.subMeshes) {
  7946. // Submeshes Octrees
  7947. var len;
  7948. var subMeshes;
  7949. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  7950. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  7951. len = intersections.length;
  7952. subMeshes = intersections.data;
  7953. }
  7954. else {
  7955. subMeshes = mesh.subMeshes;
  7956. len = subMeshes.length;
  7957. }
  7958. for (var subIndex = 0; subIndex < len; subIndex++) {
  7959. var subMesh = subMeshes[subIndex];
  7960. this._evaluateSubMesh(subMesh, mesh);
  7961. }
  7962. }
  7963. };
  7964. Scene.prototype.updateTransformMatrix = function (force) {
  7965. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  7966. };
  7967. Scene.prototype._renderForCamera = function (camera) {
  7968. var engine = this._engine;
  7969. this.activeCamera = camera;
  7970. if (!this.activeCamera)
  7971. throw new Error("Active camera not set");
  7972. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  7973. // Viewport
  7974. engine.setViewport(this.activeCamera.viewport);
  7975. // Camera
  7976. this._renderId++;
  7977. this.updateTransformMatrix();
  7978. if (this.beforeCameraRender) {
  7979. this.beforeCameraRender(this.activeCamera);
  7980. }
  7981. // Meshes
  7982. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  7983. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  7984. this._evaluateActiveMeshes();
  7985. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  7986. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  7987. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  7988. var skeleton = this._activeSkeletons.data[skeletonIndex];
  7989. skeleton.prepare();
  7990. this._activeBones += skeleton.bones.length;
  7991. }
  7992. // Render targets
  7993. var beforeRenderTargetDate = BABYLON.Tools.Now;
  7994. if (this.renderTargetsEnabled) {
  7995. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  7996. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  7997. var renderTarget = this._renderTargets.data[renderIndex];
  7998. if (renderTarget._shouldRender()) {
  7999. this._renderId++;
  8000. renderTarget.render();
  8001. }
  8002. }
  8003. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8004. this._renderId++;
  8005. }
  8006. if (this._renderTargets.length > 0) {
  8007. engine.restoreDefaultFramebuffer();
  8008. }
  8009. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8010. // Prepare Frame
  8011. this.postProcessManager._prepareFrame();
  8012. var beforeRenderDate = BABYLON.Tools.Now;
  8013. // Backgrounds
  8014. if (this.layers.length) {
  8015. engine.setDepthBuffer(false);
  8016. var layerIndex;
  8017. var layer;
  8018. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8019. layer = this.layers[layerIndex];
  8020. if (layer.isBackground) {
  8021. layer.render();
  8022. }
  8023. }
  8024. engine.setDepthBuffer(true);
  8025. }
  8026. // Render
  8027. BABYLON.Tools.StartPerformanceCounter("Main render");
  8028. this._renderingManager.render(null, null, true, true);
  8029. BABYLON.Tools.EndPerformanceCounter("Main render");
  8030. // Bounding boxes
  8031. this._boundingBoxRenderer.render();
  8032. // Lens flares
  8033. if (this.lensFlaresEnabled) {
  8034. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8035. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8036. this.lensFlareSystems[lensFlareSystemIndex].render();
  8037. }
  8038. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8039. }
  8040. // Foregrounds
  8041. if (this.layers.length) {
  8042. engine.setDepthBuffer(false);
  8043. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8044. layer = this.layers[layerIndex];
  8045. if (!layer.isBackground) {
  8046. layer.render();
  8047. }
  8048. }
  8049. engine.setDepthBuffer(true);
  8050. }
  8051. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8052. // Finalize frame
  8053. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8054. // Update camera
  8055. this.activeCamera._updateFromScene();
  8056. // Reset some special arrays
  8057. this._renderTargets.reset();
  8058. if (this.afterCameraRender) {
  8059. this.afterCameraRender(this.activeCamera);
  8060. }
  8061. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8062. };
  8063. Scene.prototype._processSubCameras = function (camera) {
  8064. if (camera.subCameras.length === 0) {
  8065. this._renderForCamera(camera);
  8066. return;
  8067. }
  8068. for (var index = 0; index < camera.subCameras.length; index++) {
  8069. this._renderForCamera(camera.subCameras[index]);
  8070. }
  8071. this.activeCamera = camera;
  8072. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8073. // Update camera
  8074. this.activeCamera._updateFromScene();
  8075. };
  8076. Scene.prototype._checkIntersections = function () {
  8077. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8078. var sourceMesh = this._meshesForIntersections.data[index];
  8079. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8080. var action = sourceMesh.actionManager.actions[actionIndex];
  8081. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8082. var otherMesh = action.getTriggerParameter();
  8083. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, false);
  8084. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8085. if (areIntersecting && currentIntersectionInProgress === -1 && action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8086. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8087. sourceMesh._intersectionsInProgress.push(otherMesh);
  8088. }
  8089. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8090. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8091. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8092. if (indexOfOther > -1) {
  8093. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8094. }
  8095. }
  8096. }
  8097. }
  8098. }
  8099. };
  8100. Scene.prototype.render = function () {
  8101. var startDate = BABYLON.Tools.Now;
  8102. this._particlesDuration = 0;
  8103. this._spritesDuration = 0;
  8104. this._activeParticles = 0;
  8105. this._renderDuration = 0;
  8106. this._renderTargetsDuration = 0;
  8107. this._evaluateActiveMeshesDuration = 0;
  8108. this._totalVertices = 0;
  8109. this._activeVertices = 0;
  8110. this._activeBones = 0;
  8111. this.getEngine().resetDrawCalls();
  8112. this._meshesForIntersections.reset();
  8113. this.resetCachedMaterial();
  8114. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8115. // Actions
  8116. if (this.actionManager) {
  8117. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8118. }
  8119. // Before render
  8120. if (this.beforeRender) {
  8121. this.beforeRender();
  8122. }
  8123. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8124. this._onBeforeRenderCallbacks[callbackIndex]();
  8125. }
  8126. // Animations
  8127. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8128. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8129. this._animate();
  8130. // Physics
  8131. if (this._physicsEngine) {
  8132. BABYLON.Tools.StartPerformanceCounter("Physics");
  8133. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8134. BABYLON.Tools.EndPerformanceCounter("Physics");
  8135. }
  8136. // Customs render targets
  8137. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8138. var engine = this.getEngine();
  8139. if (this.renderTargetsEnabled) {
  8140. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8141. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8142. var renderTarget = this.customRenderTargets[customIndex];
  8143. if (renderTarget._shouldRender()) {
  8144. this._renderId++;
  8145. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8146. if (!this.activeCamera)
  8147. throw new Error("Active camera not set");
  8148. // Viewport
  8149. engine.setViewport(this.activeCamera.viewport);
  8150. // Camera
  8151. this.updateTransformMatrix();
  8152. renderTarget.render();
  8153. }
  8154. }
  8155. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8156. this._renderId++;
  8157. }
  8158. if (this.customRenderTargets.length > 0) {
  8159. engine.restoreDefaultFramebuffer();
  8160. }
  8161. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8162. // Procedural textures
  8163. if (this.proceduralTexturesEnabled) {
  8164. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8165. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8166. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8167. if (proceduralTexture._shouldRender()) {
  8168. proceduralTexture.render();
  8169. }
  8170. }
  8171. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8172. }
  8173. // Clear
  8174. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8175. // Shadows
  8176. if (this.shadowsEnabled) {
  8177. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8178. var light = this.lights[lightIndex];
  8179. var shadowGenerator = light.getShadowGenerator();
  8180. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8181. this._renderTargets.push(shadowGenerator.getShadowMap());
  8182. }
  8183. }
  8184. }
  8185. // RenderPipeline
  8186. this.postProcessRenderPipelineManager.update();
  8187. // Multi-cameras?
  8188. if (this.activeCameras.length > 0) {
  8189. var currentRenderId = this._renderId;
  8190. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8191. this._renderId = currentRenderId;
  8192. this._processSubCameras(this.activeCameras[cameraIndex]);
  8193. }
  8194. }
  8195. else {
  8196. if (!this.activeCamera) {
  8197. throw new Error("No camera defined");
  8198. }
  8199. this._processSubCameras(this.activeCamera);
  8200. }
  8201. // Intersection checks
  8202. this._checkIntersections();
  8203. // Update the audio listener attached to the camera
  8204. this._updateAudioParameters();
  8205. // After render
  8206. if (this.afterRender) {
  8207. this.afterRender();
  8208. }
  8209. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8210. this._onAfterRenderCallbacks[callbackIndex]();
  8211. }
  8212. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8213. this._toBeDisposed.data[index].dispose();
  8214. this._toBeDisposed[index] = null;
  8215. }
  8216. this._toBeDisposed.reset();
  8217. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8218. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8219. };
  8220. Scene.prototype._updateAudioParameters = function () {
  8221. var listeningCamera;
  8222. var audioEngine = this._engine.getAudioEngine();
  8223. if (this.activeCameras.length > 0) {
  8224. listeningCamera = this.activeCameras[0];
  8225. }
  8226. else {
  8227. listeningCamera = this.activeCamera;
  8228. }
  8229. if (listeningCamera && audioEngine.canUseWebAudio) {
  8230. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8231. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8232. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8233. cameraDirection.normalize();
  8234. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8235. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8236. var sound = this.mainSoundTrack.soundCollection[i];
  8237. if (sound.useCustomAttenuation) {
  8238. sound.updateDistanceFromListener();
  8239. }
  8240. }
  8241. for (var i = 0; i < this.soundTracks.length; i++) {
  8242. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8243. var sound = this.soundTracks[i].soundCollection[j];
  8244. if (sound.useCustomAttenuation) {
  8245. sound.updateDistanceFromListener();
  8246. }
  8247. }
  8248. }
  8249. }
  8250. };
  8251. Scene.prototype.dispose = function () {
  8252. this.beforeRender = null;
  8253. this.afterRender = null;
  8254. this.skeletons = [];
  8255. this._boundingBoxRenderer.dispose();
  8256. // Debug layer
  8257. this.debugLayer.hide();
  8258. // Events
  8259. if (this.onDispose) {
  8260. this.onDispose();
  8261. }
  8262. this._onBeforeRenderCallbacks = [];
  8263. this._onAfterRenderCallbacks = [];
  8264. this.detachControl();
  8265. // Detach cameras
  8266. var canvas = this._engine.getRenderingCanvas();
  8267. var index;
  8268. for (index = 0; index < this.cameras.length; index++) {
  8269. this.cameras[index].detachControl(canvas);
  8270. }
  8271. while (this.lights.length) {
  8272. this.lights[0].dispose();
  8273. }
  8274. while (this.meshes.length) {
  8275. this.meshes[0].dispose(true);
  8276. }
  8277. while (this.cameras.length) {
  8278. this.cameras[0].dispose();
  8279. }
  8280. while (this.materials.length) {
  8281. this.materials[0].dispose();
  8282. }
  8283. while (this.particleSystems.length) {
  8284. this.particleSystems[0].dispose();
  8285. }
  8286. while (this.spriteManagers.length) {
  8287. this.spriteManagers[0].dispose();
  8288. }
  8289. while (this.layers.length) {
  8290. this.layers[0].dispose();
  8291. }
  8292. while (this.textures.length) {
  8293. this.textures[0].dispose();
  8294. }
  8295. // Post-processes
  8296. this.postProcessManager.dispose();
  8297. // Physics
  8298. if (this._physicsEngine) {
  8299. this.disablePhysicsEngine();
  8300. }
  8301. // Remove from engine
  8302. index = this._engine.scenes.indexOf(this);
  8303. if (index > -1) {
  8304. this._engine.scenes.splice(index, 1);
  8305. }
  8306. this._engine.wipeCaches();
  8307. };
  8308. // Collisions
  8309. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8310. if (excludedMesh === void 0) { excludedMesh = null; }
  8311. position.divideToRef(collider.radius, this._scaledPosition);
  8312. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8313. collider.retry = 0;
  8314. collider.initialVelocity = this._scaledVelocity;
  8315. collider.initialPosition = this._scaledPosition;
  8316. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8317. finalPosition.multiplyInPlace(collider.radius);
  8318. };
  8319. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8320. if (excludedMesh === void 0) { excludedMesh = null; }
  8321. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  8322. if (collider.retry >= maximumRetry) {
  8323. finalPosition.copyFrom(position);
  8324. return;
  8325. }
  8326. collider._initialize(position, velocity, closeDistance);
  8327. for (var index = 0; index < this.meshes.length; index++) {
  8328. var mesh = this.meshes[index];
  8329. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  8330. mesh._checkCollision(collider);
  8331. }
  8332. }
  8333. if (!collider.collisionFound) {
  8334. position.addToRef(velocity, finalPosition);
  8335. return;
  8336. }
  8337. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  8338. collider._getResponse(position, velocity);
  8339. }
  8340. if (velocity.length() <= closeDistance) {
  8341. finalPosition.copyFrom(position);
  8342. return;
  8343. }
  8344. collider.retry++;
  8345. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  8346. };
  8347. // Octrees
  8348. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  8349. if (maxCapacity === void 0) { maxCapacity = 64; }
  8350. if (maxDepth === void 0) { maxDepth = 2; }
  8351. if (!this._selectionOctree) {
  8352. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  8353. }
  8354. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8355. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8356. for (var index = 0; index < this.meshes.length; index++) {
  8357. var mesh = this.meshes[index];
  8358. mesh.computeWorldMatrix(true);
  8359. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  8360. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  8361. BABYLON.Tools.CheckExtends(minBox, min, max);
  8362. BABYLON.Tools.CheckExtends(maxBox, min, max);
  8363. }
  8364. // Update octree
  8365. this._selectionOctree.update(min, max, this.meshes);
  8366. return this._selectionOctree;
  8367. };
  8368. // Picking
  8369. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  8370. var engine = this._engine;
  8371. if (!camera) {
  8372. if (!this.activeCamera)
  8373. throw new Error("Active camera not set");
  8374. camera = this.activeCamera;
  8375. }
  8376. var cameraViewport = camera.viewport;
  8377. var viewport = cameraViewport.toGlobal(engine);
  8378. // Moving coordinates to local viewport world
  8379. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  8380. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  8381. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8382. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  8383. };
  8384. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  8385. var pickingInfo = null;
  8386. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  8387. var mesh = this.meshes[meshIndex];
  8388. if (predicate) {
  8389. if (!predicate(mesh)) {
  8390. continue;
  8391. }
  8392. }
  8393. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  8394. continue;
  8395. }
  8396. var world = mesh.getWorldMatrix();
  8397. var ray = rayFunction(world);
  8398. var result = mesh.intersects(ray, fastCheck);
  8399. if (!result || !result.hit)
  8400. continue;
  8401. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  8402. continue;
  8403. pickingInfo = result;
  8404. if (fastCheck) {
  8405. break;
  8406. }
  8407. }
  8408. return pickingInfo || new BABYLON.PickingInfo();
  8409. };
  8410. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  8411. var _this = this;
  8412. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  8413. /// <param name="x">X position on screen</param>
  8414. /// <param name="y">Y position on screen</param>
  8415. /// <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>
  8416. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  8417. /// <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>
  8418. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  8419. };
  8420. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  8421. var _this = this;
  8422. return this._internalPick(function (world) {
  8423. if (!_this._pickWithRayInverseMatrix) {
  8424. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  8425. }
  8426. world.invertToRef(_this._pickWithRayInverseMatrix);
  8427. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  8428. }, predicate, fastCheck);
  8429. };
  8430. Scene.prototype.setPointerOverMesh = function (mesh) {
  8431. if (this._pointerOverMesh === mesh) {
  8432. return;
  8433. }
  8434. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8435. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8436. }
  8437. this._pointerOverMesh = mesh;
  8438. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  8439. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  8440. }
  8441. };
  8442. Scene.prototype.getPointerOverMesh = function () {
  8443. return this._pointerOverMesh;
  8444. };
  8445. // Physics
  8446. Scene.prototype.getPhysicsEngine = function () {
  8447. return this._physicsEngine;
  8448. };
  8449. Scene.prototype.enablePhysics = function (gravity, plugin) {
  8450. if (this._physicsEngine) {
  8451. return true;
  8452. }
  8453. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  8454. if (!this._physicsEngine.isSupported()) {
  8455. this._physicsEngine = null;
  8456. return false;
  8457. }
  8458. this._physicsEngine._initialize(gravity);
  8459. return true;
  8460. };
  8461. Scene.prototype.disablePhysicsEngine = function () {
  8462. if (!this._physicsEngine) {
  8463. return;
  8464. }
  8465. this._physicsEngine.dispose();
  8466. this._physicsEngine = undefined;
  8467. };
  8468. Scene.prototype.isPhysicsEnabled = function () {
  8469. return this._physicsEngine !== undefined;
  8470. };
  8471. Scene.prototype.setGravity = function (gravity) {
  8472. if (!this._physicsEngine) {
  8473. return;
  8474. }
  8475. this._physicsEngine._setGravity(gravity);
  8476. };
  8477. Scene.prototype.createCompoundImpostor = function (parts, options) {
  8478. if (parts.parts) {
  8479. options = parts;
  8480. parts = parts.parts;
  8481. }
  8482. if (!this._physicsEngine) {
  8483. return null;
  8484. }
  8485. for (var index = 0; index < parts.length; index++) {
  8486. var mesh = parts[index].mesh;
  8487. mesh._physicImpostor = parts[index].impostor;
  8488. mesh._physicsMass = options.mass / parts.length;
  8489. mesh._physicsFriction = options.friction;
  8490. mesh._physicRestitution = options.restitution;
  8491. }
  8492. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  8493. };
  8494. //ANY
  8495. Scene.prototype.deleteCompoundImpostor = function (compound) {
  8496. for (var index = 0; index < compound.parts.length; index++) {
  8497. var mesh = compound.parts[index].mesh;
  8498. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8499. this._physicsEngine._unregisterMesh(mesh);
  8500. }
  8501. };
  8502. // Tags
  8503. Scene.prototype._getByTags = function (list, tagsQuery) {
  8504. if (tagsQuery === undefined) {
  8505. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  8506. return list;
  8507. }
  8508. var listByTags = [];
  8509. for (var i in list) {
  8510. var item = list[i];
  8511. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  8512. listByTags.push(item);
  8513. }
  8514. }
  8515. return listByTags;
  8516. };
  8517. Scene.prototype.getMeshesByTags = function (tagsQuery) {
  8518. return this._getByTags(this.meshes, tagsQuery);
  8519. };
  8520. Scene.prototype.getCamerasByTags = function (tagsQuery) {
  8521. return this._getByTags(this.cameras, tagsQuery);
  8522. };
  8523. Scene.prototype.getLightsByTags = function (tagsQuery) {
  8524. return this._getByTags(this.lights, tagsQuery);
  8525. };
  8526. Scene.prototype.getMaterialByTags = function (tagsQuery) {
  8527. return this._getByTags(this.materials, tagsQuery).concat(this._getByTags(this.multiMaterials, tagsQuery));
  8528. };
  8529. // Statics
  8530. Scene.FOGMODE_NONE = 0;
  8531. Scene.FOGMODE_EXP = 1;
  8532. Scene.FOGMODE_EXP2 = 2;
  8533. Scene.FOGMODE_LINEAR = 3;
  8534. Scene.MinDeltaTime = 1.0;
  8535. Scene.MaxDeltaTime = 1000.0;
  8536. return Scene;
  8537. })();
  8538. BABYLON.Scene = Scene;
  8539. })(BABYLON || (BABYLON = {}));
  8540. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  8541. (function (BABYLON) {
  8542. var VertexBuffer = (function () {
  8543. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  8544. if (engine instanceof BABYLON.Mesh) {
  8545. this._engine = engine.getScene().getEngine();
  8546. }
  8547. else {
  8548. this._engine = engine;
  8549. }
  8550. this._updatable = updatable;
  8551. this._data = data;
  8552. if (!postponeInternalCreation) {
  8553. this.create();
  8554. }
  8555. this._kind = kind;
  8556. if (stride) {
  8557. this._strideSize = stride;
  8558. return;
  8559. }
  8560. switch (kind) {
  8561. case VertexBuffer.PositionKind:
  8562. this._strideSize = 3;
  8563. break;
  8564. case VertexBuffer.NormalKind:
  8565. this._strideSize = 3;
  8566. break;
  8567. case VertexBuffer.UVKind:
  8568. this._strideSize = 2;
  8569. break;
  8570. case VertexBuffer.UV2Kind:
  8571. this._strideSize = 2;
  8572. break;
  8573. case VertexBuffer.ColorKind:
  8574. this._strideSize = 4;
  8575. break;
  8576. case VertexBuffer.MatricesIndicesKind:
  8577. this._strideSize = 4;
  8578. break;
  8579. case VertexBuffer.MatricesWeightsKind:
  8580. this._strideSize = 4;
  8581. break;
  8582. }
  8583. }
  8584. // Properties
  8585. VertexBuffer.prototype.isUpdatable = function () {
  8586. return this._updatable;
  8587. };
  8588. VertexBuffer.prototype.getData = function () {
  8589. return this._data;
  8590. };
  8591. VertexBuffer.prototype.getBuffer = function () {
  8592. return this._buffer;
  8593. };
  8594. VertexBuffer.prototype.getStrideSize = function () {
  8595. return this._strideSize;
  8596. };
  8597. // Methods
  8598. VertexBuffer.prototype.create = function (data) {
  8599. if (!data && this._buffer) {
  8600. return; // nothing to do
  8601. }
  8602. data = data || this._data;
  8603. if (!this._buffer) {
  8604. if (this._updatable) {
  8605. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  8606. }
  8607. else {
  8608. this._buffer = this._engine.createVertexBuffer(data);
  8609. }
  8610. }
  8611. if (this._updatable) {
  8612. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  8613. this._data = data;
  8614. }
  8615. };
  8616. VertexBuffer.prototype.update = function (data) {
  8617. this.create(data);
  8618. };
  8619. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  8620. if (!this._buffer) {
  8621. return;
  8622. }
  8623. if (this._updatable) {
  8624. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  8625. this._data = null;
  8626. }
  8627. };
  8628. VertexBuffer.prototype.dispose = function () {
  8629. if (!this._buffer) {
  8630. return;
  8631. }
  8632. if (this._engine._releaseBuffer(this._buffer)) {
  8633. this._buffer = null;
  8634. }
  8635. };
  8636. Object.defineProperty(VertexBuffer, "PositionKind", {
  8637. get: function () {
  8638. return VertexBuffer._PositionKind;
  8639. },
  8640. enumerable: true,
  8641. configurable: true
  8642. });
  8643. Object.defineProperty(VertexBuffer, "NormalKind", {
  8644. get: function () {
  8645. return VertexBuffer._NormalKind;
  8646. },
  8647. enumerable: true,
  8648. configurable: true
  8649. });
  8650. Object.defineProperty(VertexBuffer, "UVKind", {
  8651. get: function () {
  8652. return VertexBuffer._UVKind;
  8653. },
  8654. enumerable: true,
  8655. configurable: true
  8656. });
  8657. Object.defineProperty(VertexBuffer, "UV2Kind", {
  8658. get: function () {
  8659. return VertexBuffer._UV2Kind;
  8660. },
  8661. enumerable: true,
  8662. configurable: true
  8663. });
  8664. Object.defineProperty(VertexBuffer, "ColorKind", {
  8665. get: function () {
  8666. return VertexBuffer._ColorKind;
  8667. },
  8668. enumerable: true,
  8669. configurable: true
  8670. });
  8671. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  8672. get: function () {
  8673. return VertexBuffer._MatricesIndicesKind;
  8674. },
  8675. enumerable: true,
  8676. configurable: true
  8677. });
  8678. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  8679. get: function () {
  8680. return VertexBuffer._MatricesWeightsKind;
  8681. },
  8682. enumerable: true,
  8683. configurable: true
  8684. });
  8685. // Enums
  8686. VertexBuffer._PositionKind = "position";
  8687. VertexBuffer._NormalKind = "normal";
  8688. VertexBuffer._UVKind = "uv";
  8689. VertexBuffer._UV2Kind = "uv2";
  8690. VertexBuffer._ColorKind = "color";
  8691. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  8692. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  8693. return VertexBuffer;
  8694. })();
  8695. BABYLON.VertexBuffer = VertexBuffer;
  8696. })(BABYLON || (BABYLON = {}));
  8697. //# sourceMappingURL=babylon.vertexBuffer.js.map
  8698. var BABYLON;
  8699. (function (BABYLON) {
  8700. var AbstractMesh = (function (_super) {
  8701. __extends(AbstractMesh, _super);
  8702. function AbstractMesh(name, scene) {
  8703. _super.call(this, name, scene);
  8704. // Properties
  8705. this.position = new BABYLON.Vector3(0, 0, 0);
  8706. this.rotation = new BABYLON.Vector3(0, 0, 0);
  8707. this.scaling = new BABYLON.Vector3(1, 1, 1);
  8708. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  8709. this.visibility = 1.0;
  8710. this.alphaIndex = Number.MAX_VALUE;
  8711. this.infiniteDistance = false;
  8712. this.isVisible = true;
  8713. this.isPickable = true;
  8714. this.showBoundingBox = false;
  8715. this.showSubMeshesBoundingBox = false;
  8716. this.onDispose = null;
  8717. this.checkCollisions = false;
  8718. this.isBlocker = false;
  8719. this.renderingGroupId = 0;
  8720. this.receiveShadows = false;
  8721. this.renderOutline = false;
  8722. this.outlineColor = BABYLON.Color3.Red();
  8723. this.outlineWidth = 0.02;
  8724. this.renderOverlay = false;
  8725. this.overlayColor = BABYLON.Color3.Red();
  8726. this.overlayAlpha = 0.5;
  8727. this.hasVertexAlpha = false;
  8728. this.useVertexColors = true;
  8729. this.applyFog = true;
  8730. this.useOctreeForRenderingSelection = true;
  8731. this.useOctreeForPicking = true;
  8732. this.useOctreeForCollisions = true;
  8733. this.layerMask = 0xFFFFFFFF;
  8734. // Physics
  8735. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  8736. // Collisions
  8737. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  8738. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  8739. this._collider = new BABYLON.Collider();
  8740. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8741. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8742. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  8743. // Cache
  8744. this._localScaling = BABYLON.Matrix.Zero();
  8745. this._localRotation = BABYLON.Matrix.Zero();
  8746. this._localTranslation = BABYLON.Matrix.Zero();
  8747. this._localBillboard = BABYLON.Matrix.Zero();
  8748. this._localPivotScaling = BABYLON.Matrix.Zero();
  8749. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  8750. this._localWorld = BABYLON.Matrix.Zero();
  8751. this._worldMatrix = BABYLON.Matrix.Zero();
  8752. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  8753. this._absolutePosition = BABYLON.Vector3.Zero();
  8754. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  8755. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  8756. this._isDirty = false;
  8757. this._pivotMatrix = BABYLON.Matrix.Identity();
  8758. this._isDisposed = false;
  8759. this._renderId = 0;
  8760. this._intersectionsInProgress = new Array();
  8761. this._onAfterWorldMatrixUpdate = new Array();
  8762. scene.meshes.push(this);
  8763. }
  8764. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  8765. get: function () {
  8766. return AbstractMesh._BILLBOARDMODE_NONE;
  8767. },
  8768. enumerable: true,
  8769. configurable: true
  8770. });
  8771. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  8772. get: function () {
  8773. return AbstractMesh._BILLBOARDMODE_X;
  8774. },
  8775. enumerable: true,
  8776. configurable: true
  8777. });
  8778. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  8779. get: function () {
  8780. return AbstractMesh._BILLBOARDMODE_Y;
  8781. },
  8782. enumerable: true,
  8783. configurable: true
  8784. });
  8785. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  8786. get: function () {
  8787. return AbstractMesh._BILLBOARDMODE_Z;
  8788. },
  8789. enumerable: true,
  8790. configurable: true
  8791. });
  8792. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  8793. get: function () {
  8794. return AbstractMesh._BILLBOARDMODE_ALL;
  8795. },
  8796. enumerable: true,
  8797. configurable: true
  8798. });
  8799. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  8800. // Methods
  8801. get: function () {
  8802. return false;
  8803. },
  8804. enumerable: true,
  8805. configurable: true
  8806. });
  8807. AbstractMesh.prototype.getLOD = function (camera) {
  8808. return this;
  8809. };
  8810. AbstractMesh.prototype.getTotalVertices = function () {
  8811. return 0;
  8812. };
  8813. AbstractMesh.prototype.getIndices = function () {
  8814. return null;
  8815. };
  8816. AbstractMesh.prototype.getVerticesData = function (kind) {
  8817. return null;
  8818. };
  8819. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  8820. return false;
  8821. };
  8822. AbstractMesh.prototype.getBoundingInfo = function () {
  8823. if (this._masterMesh) {
  8824. return this._masterMesh.getBoundingInfo();
  8825. }
  8826. if (!this._boundingInfo) {
  8827. this._updateBoundingInfo();
  8828. }
  8829. return this._boundingInfo;
  8830. };
  8831. AbstractMesh.prototype._preActivate = function () {
  8832. };
  8833. AbstractMesh.prototype._activate = function (renderId) {
  8834. this._renderId = renderId;
  8835. };
  8836. AbstractMesh.prototype.getWorldMatrix = function () {
  8837. if (this._masterMesh) {
  8838. return this._masterMesh.getWorldMatrix();
  8839. }
  8840. if (this._currentRenderId !== this.getScene().getRenderId()) {
  8841. this.computeWorldMatrix();
  8842. }
  8843. return this._worldMatrix;
  8844. };
  8845. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  8846. get: function () {
  8847. return this._worldMatrix;
  8848. },
  8849. enumerable: true,
  8850. configurable: true
  8851. });
  8852. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  8853. get: function () {
  8854. return this._absolutePosition;
  8855. },
  8856. enumerable: true,
  8857. configurable: true
  8858. });
  8859. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  8860. if (!this.rotationQuaternion) {
  8861. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  8862. this.rotation = BABYLON.Vector3.Zero();
  8863. }
  8864. if (!space || space == 0 /* LOCAL */) {
  8865. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8866. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  8867. }
  8868. else {
  8869. if (this.parent) {
  8870. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8871. invertParentWorldMatrix.invert();
  8872. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  8873. }
  8874. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  8875. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  8876. }
  8877. };
  8878. AbstractMesh.prototype.translate = function (axis, distance, space) {
  8879. var displacementVector = axis.scale(distance);
  8880. if (!space || space == 0 /* LOCAL */) {
  8881. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  8882. this.setPositionWithLocalVector(tempV3);
  8883. }
  8884. else {
  8885. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  8886. }
  8887. };
  8888. AbstractMesh.prototype.getAbsolutePosition = function () {
  8889. this.computeWorldMatrix();
  8890. return this._absolutePosition;
  8891. };
  8892. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  8893. if (!absolutePosition) {
  8894. return;
  8895. }
  8896. var absolutePositionX;
  8897. var absolutePositionY;
  8898. var absolutePositionZ;
  8899. if (absolutePosition.x === undefined) {
  8900. if (arguments.length < 3) {
  8901. return;
  8902. }
  8903. absolutePositionX = arguments[0];
  8904. absolutePositionY = arguments[1];
  8905. absolutePositionZ = arguments[2];
  8906. }
  8907. else {
  8908. absolutePositionX = absolutePosition.x;
  8909. absolutePositionY = absolutePosition.y;
  8910. absolutePositionZ = absolutePosition.z;
  8911. }
  8912. if (this.parent) {
  8913. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  8914. invertParentWorldMatrix.invert();
  8915. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  8916. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  8917. }
  8918. else {
  8919. this.position.x = absolutePositionX;
  8920. this.position.y = absolutePositionY;
  8921. this.position.z = absolutePositionZ;
  8922. }
  8923. };
  8924. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  8925. this._pivotMatrix = matrix;
  8926. this._cache.pivotMatrixUpdated = true;
  8927. };
  8928. AbstractMesh.prototype.getPivotMatrix = function () {
  8929. return this._pivotMatrix;
  8930. };
  8931. AbstractMesh.prototype._isSynchronized = function () {
  8932. if (this._isDirty) {
  8933. return false;
  8934. }
  8935. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  8936. return false;
  8937. if (this._cache.pivotMatrixUpdated) {
  8938. return false;
  8939. }
  8940. if (this.infiniteDistance) {
  8941. return false;
  8942. }
  8943. if (!this._cache.position.equals(this.position))
  8944. return false;
  8945. if (this.rotationQuaternion) {
  8946. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  8947. return false;
  8948. }
  8949. else {
  8950. if (!this._cache.rotation.equals(this.rotation))
  8951. return false;
  8952. }
  8953. if (!this._cache.scaling.equals(this.scaling))
  8954. return false;
  8955. return true;
  8956. };
  8957. AbstractMesh.prototype._initCache = function () {
  8958. _super.prototype._initCache.call(this);
  8959. this._cache.localMatrixUpdated = false;
  8960. this._cache.position = BABYLON.Vector3.Zero();
  8961. this._cache.scaling = BABYLON.Vector3.Zero();
  8962. this._cache.rotation = BABYLON.Vector3.Zero();
  8963. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  8964. };
  8965. AbstractMesh.prototype.markAsDirty = function (property) {
  8966. if (property === "rotation") {
  8967. this.rotationQuaternion = null;
  8968. }
  8969. this._currentRenderId = Number.MAX_VALUE;
  8970. this._isDirty = true;
  8971. };
  8972. AbstractMesh.prototype._updateBoundingInfo = function () {
  8973. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  8974. this._boundingInfo._update(this.worldMatrixFromCache);
  8975. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  8976. };
  8977. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  8978. if (!this.subMeshes) {
  8979. return;
  8980. }
  8981. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  8982. var subMesh = this.subMeshes[subIndex];
  8983. subMesh.updateBoundingInfo(matrix);
  8984. }
  8985. };
  8986. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  8987. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  8988. return this._worldMatrix;
  8989. }
  8990. this._cache.position.copyFrom(this.position);
  8991. this._cache.scaling.copyFrom(this.scaling);
  8992. this._cache.pivotMatrixUpdated = false;
  8993. this._currentRenderId = this.getScene().getRenderId();
  8994. this._isDirty = false;
  8995. // Scaling
  8996. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  8997. // Rotation
  8998. if (this.rotationQuaternion) {
  8999. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9000. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9001. }
  9002. else {
  9003. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9004. this._cache.rotation.copyFrom(this.rotation);
  9005. }
  9006. // Translation
  9007. if (this.infiniteDistance && !this.parent) {
  9008. var camera = this.getScene().activeCamera;
  9009. var cameraWorldMatrix = camera.getWorldMatrix();
  9010. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9011. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9012. }
  9013. else {
  9014. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9015. }
  9016. // Composing transformations
  9017. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9018. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9019. // Billboarding
  9020. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9021. var localPosition = this.position.clone();
  9022. var zero = this.getScene().activeCamera.position.clone();
  9023. if (this.parent && this.parent.position) {
  9024. localPosition.addInPlace(this.parent.position);
  9025. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9026. }
  9027. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9028. zero = this.getScene().activeCamera.position;
  9029. }
  9030. else {
  9031. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9032. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9033. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9034. zero.y = localPosition.y + 0.001;
  9035. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9036. zero.z = localPosition.z + 0.001;
  9037. }
  9038. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9039. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9040. this._localBillboard.invert();
  9041. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9042. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9043. }
  9044. // Local world
  9045. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9046. // Parent
  9047. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9048. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9049. }
  9050. else {
  9051. this._worldMatrix.copyFrom(this._localWorld);
  9052. }
  9053. // Bounding info
  9054. this._updateBoundingInfo();
  9055. // Absolute position
  9056. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9057. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9058. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9059. }
  9060. return this._worldMatrix;
  9061. };
  9062. /**
  9063. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9064. * @param func: callback function to add
  9065. */
  9066. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9067. this._onAfterWorldMatrixUpdate.push(func);
  9068. };
  9069. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9070. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9071. if (index > -1) {
  9072. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9073. }
  9074. };
  9075. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9076. this.computeWorldMatrix();
  9077. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9078. };
  9079. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9080. this.computeWorldMatrix();
  9081. var invLocalWorldMatrix = this._localWorld.clone();
  9082. invLocalWorldMatrix.invert();
  9083. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9084. };
  9085. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9086. this.computeWorldMatrix();
  9087. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9088. };
  9089. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9090. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9091. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9092. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9093. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9094. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9095. /// <returns>Mesh oriented towards targetMesh</returns>
  9096. yawCor = yawCor || 0; // default to zero if undefined
  9097. pitchCor = pitchCor || 0;
  9098. rollCor = rollCor || 0;
  9099. var dv = targetPoint.subtract(this.position);
  9100. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9101. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9102. var pitch = Math.atan2(dv.y, len);
  9103. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9104. };
  9105. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9106. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9107. return false;
  9108. }
  9109. return true;
  9110. };
  9111. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9112. if (!camera) {
  9113. camera = this.getScene().activeCamera;
  9114. }
  9115. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9116. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9117. return false;
  9118. }
  9119. return true;
  9120. };
  9121. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9122. if (!this._boundingInfo || !mesh._boundingInfo) {
  9123. return false;
  9124. }
  9125. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9126. };
  9127. AbstractMesh.prototype.intersectsPoint = function (point) {
  9128. if (!this._boundingInfo) {
  9129. return false;
  9130. }
  9131. return this._boundingInfo.intersectsPoint(point);
  9132. };
  9133. // Physics
  9134. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9135. var physicsEngine = this.getScene().getPhysicsEngine();
  9136. if (!physicsEngine) {
  9137. return;
  9138. }
  9139. if (impostor.impostor) {
  9140. // Old API
  9141. options = impostor;
  9142. impostor = impostor.impostor;
  9143. }
  9144. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9145. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9146. physicsEngine._unregisterMesh(this);
  9147. return;
  9148. }
  9149. options.mass = options.mass || 0;
  9150. options.friction = options.friction || 0.2;
  9151. options.restitution = options.restitution || 0.2;
  9152. this._physicImpostor = impostor;
  9153. this._physicsMass = options.mass;
  9154. this._physicsFriction = options.friction;
  9155. this._physicRestitution = options.restitution;
  9156. return physicsEngine._registerMesh(this, impostor, options);
  9157. };
  9158. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9159. if (!this._physicImpostor) {
  9160. return BABYLON.PhysicsEngine.NoImpostor;
  9161. }
  9162. return this._physicImpostor;
  9163. };
  9164. AbstractMesh.prototype.getPhysicsMass = function () {
  9165. if (!this._physicsMass) {
  9166. return 0;
  9167. }
  9168. return this._physicsMass;
  9169. };
  9170. AbstractMesh.prototype.getPhysicsFriction = function () {
  9171. if (!this._physicsFriction) {
  9172. return 0;
  9173. }
  9174. return this._physicsFriction;
  9175. };
  9176. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9177. if (!this._physicRestitution) {
  9178. return 0;
  9179. }
  9180. return this._physicRestitution;
  9181. };
  9182. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9183. if (!camera) {
  9184. camera = this.getScene().activeCamera;
  9185. }
  9186. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9187. };
  9188. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9189. if (!camera) {
  9190. camera = this.getScene().activeCamera;
  9191. }
  9192. return this.absolutePosition.subtract(camera.position).length();
  9193. };
  9194. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9195. if (!this._physicImpostor) {
  9196. return;
  9197. }
  9198. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9199. };
  9200. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9201. if (!this._physicImpostor) {
  9202. return;
  9203. }
  9204. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9205. };
  9206. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9207. if (!this._physicImpostor) {
  9208. return;
  9209. }
  9210. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9211. };
  9212. // Collisions
  9213. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  9214. var globalPosition = this.getAbsolutePosition();
  9215. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  9216. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  9217. this._collider.radius = this.ellipsoid;
  9218. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  9219. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  9220. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  9221. this.position.addInPlace(this._diffPositionForCollisions);
  9222. }
  9223. };
  9224. // Submeshes octree
  9225. /**
  9226. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  9227. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  9228. */
  9229. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  9230. if (maxCapacity === void 0) { maxCapacity = 64; }
  9231. if (maxDepth === void 0) { maxDepth = 2; }
  9232. if (!this._submeshesOctree) {
  9233. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  9234. }
  9235. this.computeWorldMatrix(true);
  9236. // Update octree
  9237. var bbox = this.getBoundingInfo().boundingBox;
  9238. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  9239. return this._submeshesOctree;
  9240. };
  9241. // Collisions
  9242. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  9243. this._generatePointsArray();
  9244. // Transformation
  9245. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  9246. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  9247. subMesh._lastColliderWorldVertices = [];
  9248. subMesh._trianglePlanes = [];
  9249. var start = subMesh.verticesStart;
  9250. var end = (subMesh.verticesStart + subMesh.verticesCount);
  9251. for (var i = start; i < end; i++) {
  9252. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  9253. }
  9254. }
  9255. // Collide
  9256. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  9257. };
  9258. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  9259. var subMeshes;
  9260. var len;
  9261. // Octrees
  9262. if (this._submeshesOctree && this.useOctreeForCollisions) {
  9263. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  9264. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  9265. len = intersections.length;
  9266. subMeshes = intersections.data;
  9267. }
  9268. else {
  9269. subMeshes = this.subMeshes;
  9270. len = subMeshes.length;
  9271. }
  9272. for (var index = 0; index < len; index++) {
  9273. var subMesh = subMeshes[index];
  9274. // Bounding test
  9275. if (len > 1 && !subMesh._checkCollision(collider))
  9276. continue;
  9277. this._collideForSubMesh(subMesh, transformMatrix, collider);
  9278. }
  9279. };
  9280. AbstractMesh.prototype._checkCollision = function (collider) {
  9281. // Bounding box test
  9282. if (!this._boundingInfo._checkCollision(collider))
  9283. return;
  9284. // Transformation matrix
  9285. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  9286. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  9287. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  9288. };
  9289. // Picking
  9290. AbstractMesh.prototype._generatePointsArray = function () {
  9291. return false;
  9292. };
  9293. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  9294. var pickingInfo = new BABYLON.PickingInfo();
  9295. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  9296. return pickingInfo;
  9297. }
  9298. if (!this._generatePointsArray()) {
  9299. return pickingInfo;
  9300. }
  9301. var intersectInfo = null;
  9302. // Octrees
  9303. var subMeshes;
  9304. var len;
  9305. if (this._submeshesOctree && this.useOctreeForPicking) {
  9306. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  9307. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  9308. len = intersections.length;
  9309. subMeshes = intersections.data;
  9310. }
  9311. else {
  9312. subMeshes = this.subMeshes;
  9313. len = subMeshes.length;
  9314. }
  9315. for (var index = 0; index < len; index++) {
  9316. var subMesh = subMeshes[index];
  9317. // Bounding test
  9318. if (len > 1 && !subMesh.canIntersects(ray))
  9319. continue;
  9320. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  9321. if (currentIntersectInfo) {
  9322. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  9323. intersectInfo = currentIntersectInfo;
  9324. if (fastCheck) {
  9325. break;
  9326. }
  9327. }
  9328. }
  9329. }
  9330. if (intersectInfo) {
  9331. // Get picked point
  9332. var world = this.getWorldMatrix();
  9333. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  9334. var direction = ray.direction.clone();
  9335. direction.normalize();
  9336. direction = direction.scale(intersectInfo.distance);
  9337. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  9338. var pickedPoint = worldOrigin.add(worldDirection);
  9339. // Return result
  9340. pickingInfo.hit = true;
  9341. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  9342. pickingInfo.pickedPoint = pickedPoint;
  9343. pickingInfo.pickedMesh = this;
  9344. pickingInfo.bu = intersectInfo.bu;
  9345. pickingInfo.bv = intersectInfo.bv;
  9346. pickingInfo.faceId = intersectInfo.faceId;
  9347. return pickingInfo;
  9348. }
  9349. return pickingInfo;
  9350. };
  9351. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  9352. return null;
  9353. };
  9354. AbstractMesh.prototype.releaseSubMeshes = function () {
  9355. if (this.subMeshes) {
  9356. while (this.subMeshes.length) {
  9357. this.subMeshes[0].dispose();
  9358. }
  9359. }
  9360. else {
  9361. this.subMeshes = new Array();
  9362. }
  9363. };
  9364. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  9365. // Physics
  9366. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  9367. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  9368. }
  9369. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  9370. var other = this._intersectionsInProgress[index];
  9371. var pos = other._intersectionsInProgress.indexOf(this);
  9372. other._intersectionsInProgress.splice(pos, 1);
  9373. }
  9374. this._intersectionsInProgress = [];
  9375. // SubMeshes
  9376. this.releaseSubMeshes();
  9377. // Remove from scene
  9378. var index = this.getScene().meshes.indexOf(this);
  9379. if (index != -1) {
  9380. // Remove from the scene if mesh found
  9381. this.getScene().meshes.splice(index, 1);
  9382. }
  9383. if (!doNotRecurse) {
  9384. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  9385. if (this.getScene().particleSystems[index].emitter == this) {
  9386. this.getScene().particleSystems[index].dispose();
  9387. index--;
  9388. }
  9389. }
  9390. // Children
  9391. var objects = this.getScene().meshes.slice(0);
  9392. for (index = 0; index < objects.length; index++) {
  9393. if (objects[index].parent == this) {
  9394. objects[index].dispose();
  9395. }
  9396. }
  9397. }
  9398. else {
  9399. for (index = 0; index < this.getScene().meshes.length; index++) {
  9400. var obj = this.getScene().meshes[index];
  9401. if (obj.parent === this) {
  9402. obj.parent = null;
  9403. obj.computeWorldMatrix(true);
  9404. }
  9405. }
  9406. }
  9407. this._onAfterWorldMatrixUpdate = [];
  9408. this._isDisposed = true;
  9409. // Callback
  9410. if (this.onDispose) {
  9411. this.onDispose();
  9412. }
  9413. };
  9414. // Statics
  9415. AbstractMesh._BILLBOARDMODE_NONE = 0;
  9416. AbstractMesh._BILLBOARDMODE_X = 1;
  9417. AbstractMesh._BILLBOARDMODE_Y = 2;
  9418. AbstractMesh._BILLBOARDMODE_Z = 4;
  9419. AbstractMesh._BILLBOARDMODE_ALL = 7;
  9420. return AbstractMesh;
  9421. })(BABYLON.Node);
  9422. BABYLON.AbstractMesh = AbstractMesh;
  9423. })(BABYLON || (BABYLON = {}));
  9424. //# sourceMappingURL=babylon.abstractMesh.js.map
  9425. var BABYLON;
  9426. (function (BABYLON) {
  9427. var _InstancesBatch = (function () {
  9428. function _InstancesBatch() {
  9429. this.mustReturn = false;
  9430. this.visibleInstances = new Array();
  9431. this.renderSelf = new Array();
  9432. }
  9433. return _InstancesBatch;
  9434. })();
  9435. BABYLON._InstancesBatch = _InstancesBatch;
  9436. var Mesh = (function (_super) {
  9437. __extends(Mesh, _super);
  9438. /**
  9439. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  9440. * @param {Scene} scene - The scene to add this mesh to.
  9441. * @param {Node} parent - The parent of this mesh, if it has one
  9442. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  9443. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  9444. * When false, achieved by calling a clone(), also passing False.
  9445. * This will make creation of children, recursive.
  9446. */
  9447. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  9448. if (parent === void 0) { parent = null; }
  9449. _super.call(this, name, scene);
  9450. // Members
  9451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  9452. this.instances = new Array();
  9453. this._LODLevels = new Array();
  9454. this._onBeforeRenderCallbacks = new Array();
  9455. this._onAfterRenderCallbacks = new Array();
  9456. this._visibleInstances = {};
  9457. this._renderIdForInstances = new Array();
  9458. this._batchCache = new _InstancesBatch();
  9459. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  9460. if (source) {
  9461. // Geometry
  9462. if (source._geometry) {
  9463. source._geometry.applyToMesh(this);
  9464. }
  9465. // Deep copy
  9466. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  9467. // Material
  9468. this.material = source.material;
  9469. if (!doNotCloneChildren) {
  9470. for (var index = 0; index < scene.meshes.length; index++) {
  9471. var mesh = scene.meshes[index];
  9472. if (mesh.parent === source) {
  9473. // doNotCloneChildren is always going to be False
  9474. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  9475. }
  9476. }
  9477. }
  9478. for (index = 0; index < scene.particleSystems.length; index++) {
  9479. var system = scene.particleSystems[index];
  9480. if (system.emitter === source) {
  9481. system.clone(system.name, this);
  9482. }
  9483. }
  9484. this.computeWorldMatrix(true);
  9485. }
  9486. // Parent
  9487. if (parent !== null) {
  9488. this.parent = parent;
  9489. }
  9490. }
  9491. Mesh.prototype._clone = function () {
  9492. };
  9493. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  9494. // Methods
  9495. get: function () {
  9496. return this._LODLevels.length > 0;
  9497. },
  9498. enumerable: true,
  9499. configurable: true
  9500. });
  9501. Mesh.prototype._sortLODLevels = function () {
  9502. this._LODLevels.sort(function (a, b) {
  9503. if (a.distance < b.distance) {
  9504. return 1;
  9505. }
  9506. if (a.distance > b.distance) {
  9507. return -1;
  9508. }
  9509. return 0;
  9510. });
  9511. };
  9512. Mesh.prototype.addLODLevel = function (distance, mesh) {
  9513. if (mesh && mesh._masterMesh) {
  9514. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  9515. return this;
  9516. }
  9517. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  9518. this._LODLevels.push(level);
  9519. if (mesh) {
  9520. mesh._masterMesh = this;
  9521. }
  9522. this._sortLODLevels();
  9523. return this;
  9524. };
  9525. Mesh.prototype.removeLODLevel = function (mesh) {
  9526. for (var index = 0; index < this._LODLevels.length; index++) {
  9527. if (this._LODLevels[index].mesh === mesh) {
  9528. this._LODLevels.splice(index, 1);
  9529. if (mesh) {
  9530. mesh._masterMesh = null;
  9531. }
  9532. }
  9533. }
  9534. this._sortLODLevels();
  9535. return this;
  9536. };
  9537. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  9538. if (!this._LODLevels || this._LODLevels.length === 0) {
  9539. return this;
  9540. }
  9541. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  9542. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  9543. return this;
  9544. }
  9545. for (var index = 0; index < this._LODLevels.length; index++) {
  9546. var level = this._LODLevels[index];
  9547. if (level.distance < distanceToCamera) {
  9548. if (level.mesh) {
  9549. level.mesh._preActivate();
  9550. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9551. }
  9552. return level.mesh;
  9553. }
  9554. }
  9555. return this;
  9556. };
  9557. Object.defineProperty(Mesh.prototype, "geometry", {
  9558. get: function () {
  9559. return this._geometry;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Mesh.prototype.getTotalVertices = function () {
  9565. if (!this._geometry) {
  9566. return 0;
  9567. }
  9568. return this._geometry.getTotalVertices();
  9569. };
  9570. Mesh.prototype.getVerticesData = function (kind) {
  9571. if (!this._geometry) {
  9572. return null;
  9573. }
  9574. return this._geometry.getVerticesData(kind);
  9575. };
  9576. Mesh.prototype.getVertexBuffer = function (kind) {
  9577. if (!this._geometry) {
  9578. return undefined;
  9579. }
  9580. return this._geometry.getVertexBuffer(kind);
  9581. };
  9582. Mesh.prototype.isVerticesDataPresent = function (kind) {
  9583. if (!this._geometry) {
  9584. if (this._delayInfo) {
  9585. return this._delayInfo.indexOf(kind) !== -1;
  9586. }
  9587. return false;
  9588. }
  9589. return this._geometry.isVerticesDataPresent(kind);
  9590. };
  9591. Mesh.prototype.getVerticesDataKinds = function () {
  9592. if (!this._geometry) {
  9593. var result = [];
  9594. if (this._delayInfo) {
  9595. for (var kind in this._delayInfo) {
  9596. result.push(kind);
  9597. }
  9598. }
  9599. return result;
  9600. }
  9601. return this._geometry.getVerticesDataKinds();
  9602. };
  9603. Mesh.prototype.getTotalIndices = function () {
  9604. if (!this._geometry) {
  9605. return 0;
  9606. }
  9607. return this._geometry.getTotalIndices();
  9608. };
  9609. Mesh.prototype.getIndices = function () {
  9610. if (!this._geometry) {
  9611. return [];
  9612. }
  9613. return this._geometry.getIndices();
  9614. };
  9615. Object.defineProperty(Mesh.prototype, "isBlocked", {
  9616. get: function () {
  9617. return this._masterMesh !== null && this._masterMesh !== undefined;
  9618. },
  9619. enumerable: true,
  9620. configurable: true
  9621. });
  9622. Mesh.prototype.isReady = function () {
  9623. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  9624. return false;
  9625. }
  9626. return _super.prototype.isReady.call(this);
  9627. };
  9628. Mesh.prototype.isDisposed = function () {
  9629. return this._isDisposed;
  9630. };
  9631. // Methods
  9632. Mesh.prototype._preActivate = function () {
  9633. var sceneRenderId = this.getScene().getRenderId();
  9634. if (this._preActivateId == sceneRenderId) {
  9635. return;
  9636. }
  9637. this._preActivateId = sceneRenderId;
  9638. this._visibleInstances = null;
  9639. };
  9640. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  9641. if (!this._visibleInstances) {
  9642. this._visibleInstances = {};
  9643. this._visibleInstances.defaultRenderId = renderId;
  9644. this._visibleInstances.selfDefaultRenderId = this._renderId;
  9645. }
  9646. if (!this._visibleInstances[renderId]) {
  9647. this._visibleInstances[renderId] = new Array();
  9648. }
  9649. this._visibleInstances[renderId].push(instance);
  9650. };
  9651. Mesh.prototype.refreshBoundingInfo = function () {
  9652. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9653. if (data) {
  9654. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  9655. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  9656. }
  9657. if (this.subMeshes) {
  9658. for (var index = 0; index < this.subMeshes.length; index++) {
  9659. this.subMeshes[index].refreshBoundingInfo();
  9660. }
  9661. }
  9662. this._updateBoundingInfo();
  9663. };
  9664. Mesh.prototype._createGlobalSubMesh = function () {
  9665. var totalVertices = this.getTotalVertices();
  9666. if (!totalVertices || !this.getIndices()) {
  9667. return null;
  9668. }
  9669. this.releaseSubMeshes();
  9670. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  9671. };
  9672. Mesh.prototype.subdivide = function (count) {
  9673. if (count < 1) {
  9674. return;
  9675. }
  9676. var totalIndices = this.getTotalIndices();
  9677. var subdivisionSize = (totalIndices / count) | 0;
  9678. var offset = 0;
  9679. while (subdivisionSize % 3 != 0) {
  9680. subdivisionSize++;
  9681. }
  9682. this.releaseSubMeshes();
  9683. for (var index = 0; index < count; index++) {
  9684. if (offset >= totalIndices) {
  9685. break;
  9686. }
  9687. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  9688. offset += subdivisionSize;
  9689. }
  9690. this.synchronizeInstances();
  9691. };
  9692. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  9693. if (kind instanceof Array) {
  9694. var temp = data;
  9695. data = kind;
  9696. kind = temp;
  9697. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  9698. }
  9699. if (!this._geometry) {
  9700. var vertexData = new BABYLON.VertexData();
  9701. vertexData.set(data, kind);
  9702. var scene = this.getScene();
  9703. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  9704. }
  9705. else {
  9706. this._geometry.setVerticesData(kind, data, updatable, stride);
  9707. }
  9708. };
  9709. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  9710. if (!this._geometry) {
  9711. return;
  9712. }
  9713. if (!makeItUnique) {
  9714. this._geometry.updateVerticesData(kind, data, updateExtends);
  9715. }
  9716. else {
  9717. this.makeGeometryUnique();
  9718. this.updateVerticesData(kind, data, updateExtends, false);
  9719. }
  9720. };
  9721. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  9722. if (!this._geometry) {
  9723. return;
  9724. }
  9725. if (!makeItUnique) {
  9726. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  9727. }
  9728. else {
  9729. this.makeGeometryUnique();
  9730. this.updateVerticesDataDirectly(kind, data, offset, false);
  9731. }
  9732. };
  9733. Mesh.prototype.makeGeometryUnique = function () {
  9734. if (!this._geometry) {
  9735. return;
  9736. }
  9737. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  9738. geometry.applyToMesh(this);
  9739. };
  9740. Mesh.prototype.setIndices = function (indices, totalVertices) {
  9741. if (!this._geometry) {
  9742. var vertexData = new BABYLON.VertexData();
  9743. vertexData.indices = indices;
  9744. var scene = this.getScene();
  9745. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  9746. }
  9747. else {
  9748. this._geometry.setIndices(indices, totalVertices);
  9749. }
  9750. };
  9751. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  9752. var engine = this.getScene().getEngine();
  9753. // Wireframe
  9754. var indexToBind;
  9755. switch (fillMode) {
  9756. case BABYLON.Material.PointFillMode:
  9757. indexToBind = null;
  9758. break;
  9759. case BABYLON.Material.WireFrameFillMode:
  9760. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  9761. break;
  9762. default:
  9763. case BABYLON.Material.TriangleFillMode:
  9764. indexToBind = this._geometry.getIndexBuffer();
  9765. break;
  9766. }
  9767. // VBOs
  9768. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  9769. };
  9770. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  9771. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9772. return;
  9773. }
  9774. var engine = this.getScene().getEngine();
  9775. switch (fillMode) {
  9776. case BABYLON.Material.PointFillMode:
  9777. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  9778. break;
  9779. case BABYLON.Material.WireFrameFillMode:
  9780. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  9781. break;
  9782. default:
  9783. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  9784. }
  9785. };
  9786. Mesh.prototype.registerBeforeRender = function (func) {
  9787. this._onBeforeRenderCallbacks.push(func);
  9788. };
  9789. Mesh.prototype.unregisterBeforeRender = function (func) {
  9790. var index = this._onBeforeRenderCallbacks.indexOf(func);
  9791. if (index > -1) {
  9792. this._onBeforeRenderCallbacks.splice(index, 1);
  9793. }
  9794. };
  9795. Mesh.prototype.registerAfterRender = function (func) {
  9796. this._onAfterRenderCallbacks.push(func);
  9797. };
  9798. Mesh.prototype.unregisterAfterRender = function (func) {
  9799. var index = this._onAfterRenderCallbacks.indexOf(func);
  9800. if (index > -1) {
  9801. this._onAfterRenderCallbacks.splice(index, 1);
  9802. }
  9803. };
  9804. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  9805. var scene = this.getScene();
  9806. this._batchCache.mustReturn = false;
  9807. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  9808. this._batchCache.visibleInstances[subMeshId] = null;
  9809. if (this._visibleInstances) {
  9810. var currentRenderId = scene.getRenderId();
  9811. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  9812. var selfRenderId = this._renderId;
  9813. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  9814. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  9815. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  9816. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  9817. }
  9818. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  9819. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  9820. this._batchCache.mustReturn = true;
  9821. return this._batchCache;
  9822. }
  9823. if (currentRenderId !== selfRenderId) {
  9824. this._batchCache.renderSelf[subMeshId] = false;
  9825. }
  9826. }
  9827. this._renderIdForInstances[subMeshId] = currentRenderId;
  9828. }
  9829. return this._batchCache;
  9830. };
  9831. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  9832. var visibleInstances = batch.visibleInstances[subMesh._id];
  9833. var matricesCount = visibleInstances.length + 1;
  9834. var bufferSize = matricesCount * 16 * 4;
  9835. while (this._instancesBufferSize < bufferSize) {
  9836. this._instancesBufferSize *= 2;
  9837. }
  9838. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  9839. if (this._worldMatricesInstancesBuffer) {
  9840. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  9841. }
  9842. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  9843. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  9844. }
  9845. var offset = 0;
  9846. var instancesCount = 0;
  9847. var world = this.getWorldMatrix();
  9848. if (batch.renderSelf[subMesh._id]) {
  9849. world.copyToArray(this._worldMatricesInstancesArray, offset);
  9850. offset += 16;
  9851. instancesCount++;
  9852. }
  9853. if (visibleInstances) {
  9854. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  9855. var instance = visibleInstances[instanceIndex];
  9856. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  9857. offset += 16;
  9858. instancesCount++;
  9859. }
  9860. }
  9861. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  9862. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  9863. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  9864. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  9865. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  9866. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  9867. this._draw(subMesh, fillMode, instancesCount);
  9868. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  9869. };
  9870. Mesh.prototype.render = function (subMesh) {
  9871. var scene = this.getScene();
  9872. // Managing instances
  9873. var batch = this._getInstancesRenderList(subMesh._id);
  9874. if (batch.mustReturn) {
  9875. return;
  9876. }
  9877. // Checking geometry state
  9878. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  9879. return;
  9880. }
  9881. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9882. this._onBeforeRenderCallbacks[callbackIndex]();
  9883. }
  9884. var engine = scene.getEngine();
  9885. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  9886. // Material
  9887. var effectiveMaterial = subMesh.getMaterial();
  9888. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  9889. return;
  9890. }
  9891. // Outline - step 1
  9892. var savedDepthWrite = engine.getDepthWrite();
  9893. if (this.renderOutline) {
  9894. engine.setDepthWrite(false);
  9895. scene.getOutlineRenderer().render(subMesh, batch);
  9896. engine.setDepthWrite(savedDepthWrite);
  9897. }
  9898. effectiveMaterial._preBind();
  9899. var effect = effectiveMaterial.getEffect();
  9900. // Bind
  9901. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  9902. this._bind(subMesh, effect, fillMode);
  9903. var world = this.getWorldMatrix();
  9904. effectiveMaterial.bind(world, this);
  9905. // Instances rendering
  9906. if (hardwareInstancedRendering) {
  9907. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  9908. }
  9909. else {
  9910. if (batch.renderSelf[subMesh._id]) {
  9911. // Draw
  9912. this._draw(subMesh, fillMode);
  9913. }
  9914. if (batch.visibleInstances[subMesh._id]) {
  9915. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  9916. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  9917. // World
  9918. world = instance.getWorldMatrix();
  9919. effectiveMaterial.bindOnlyWorldMatrix(world);
  9920. // Draw
  9921. this._draw(subMesh, fillMode);
  9922. }
  9923. }
  9924. }
  9925. // Unbind
  9926. effectiveMaterial.unbind();
  9927. // Outline - step 2
  9928. if (this.renderOutline && savedDepthWrite) {
  9929. engine.setDepthWrite(true);
  9930. engine.setColorWrite(false);
  9931. scene.getOutlineRenderer().render(subMesh, batch);
  9932. engine.setColorWrite(true);
  9933. }
  9934. // Overlay
  9935. if (this.renderOverlay) {
  9936. var currentMode = engine.getAlphaMode();
  9937. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  9938. scene.getOutlineRenderer().render(subMesh, batch, true);
  9939. engine.setAlphaMode(currentMode);
  9940. }
  9941. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9942. this._onAfterRenderCallbacks[callbackIndex]();
  9943. }
  9944. };
  9945. Mesh.prototype.getEmittedParticleSystems = function () {
  9946. var results = new Array();
  9947. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9948. var particleSystem = this.getScene().particleSystems[index];
  9949. if (particleSystem.emitter === this) {
  9950. results.push(particleSystem);
  9951. }
  9952. }
  9953. return results;
  9954. };
  9955. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  9956. var results = new Array();
  9957. var descendants = this.getDescendants();
  9958. descendants.push(this);
  9959. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  9960. var particleSystem = this.getScene().particleSystems[index];
  9961. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  9962. results.push(particleSystem);
  9963. }
  9964. }
  9965. return results;
  9966. };
  9967. Mesh.prototype.getChildren = function () {
  9968. var results = [];
  9969. for (var index = 0; index < this.getScene().meshes.length; index++) {
  9970. var mesh = this.getScene().meshes[index];
  9971. if (mesh.parent == this) {
  9972. results.push(mesh);
  9973. }
  9974. }
  9975. return results;
  9976. };
  9977. Mesh.prototype._checkDelayState = function () {
  9978. var _this = this;
  9979. var that = this;
  9980. var scene = this.getScene();
  9981. if (this._geometry) {
  9982. this._geometry.load(scene);
  9983. }
  9984. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  9985. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  9986. scene._addPendingData(that);
  9987. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  9988. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  9989. if (data instanceof ArrayBuffer) {
  9990. _this._delayLoadingFunction(data, _this);
  9991. }
  9992. else {
  9993. _this._delayLoadingFunction(JSON.parse(data), _this);
  9994. }
  9995. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  9996. scene._removePendingData(_this);
  9997. }, function () {
  9998. }, scene.database, getBinaryData);
  9999. }
  10000. };
  10001. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10002. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10003. return false;
  10004. }
  10005. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10006. return false;
  10007. }
  10008. this._checkDelayState();
  10009. return true;
  10010. };
  10011. Mesh.prototype.setMaterialByID = function (id) {
  10012. var materials = this.getScene().materials;
  10013. for (var index = 0; index < materials.length; index++) {
  10014. if (materials[index].id == id) {
  10015. this.material = materials[index];
  10016. return;
  10017. }
  10018. }
  10019. // Multi
  10020. var multiMaterials = this.getScene().multiMaterials;
  10021. for (index = 0; index < multiMaterials.length; index++) {
  10022. if (multiMaterials[index].id == id) {
  10023. this.material = multiMaterials[index];
  10024. return;
  10025. }
  10026. }
  10027. };
  10028. Mesh.prototype.getAnimatables = function () {
  10029. var results = [];
  10030. if (this.material) {
  10031. results.push(this.material);
  10032. }
  10033. if (this.skeleton) {
  10034. results.push(this.skeleton);
  10035. }
  10036. return results;
  10037. };
  10038. // Geometry
  10039. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10040. // Position
  10041. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10042. return;
  10043. }
  10044. this._resetPointsArrayCache();
  10045. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10046. var temp = [];
  10047. for (var index = 0; index < data.length; index += 3) {
  10048. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10049. }
  10050. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10051. // Normals
  10052. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10053. return;
  10054. }
  10055. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10056. for (index = 0; index < data.length; index += 3) {
  10057. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10058. }
  10059. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10060. };
  10061. // Cache
  10062. Mesh.prototype._resetPointsArrayCache = function () {
  10063. this._positions = null;
  10064. };
  10065. Mesh.prototype._generatePointsArray = function () {
  10066. if (this._positions)
  10067. return true;
  10068. this._positions = [];
  10069. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10070. if (!data) {
  10071. return false;
  10072. }
  10073. for (var index = 0; index < data.length; index += 3) {
  10074. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10075. }
  10076. return true;
  10077. };
  10078. // Clone
  10079. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10080. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10081. };
  10082. // Dispose
  10083. Mesh.prototype.dispose = function (doNotRecurse) {
  10084. if (this._geometry) {
  10085. this._geometry.releaseForMesh(this, true);
  10086. }
  10087. // Instances
  10088. if (this._worldMatricesInstancesBuffer) {
  10089. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10090. this._worldMatricesInstancesBuffer = null;
  10091. }
  10092. while (this.instances.length) {
  10093. this.instances[0].dispose();
  10094. }
  10095. _super.prototype.dispose.call(this, doNotRecurse);
  10096. };
  10097. // Geometric tools
  10098. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
  10099. var _this = this;
  10100. var scene = this.getScene();
  10101. var onload = function (img) {
  10102. // Getting height map data
  10103. var canvas = document.createElement("canvas");
  10104. var context = canvas.getContext("2d");
  10105. var heightMapWidth = img.width;
  10106. var heightMapHeight = img.height;
  10107. canvas.width = heightMapWidth;
  10108. canvas.height = heightMapHeight;
  10109. context.drawImage(img, 0, 0);
  10110. // Create VertexData from map data
  10111. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10112. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10113. };
  10114. BABYLON.Tools.LoadImage(url, onload, function () {
  10115. }, scene.database);
  10116. };
  10117. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10119. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10120. return;
  10121. }
  10122. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10123. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10124. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10125. var position = BABYLON.Vector3.Zero();
  10126. var normal = BABYLON.Vector3.Zero();
  10127. var uv = BABYLON.Vector2.Zero();
  10128. for (var index = 0; index < positions.length; index += 3) {
  10129. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10130. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10131. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10132. // Compute height
  10133. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10134. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10135. var pos = (u + v * heightMapWidth) * 4;
  10136. var r = buffer[pos] / 255.0;
  10137. var g = buffer[pos + 1] / 255.0;
  10138. var b = buffer[pos + 2] / 255.0;
  10139. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10140. normal.normalize();
  10141. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10142. position = position.add(normal);
  10143. position.toArray(positions, index);
  10144. }
  10145. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10146. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10147. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10148. };
  10149. Mesh.prototype.convertToFlatShadedMesh = function () {
  10150. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10151. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10152. var kinds = this.getVerticesDataKinds();
  10153. var vbs = [];
  10154. var data = [];
  10155. var newdata = [];
  10156. var updatableNormals = false;
  10157. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10158. var kind = kinds[kindIndex];
  10159. var vertexBuffer = this.getVertexBuffer(kind);
  10160. if (kind === BABYLON.VertexBuffer.NormalKind) {
  10161. updatableNormals = vertexBuffer.isUpdatable();
  10162. kinds.splice(kindIndex, 1);
  10163. kindIndex--;
  10164. continue;
  10165. }
  10166. vbs[kind] = vertexBuffer;
  10167. data[kind] = vbs[kind].getData();
  10168. newdata[kind] = [];
  10169. }
  10170. // Save previous submeshes
  10171. var previousSubmeshes = this.subMeshes.slice(0);
  10172. var indices = this.getIndices();
  10173. var totalIndices = this.getTotalIndices();
  10174. for (var index = 0; index < totalIndices; index++) {
  10175. var vertexIndex = indices[index];
  10176. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10177. kind = kinds[kindIndex];
  10178. var stride = vbs[kind].getStrideSize();
  10179. for (var offset = 0; offset < stride; offset++) {
  10180. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  10181. }
  10182. }
  10183. }
  10184. // Updating faces & normal
  10185. var normals = [];
  10186. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  10187. for (index = 0; index < totalIndices; index += 3) {
  10188. indices[index] = index;
  10189. indices[index + 1] = index + 1;
  10190. indices[index + 2] = index + 2;
  10191. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  10192. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  10193. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  10194. var p1p2 = p1.subtract(p2);
  10195. var p3p2 = p3.subtract(p2);
  10196. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  10197. for (var localIndex = 0; localIndex < 3; localIndex++) {
  10198. normals.push(normal.x);
  10199. normals.push(normal.y);
  10200. normals.push(normal.z);
  10201. }
  10202. }
  10203. this.setIndices(indices);
  10204. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  10205. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  10206. kind = kinds[kindIndex];
  10207. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  10208. }
  10209. // Updating submeshes
  10210. this.releaseSubMeshes();
  10211. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  10212. var previousOne = previousSubmeshes[submeshIndex];
  10213. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  10214. }
  10215. this.synchronizeInstances();
  10216. };
  10217. // Instances
  10218. Mesh.prototype.createInstance = function (name) {
  10219. return new BABYLON.InstancedMesh(name, this);
  10220. };
  10221. Mesh.prototype.synchronizeInstances = function () {
  10222. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  10223. var instance = this.instances[instanceIndex];
  10224. instance._syncSubMeshes();
  10225. }
  10226. };
  10227. /**
  10228. * Simplify the mesh according to the given array of settings.
  10229. * Function will return immediately and will simplify async.
  10230. * @param settings a collection of simplification settings.
  10231. * @param parallelProcessing should all levels calculate parallel or one after the other.
  10232. * @param type the type of simplification to run.
  10233. * successCallback optional success callback to be called after the simplification finished processing all settings.
  10234. */
  10235. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  10236. var _this = this;
  10237. if (parallelProcessing === void 0) { parallelProcessing = true; }
  10238. if (type === void 0) { type = 0 /* QUADRATIC */; }
  10239. var getSimplifier = function () {
  10240. switch (type) {
  10241. case 0 /* QUADRATIC */:
  10242. default:
  10243. return new BABYLON.QuadraticErrorSimplification(_this);
  10244. }
  10245. };
  10246. if (parallelProcessing) {
  10247. //parallel simplifier
  10248. settings.forEach(function (setting) {
  10249. var simplifier = getSimplifier();
  10250. simplifier.simplify(setting, function (newMesh) {
  10251. _this.addLODLevel(setting.distance, newMesh);
  10252. //check if it is the last
  10253. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  10254. //all done, run the success callback.
  10255. successCallback();
  10256. }
  10257. });
  10258. });
  10259. }
  10260. else {
  10261. //single simplifier.
  10262. var simplifier = getSimplifier();
  10263. var runDecimation = function (setting, callback) {
  10264. simplifier.simplify(setting, function (newMesh) {
  10265. _this.addLODLevel(setting.distance, newMesh);
  10266. //run the next quality level
  10267. callback();
  10268. });
  10269. };
  10270. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  10271. runDecimation(settings[loop.index], function () {
  10272. loop.executeNext();
  10273. });
  10274. }, function () {
  10275. //execution ended, run the success callback.
  10276. if (successCallback) {
  10277. successCallback();
  10278. }
  10279. });
  10280. }
  10281. };
  10282. // Statics
  10283. Mesh.CreateBox = function (name, size, scene, updatable) {
  10284. var box = new Mesh(name, scene);
  10285. var vertexData = BABYLON.VertexData.CreateBox(size);
  10286. vertexData.applyToMesh(box, updatable);
  10287. return box;
  10288. };
  10289. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
  10290. var sphere = new Mesh(name, scene);
  10291. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
  10292. vertexData.applyToMesh(sphere, updatable);
  10293. return sphere;
  10294. };
  10295. // Cylinder and cone (Code inspired by SharpDX.org)
  10296. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
  10297. // subdivisions is a new parameter, we need to support old signature
  10298. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  10299. if (scene !== undefined) {
  10300. updatable = scene;
  10301. }
  10302. scene = subdivisions;
  10303. subdivisions = 1;
  10304. }
  10305. var cylinder = new Mesh(name, scene);
  10306. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  10307. vertexData.applyToMesh(cylinder, updatable);
  10308. return cylinder;
  10309. };
  10310. // Torus (Code from SharpDX.org)
  10311. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
  10312. var torus = new Mesh(name, scene);
  10313. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
  10314. vertexData.applyToMesh(torus, updatable);
  10315. return torus;
  10316. };
  10317. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
  10318. var torusKnot = new Mesh(name, scene);
  10319. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  10320. vertexData.applyToMesh(torusKnot, updatable);
  10321. return torusKnot;
  10322. };
  10323. // Lines
  10324. Mesh.CreateLines = function (name, points, scene, updatable) {
  10325. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  10326. var vertexData = BABYLON.VertexData.CreateLines(points);
  10327. vertexData.applyToMesh(lines, updatable);
  10328. return lines;
  10329. };
  10330. // Plane & ground
  10331. Mesh.CreatePlane = function (name, size, scene, updatable) {
  10332. var plane = new Mesh(name, scene);
  10333. var vertexData = BABYLON.VertexData.CreatePlane(size);
  10334. vertexData.applyToMesh(plane, updatable);
  10335. return plane;
  10336. };
  10337. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  10338. var ground = new BABYLON.GroundMesh(name, scene);
  10339. ground._setReady(false);
  10340. ground._subdivisions = subdivisions;
  10341. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  10342. vertexData.applyToMesh(ground, updatable);
  10343. ground._setReady(true);
  10344. return ground;
  10345. };
  10346. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  10347. var tiledGround = new Mesh(name, scene);
  10348. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  10349. vertexData.applyToMesh(tiledGround, updatable);
  10350. return tiledGround;
  10351. };
  10352. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
  10353. var ground = new BABYLON.GroundMesh(name, scene);
  10354. ground._subdivisions = subdivisions;
  10355. ground._setReady(false);
  10356. var onload = function (img) {
  10357. // Getting height map data
  10358. var canvas = document.createElement("canvas");
  10359. var context = canvas.getContext("2d");
  10360. var heightMapWidth = img.width;
  10361. var heightMapHeight = img.height;
  10362. canvas.width = heightMapWidth;
  10363. canvas.height = heightMapHeight;
  10364. context.drawImage(img, 0, 0);
  10365. // Create VertexData from map data
  10366. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10367. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  10368. vertexData.applyToMesh(ground, updatable);
  10369. ground._setReady(true);
  10370. };
  10371. BABYLON.Tools.LoadImage(url, onload, function () {
  10372. }, scene.database);
  10373. return ground;
  10374. };
  10375. // Tools
  10376. Mesh.MinMax = function (meshes) {
  10377. var minVector = null;
  10378. var maxVector = null;
  10379. for (var i in meshes) {
  10380. var mesh = meshes[i];
  10381. var boundingBox = mesh.getBoundingInfo().boundingBox;
  10382. if (!minVector) {
  10383. minVector = boundingBox.minimumWorld;
  10384. maxVector = boundingBox.maximumWorld;
  10385. continue;
  10386. }
  10387. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  10388. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  10389. }
  10390. return {
  10391. min: minVector,
  10392. max: maxVector
  10393. };
  10394. };
  10395. Mesh.Center = function (meshesOrMinMaxVector) {
  10396. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  10397. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  10398. };
  10399. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  10400. if (disposeSource === void 0) { disposeSource = true; }
  10401. var source = meshes[0];
  10402. var material = source.material;
  10403. var scene = source.getScene();
  10404. if (!allow32BitsIndices) {
  10405. var totalVertices = 0;
  10406. for (var index = 0; index < meshes.length; index++) {
  10407. totalVertices += meshes[index].getTotalVertices();
  10408. if (totalVertices > 65536) {
  10409. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  10410. return null;
  10411. }
  10412. }
  10413. }
  10414. // Merge
  10415. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  10416. vertexData.transform(source.getWorldMatrix());
  10417. for (index = 1; index < meshes.length; index++) {
  10418. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  10419. otherVertexData.transform(meshes[index].getWorldMatrix());
  10420. vertexData.merge(otherVertexData);
  10421. }
  10422. var newMesh = new Mesh(source.name + "_merged", scene);
  10423. vertexData.applyToMesh(newMesh);
  10424. // Setting properties
  10425. newMesh.material = material;
  10426. newMesh.checkCollisions = source.checkCollisions;
  10427. // Cleaning
  10428. if (disposeSource) {
  10429. for (index = 0; index < meshes.length; index++) {
  10430. meshes[index].dispose();
  10431. }
  10432. }
  10433. return newMesh;
  10434. };
  10435. return Mesh;
  10436. })(BABYLON.AbstractMesh);
  10437. BABYLON.Mesh = Mesh;
  10438. })(BABYLON || (BABYLON = {}));
  10439. //# sourceMappingURL=babylon.mesh.js.map
  10440. var BABYLON;
  10441. (function (BABYLON) {
  10442. var GroundMesh = (function (_super) {
  10443. __extends(GroundMesh, _super);
  10444. function GroundMesh(name, scene) {
  10445. _super.call(this, name, scene);
  10446. this.generateOctree = false;
  10447. this._worldInverse = new BABYLON.Matrix();
  10448. }
  10449. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  10450. get: function () {
  10451. return this._subdivisions;
  10452. },
  10453. enumerable: true,
  10454. configurable: true
  10455. });
  10456. GroundMesh.prototype.optimize = function (chunksCount) {
  10457. this.subdivide(this._subdivisions);
  10458. this.createOrUpdateSubmeshesOctree(32);
  10459. };
  10460. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  10461. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  10462. this.getWorldMatrix().invertToRef(this._worldInverse);
  10463. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  10464. var pickInfo = this.intersects(ray);
  10465. if (pickInfo.hit) {
  10466. return pickInfo.pickedPoint.y;
  10467. }
  10468. return 0;
  10469. };
  10470. return GroundMesh;
  10471. })(BABYLON.Mesh);
  10472. BABYLON.GroundMesh = GroundMesh;
  10473. })(BABYLON || (BABYLON = {}));
  10474. //# sourceMappingURL=babylon.groundMesh.js.map
  10475. var BABYLON;
  10476. (function (BABYLON) {
  10477. var InstancedMesh = (function (_super) {
  10478. __extends(InstancedMesh, _super);
  10479. function InstancedMesh(name, source) {
  10480. _super.call(this, name, source.getScene());
  10481. source.instances.push(this);
  10482. this._sourceMesh = source;
  10483. this.position.copyFrom(source.position);
  10484. this.rotation.copyFrom(source.rotation);
  10485. this.scaling.copyFrom(source.scaling);
  10486. if (source.rotationQuaternion) {
  10487. this.rotationQuaternion = source.rotationQuaternion.clone();
  10488. }
  10489. this.infiniteDistance = source.infiniteDistance;
  10490. this.setPivotMatrix(source.getPivotMatrix());
  10491. this.refreshBoundingInfo();
  10492. this._syncSubMeshes();
  10493. }
  10494. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  10495. // Methods
  10496. get: function () {
  10497. return this._sourceMesh.receiveShadows;
  10498. },
  10499. enumerable: true,
  10500. configurable: true
  10501. });
  10502. Object.defineProperty(InstancedMesh.prototype, "material", {
  10503. get: function () {
  10504. return this._sourceMesh.material;
  10505. },
  10506. enumerable: true,
  10507. configurable: true
  10508. });
  10509. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  10510. get: function () {
  10511. return this._sourceMesh.visibility;
  10512. },
  10513. enumerable: true,
  10514. configurable: true
  10515. });
  10516. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  10517. get: function () {
  10518. return this._sourceMesh.skeleton;
  10519. },
  10520. enumerable: true,
  10521. configurable: true
  10522. });
  10523. InstancedMesh.prototype.getTotalVertices = function () {
  10524. return this._sourceMesh.getTotalVertices();
  10525. };
  10526. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  10527. get: function () {
  10528. return this._sourceMesh;
  10529. },
  10530. enumerable: true,
  10531. configurable: true
  10532. });
  10533. InstancedMesh.prototype.getVerticesData = function (kind) {
  10534. return this._sourceMesh.getVerticesData(kind);
  10535. };
  10536. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  10537. return this._sourceMesh.isVerticesDataPresent(kind);
  10538. };
  10539. InstancedMesh.prototype.getIndices = function () {
  10540. return this._sourceMesh.getIndices();
  10541. };
  10542. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  10543. get: function () {
  10544. return this._sourceMesh._positions;
  10545. },
  10546. enumerable: true,
  10547. configurable: true
  10548. });
  10549. InstancedMesh.prototype.refreshBoundingInfo = function () {
  10550. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10551. if (data) {
  10552. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  10553. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10554. }
  10555. this._updateBoundingInfo();
  10556. };
  10557. InstancedMesh.prototype._preActivate = function () {
  10558. if (this._currentLOD) {
  10559. this._currentLOD._preActivate();
  10560. }
  10561. };
  10562. InstancedMesh.prototype._activate = function (renderId) {
  10563. if (this._currentLOD) {
  10564. this._currentLOD._registerInstanceForRenderId(this, renderId);
  10565. }
  10566. };
  10567. InstancedMesh.prototype.getLOD = function (camera) {
  10568. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  10569. if (this._currentLOD === this.sourceMesh) {
  10570. return this;
  10571. }
  10572. return this._currentLOD;
  10573. };
  10574. InstancedMesh.prototype._syncSubMeshes = function () {
  10575. this.releaseSubMeshes();
  10576. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  10577. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  10578. }
  10579. };
  10580. InstancedMesh.prototype._generatePointsArray = function () {
  10581. return this._sourceMesh._generatePointsArray();
  10582. };
  10583. // Clone
  10584. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10585. var result = this._sourceMesh.createInstance(name);
  10586. // Deep copy
  10587. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  10588. // Bounding info
  10589. this.refreshBoundingInfo();
  10590. // Parent
  10591. if (newParent) {
  10592. result.parent = newParent;
  10593. }
  10594. if (!doNotCloneChildren) {
  10595. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10596. var mesh = this.getScene().meshes[index];
  10597. if (mesh.parent == this) {
  10598. mesh.clone(mesh.name, result);
  10599. }
  10600. }
  10601. }
  10602. result.computeWorldMatrix(true);
  10603. return result;
  10604. };
  10605. // Dispoe
  10606. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  10607. // Remove from mesh
  10608. var index = this._sourceMesh.instances.indexOf(this);
  10609. this._sourceMesh.instances.splice(index, 1);
  10610. _super.prototype.dispose.call(this, doNotRecurse);
  10611. };
  10612. return InstancedMesh;
  10613. })(BABYLON.AbstractMesh);
  10614. BABYLON.InstancedMesh = InstancedMesh;
  10615. })(BABYLON || (BABYLON = {}));
  10616. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  10617. (function (BABYLON) {
  10618. var SubMesh = (function () {
  10619. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  10620. if (createBoundingBox === void 0) { createBoundingBox = true; }
  10621. this.materialIndex = materialIndex;
  10622. this.verticesStart = verticesStart;
  10623. this.verticesCount = verticesCount;
  10624. this.indexStart = indexStart;
  10625. this.indexCount = indexCount;
  10626. this._renderId = 0;
  10627. this._mesh = mesh;
  10628. this._renderingMesh = renderingMesh || mesh;
  10629. mesh.subMeshes.push(this);
  10630. this._id = mesh.subMeshes.length - 1;
  10631. if (createBoundingBox) {
  10632. this.refreshBoundingInfo();
  10633. }
  10634. }
  10635. SubMesh.prototype.getBoundingInfo = function () {
  10636. return this._boundingInfo;
  10637. };
  10638. SubMesh.prototype.getMesh = function () {
  10639. return this._mesh;
  10640. };
  10641. SubMesh.prototype.getRenderingMesh = function () {
  10642. return this._renderingMesh;
  10643. };
  10644. SubMesh.prototype.getMaterial = function () {
  10645. var rootMaterial = this._renderingMesh.material;
  10646. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  10647. var multiMaterial = rootMaterial;
  10648. return multiMaterial.getSubMaterial(this.materialIndex);
  10649. }
  10650. if (!rootMaterial) {
  10651. return this._mesh.getScene().defaultMaterial;
  10652. }
  10653. return rootMaterial;
  10654. };
  10655. // Methods
  10656. SubMesh.prototype.refreshBoundingInfo = function () {
  10657. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10658. if (!data) {
  10659. this._boundingInfo = this._mesh._boundingInfo;
  10660. return;
  10661. }
  10662. var indices = this._renderingMesh.getIndices();
  10663. var extend;
  10664. if (this.indexStart === 0 && this.indexCount === indices.length) {
  10665. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  10666. }
  10667. else {
  10668. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  10669. }
  10670. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10671. };
  10672. SubMesh.prototype._checkCollision = function (collider) {
  10673. return this._boundingInfo._checkCollision(collider);
  10674. };
  10675. SubMesh.prototype.updateBoundingInfo = function (world) {
  10676. if (!this._boundingInfo) {
  10677. this.refreshBoundingInfo();
  10678. }
  10679. this._boundingInfo._update(world);
  10680. };
  10681. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  10682. return this._boundingInfo.isInFrustum(frustumPlanes);
  10683. };
  10684. SubMesh.prototype.render = function () {
  10685. this._renderingMesh.render(this);
  10686. };
  10687. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  10688. if (!this._linesIndexBuffer) {
  10689. var linesIndices = [];
  10690. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10691. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  10692. }
  10693. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  10694. this.linesIndexCount = linesIndices.length;
  10695. }
  10696. return this._linesIndexBuffer;
  10697. };
  10698. SubMesh.prototype.canIntersects = function (ray) {
  10699. return ray.intersectsBox(this._boundingInfo.boundingBox);
  10700. };
  10701. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  10702. var intersectInfo = null;
  10703. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  10704. var p0 = positions[indices[index]];
  10705. var p1 = positions[indices[index + 1]];
  10706. var p2 = positions[indices[index + 2]];
  10707. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  10708. if (currentIntersectInfo) {
  10709. if (currentIntersectInfo.distance < 0) {
  10710. continue;
  10711. }
  10712. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10713. intersectInfo = currentIntersectInfo;
  10714. intersectInfo.faceId = index / 3;
  10715. if (fastCheck) {
  10716. break;
  10717. }
  10718. }
  10719. }
  10720. }
  10721. return intersectInfo;
  10722. };
  10723. // Clone
  10724. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  10725. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  10726. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  10727. return result;
  10728. };
  10729. // Dispose
  10730. SubMesh.prototype.dispose = function () {
  10731. if (this._linesIndexBuffer) {
  10732. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  10733. this._linesIndexBuffer = null;
  10734. }
  10735. // Remove from mesh
  10736. var index = this._mesh.subMeshes.indexOf(this);
  10737. this._mesh.subMeshes.splice(index, 1);
  10738. };
  10739. // Statics
  10740. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  10741. var minVertexIndex = Number.MAX_VALUE;
  10742. var maxVertexIndex = -Number.MAX_VALUE;
  10743. renderingMesh = renderingMesh || mesh;
  10744. var indices = renderingMesh.getIndices();
  10745. for (var index = startIndex; index < startIndex + indexCount; index++) {
  10746. var vertexIndex = indices[index];
  10747. if (vertexIndex < minVertexIndex)
  10748. minVertexIndex = vertexIndex;
  10749. if (vertexIndex > maxVertexIndex)
  10750. maxVertexIndex = vertexIndex;
  10751. }
  10752. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  10753. };
  10754. return SubMesh;
  10755. })();
  10756. BABYLON.SubMesh = SubMesh;
  10757. })(BABYLON || (BABYLON = {}));
  10758. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  10759. (function (BABYLON) {
  10760. var BaseTexture = (function () {
  10761. function BaseTexture(scene) {
  10762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10763. this.hasAlpha = false;
  10764. this.getAlphaFromRGB = false;
  10765. this.level = 1;
  10766. this.isCube = false;
  10767. this.isRenderTarget = false;
  10768. this.animations = new Array();
  10769. this.coordinatesIndex = 0;
  10770. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  10771. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  10772. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  10773. this.anisotropicFilteringLevel = 4;
  10774. this._scene = scene;
  10775. this._scene.textures.push(this);
  10776. }
  10777. BaseTexture.prototype.getScene = function () {
  10778. return this._scene;
  10779. };
  10780. BaseTexture.prototype.getTextureMatrix = function () {
  10781. return null;
  10782. };
  10783. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  10784. return null;
  10785. };
  10786. BaseTexture.prototype.getInternalTexture = function () {
  10787. return this._texture;
  10788. };
  10789. BaseTexture.prototype.isReady = function () {
  10790. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10791. return true;
  10792. }
  10793. if (this._texture) {
  10794. return this._texture.isReady;
  10795. }
  10796. return false;
  10797. };
  10798. BaseTexture.prototype.getSize = function () {
  10799. if (this._texture._width) {
  10800. return { width: this._texture._width, height: this._texture._height };
  10801. }
  10802. if (this._texture._size) {
  10803. return { width: this._texture._size, height: this._texture._size };
  10804. }
  10805. return { width: 0, height: 0 };
  10806. };
  10807. BaseTexture.prototype.getBaseSize = function () {
  10808. if (!this.isReady())
  10809. return { width: 0, height: 0 };
  10810. if (this._texture._size) {
  10811. return { width: this._texture._size, height: this._texture._size };
  10812. }
  10813. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  10814. };
  10815. BaseTexture.prototype.scale = function (ratio) {
  10816. };
  10817. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  10818. get: function () {
  10819. return false;
  10820. },
  10821. enumerable: true,
  10822. configurable: true
  10823. });
  10824. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  10825. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10826. for (var index = 0; index < texturesCache.length; index++) {
  10827. var texturesCacheEntry = texturesCache[index];
  10828. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10829. texturesCache.splice(index, 1);
  10830. return;
  10831. }
  10832. }
  10833. };
  10834. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  10835. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10836. for (var index = 0; index < texturesCache.length; index++) {
  10837. var texturesCacheEntry = texturesCache[index];
  10838. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  10839. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  10840. texturesCacheEntry.references++;
  10841. return texturesCacheEntry;
  10842. }
  10843. }
  10844. }
  10845. return null;
  10846. };
  10847. BaseTexture.prototype.delayLoad = function () {
  10848. };
  10849. BaseTexture.prototype.releaseInternalTexture = function () {
  10850. if (!this._texture) {
  10851. return;
  10852. }
  10853. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  10854. this._texture.references--;
  10855. // Final reference ?
  10856. if (this._texture.references === 0) {
  10857. var index = texturesCache.indexOf(this._texture);
  10858. texturesCache.splice(index, 1);
  10859. this._scene.getEngine()._releaseTexture(this._texture);
  10860. delete this._texture;
  10861. }
  10862. };
  10863. BaseTexture.prototype.clone = function () {
  10864. return null;
  10865. };
  10866. BaseTexture.prototype.dispose = function () {
  10867. // Remove from scene
  10868. var index = this._scene.textures.indexOf(this);
  10869. if (index >= 0) {
  10870. this._scene.textures.splice(index, 1);
  10871. }
  10872. if (this._texture === undefined) {
  10873. return;
  10874. }
  10875. this.releaseInternalTexture();
  10876. // Callback
  10877. if (this.onDispose) {
  10878. this.onDispose();
  10879. }
  10880. };
  10881. return BaseTexture;
  10882. })();
  10883. BABYLON.BaseTexture = BaseTexture;
  10884. })(BABYLON || (BABYLON = {}));
  10885. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  10886. (function (BABYLON) {
  10887. var RenderingGroup = (function () {
  10888. function RenderingGroup(index, scene) {
  10889. this.index = index;
  10890. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  10891. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  10892. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  10893. this._scene = scene;
  10894. }
  10895. RenderingGroup.prototype.render = function (customRenderFunction) {
  10896. if (customRenderFunction) {
  10897. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  10898. return true;
  10899. }
  10900. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  10901. return false;
  10902. }
  10903. var engine = this._scene.getEngine();
  10904. // Opaque
  10905. var subIndex;
  10906. var submesh;
  10907. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  10908. submesh = this._opaqueSubMeshes.data[subIndex];
  10909. submesh.render();
  10910. }
  10911. // Alpha test
  10912. engine.setAlphaTesting(true);
  10913. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  10914. submesh = this._alphaTestSubMeshes.data[subIndex];
  10915. submesh.render();
  10916. }
  10917. engine.setAlphaTesting(false);
  10918. // Transparent
  10919. if (this._transparentSubMeshes.length) {
  10920. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  10921. submesh = this._transparentSubMeshes.data[subIndex];
  10922. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  10923. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  10924. }
  10925. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  10926. sortedArray.sort(function (a, b) {
  10927. // Alpha index first
  10928. if (a._alphaIndex > b._alphaIndex) {
  10929. return 1;
  10930. }
  10931. if (a._alphaIndex < b._alphaIndex) {
  10932. return -1;
  10933. }
  10934. // Then distance to camera
  10935. if (a._distanceToCamera < b._distanceToCamera) {
  10936. return 1;
  10937. }
  10938. if (a._distanceToCamera > b._distanceToCamera) {
  10939. return -1;
  10940. }
  10941. return 0;
  10942. });
  10943. // Rendering
  10944. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10945. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  10946. submesh = sortedArray[subIndex];
  10947. submesh.render();
  10948. }
  10949. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  10950. }
  10951. return true;
  10952. };
  10953. RenderingGroup.prototype.prepare = function () {
  10954. this._opaqueSubMeshes.reset();
  10955. this._transparentSubMeshes.reset();
  10956. this._alphaTestSubMeshes.reset();
  10957. };
  10958. RenderingGroup.prototype.dispatch = function (subMesh) {
  10959. var material = subMesh.getMaterial();
  10960. var mesh = subMesh.getMesh();
  10961. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  10962. this._transparentSubMeshes.push(subMesh);
  10963. }
  10964. else if (material.needAlphaTesting()) {
  10965. this._alphaTestSubMeshes.push(subMesh);
  10966. }
  10967. else {
  10968. this._opaqueSubMeshes.push(subMesh); // Opaque
  10969. }
  10970. };
  10971. return RenderingGroup;
  10972. })();
  10973. BABYLON.RenderingGroup = RenderingGroup;
  10974. })(BABYLON || (BABYLON = {}));
  10975. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  10976. (function (BABYLON) {
  10977. var RenderingManager = (function () {
  10978. function RenderingManager(scene) {
  10979. this._renderingGroups = new Array();
  10980. this._scene = scene;
  10981. }
  10982. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  10983. if (this._scene._activeParticleSystems.length === 0) {
  10984. return;
  10985. }
  10986. // Particles
  10987. var beforeParticlesDate = BABYLON.Tools.Now;
  10988. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  10989. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  10990. if (particleSystem.renderingGroupId !== index) {
  10991. continue;
  10992. }
  10993. this._clearDepthBuffer();
  10994. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  10995. this._scene._activeParticles += particleSystem.render();
  10996. }
  10997. }
  10998. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  10999. };
  11000. RenderingManager.prototype._renderSprites = function (index) {
  11001. if (this._scene.spriteManagers.length === 0) {
  11002. return;
  11003. }
  11004. // Sprites
  11005. var beforeSpritessDate = BABYLON.Tools.Now;
  11006. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11007. var spriteManager = this._scene.spriteManagers[id];
  11008. if (spriteManager.renderingGroupId === index) {
  11009. this._clearDepthBuffer();
  11010. spriteManager.render();
  11011. }
  11012. }
  11013. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11014. };
  11015. RenderingManager.prototype._clearDepthBuffer = function () {
  11016. if (this._depthBufferAlreadyCleaned) {
  11017. return;
  11018. }
  11019. this._scene.getEngine().clear(0, false, true);
  11020. this._depthBufferAlreadyCleaned = true;
  11021. };
  11022. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11023. for (var index = 0; index < BABYLON.RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11024. this._depthBufferAlreadyCleaned = false;
  11025. var renderingGroup = this._renderingGroups[index];
  11026. if (renderingGroup) {
  11027. this._clearDepthBuffer();
  11028. if (!renderingGroup.render(customRenderFunction)) {
  11029. this._renderingGroups.splice(index, 1);
  11030. }
  11031. }
  11032. this._renderSprites(index);
  11033. if (renderParticles) {
  11034. this._renderParticles(index, activeMeshes);
  11035. }
  11036. }
  11037. };
  11038. RenderingManager.prototype.reset = function () {
  11039. for (var index in this._renderingGroups) {
  11040. var renderingGroup = this._renderingGroups[index];
  11041. renderingGroup.prepare();
  11042. }
  11043. };
  11044. RenderingManager.prototype.dispatch = function (subMesh) {
  11045. var mesh = subMesh.getMesh();
  11046. var renderingGroupId = mesh.renderingGroupId || 0;
  11047. if (!this._renderingGroups[renderingGroupId]) {
  11048. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11049. }
  11050. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11051. };
  11052. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11053. return RenderingManager;
  11054. })();
  11055. BABYLON.RenderingManager = RenderingManager;
  11056. })(BABYLON || (BABYLON = {}));
  11057. //# sourceMappingURL=babylon.renderingManager.js.map
  11058. var BABYLON;
  11059. (function (BABYLON) {
  11060. var Texture = (function (_super) {
  11061. __extends(Texture, _super);
  11062. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11063. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11064. if (onLoad === void 0) { onLoad = null; }
  11065. if (onError === void 0) { onError = null; }
  11066. if (buffer === void 0) { buffer = null; }
  11067. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11068. _super.call(this, scene);
  11069. this.uOffset = 0;
  11070. this.vOffset = 0;
  11071. this.uScale = 1.0;
  11072. this.vScale = 1.0;
  11073. this.uAng = 0;
  11074. this.vAng = 0;
  11075. this.wAng = 0;
  11076. this.name = url;
  11077. this.url = url;
  11078. this._noMipmap = noMipmap;
  11079. this._invertY = invertY;
  11080. this._samplingMode = samplingMode;
  11081. this._buffer = buffer;
  11082. this._deleteBuffer = deleteBuffer;
  11083. if (!url) {
  11084. return;
  11085. }
  11086. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11087. if (!this._texture) {
  11088. if (!scene.useDelayedTextureLoading) {
  11089. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  11090. if (deleteBuffer) {
  11091. delete this._buffer;
  11092. }
  11093. }
  11094. else {
  11095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11096. }
  11097. }
  11098. }
  11099. Texture.prototype.delayLoad = function () {
  11100. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11101. return;
  11102. }
  11103. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11104. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  11105. if (!this._texture) {
  11106. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  11107. if (this._deleteBuffer) {
  11108. delete this._buffer;
  11109. }
  11110. }
  11111. };
  11112. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  11113. x -= this.uOffset + 0.5;
  11114. y -= this.vOffset + 0.5;
  11115. z -= 0.5;
  11116. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  11117. t.x *= this.uScale;
  11118. t.y *= this.vScale;
  11119. t.x += 0.5;
  11120. t.y += 0.5;
  11121. t.z += 0.5;
  11122. };
  11123. Texture.prototype.getTextureMatrix = function () {
  11124. 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) {
  11125. return this._cachedTextureMatrix;
  11126. }
  11127. this._cachedUOffset = this.uOffset;
  11128. this._cachedVOffset = this.vOffset;
  11129. this._cachedUScale = this.uScale;
  11130. this._cachedVScale = this.vScale;
  11131. this._cachedUAng = this.uAng;
  11132. this._cachedVAng = this.vAng;
  11133. this._cachedWAng = this.wAng;
  11134. if (!this._cachedTextureMatrix) {
  11135. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11136. this._rowGenerationMatrix = new BABYLON.Matrix();
  11137. this._t0 = BABYLON.Vector3.Zero();
  11138. this._t1 = BABYLON.Vector3.Zero();
  11139. this._t2 = BABYLON.Vector3.Zero();
  11140. }
  11141. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  11142. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  11143. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  11144. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  11145. this._t1.subtractInPlace(this._t0);
  11146. this._t2.subtractInPlace(this._t0);
  11147. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11148. this._cachedTextureMatrix.m[0] = this._t1.x;
  11149. this._cachedTextureMatrix.m[1] = this._t1.y;
  11150. this._cachedTextureMatrix.m[2] = this._t1.z;
  11151. this._cachedTextureMatrix.m[4] = this._t2.x;
  11152. this._cachedTextureMatrix.m[5] = this._t2.y;
  11153. this._cachedTextureMatrix.m[6] = this._t2.z;
  11154. this._cachedTextureMatrix.m[8] = this._t0.x;
  11155. this._cachedTextureMatrix.m[9] = this._t0.y;
  11156. this._cachedTextureMatrix.m[10] = this._t0.z;
  11157. return this._cachedTextureMatrix;
  11158. };
  11159. Texture.prototype.getReflectionTextureMatrix = function () {
  11160. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  11161. return this._cachedTextureMatrix;
  11162. }
  11163. if (!this._cachedTextureMatrix) {
  11164. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  11165. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  11166. }
  11167. this._cachedCoordinatesMode = this.coordinatesMode;
  11168. switch (this.coordinatesMode) {
  11169. case BABYLON.Texture.SPHERICAL_MODE:
  11170. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11171. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  11172. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  11173. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  11174. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  11175. break;
  11176. case BABYLON.Texture.PLANAR_MODE:
  11177. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11178. this._cachedTextureMatrix[0] = this.uScale;
  11179. this._cachedTextureMatrix[5] = this.vScale;
  11180. this._cachedTextureMatrix[12] = this.uOffset;
  11181. this._cachedTextureMatrix[13] = this.vOffset;
  11182. break;
  11183. case BABYLON.Texture.PROJECTION_MODE:
  11184. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  11185. this._projectionModeMatrix.m[0] = 0.5;
  11186. this._projectionModeMatrix.m[5] = -0.5;
  11187. this._projectionModeMatrix.m[10] = 0.0;
  11188. this._projectionModeMatrix.m[12] = 0.5;
  11189. this._projectionModeMatrix.m[13] = 0.5;
  11190. this._projectionModeMatrix.m[14] = 1.0;
  11191. this._projectionModeMatrix.m[15] = 1.0;
  11192. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  11193. break;
  11194. default:
  11195. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  11196. break;
  11197. }
  11198. return this._cachedTextureMatrix;
  11199. };
  11200. Texture.prototype.clone = function () {
  11201. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY);
  11202. // Base texture
  11203. newTexture.hasAlpha = this.hasAlpha;
  11204. newTexture.level = this.level;
  11205. newTexture.wrapU = this.wrapU;
  11206. newTexture.wrapV = this.wrapV;
  11207. newTexture.coordinatesIndex = this.coordinatesIndex;
  11208. newTexture.coordinatesMode = this.coordinatesMode;
  11209. // Texture
  11210. newTexture.uOffset = this.uOffset;
  11211. newTexture.vOffset = this.vOffset;
  11212. newTexture.uScale = this.uScale;
  11213. newTexture.vScale = this.vScale;
  11214. newTexture.uAng = this.uAng;
  11215. newTexture.vAng = this.vAng;
  11216. newTexture.wAng = this.wAng;
  11217. return newTexture;
  11218. };
  11219. // Statics
  11220. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  11221. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11222. if (onLoad === void 0) { onLoad = null; }
  11223. if (onError === void 0) { onError = null; }
  11224. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  11225. };
  11226. // Constants
  11227. Texture.NEAREST_SAMPLINGMODE = 1;
  11228. Texture.BILINEAR_SAMPLINGMODE = 2;
  11229. Texture.TRILINEAR_SAMPLINGMODE = 3;
  11230. Texture.EXPLICIT_MODE = 0;
  11231. Texture.SPHERICAL_MODE = 1;
  11232. Texture.PLANAR_MODE = 2;
  11233. Texture.CUBIC_MODE = 3;
  11234. Texture.PROJECTION_MODE = 4;
  11235. Texture.SKYBOX_MODE = 5;
  11236. Texture.CLAMP_ADDRESSMODE = 0;
  11237. Texture.WRAP_ADDRESSMODE = 1;
  11238. Texture.MIRROR_ADDRESSMODE = 2;
  11239. return Texture;
  11240. })(BABYLON.BaseTexture);
  11241. BABYLON.Texture = Texture;
  11242. })(BABYLON || (BABYLON = {}));
  11243. //# sourceMappingURL=babylon.texture.js.map
  11244. var BABYLON;
  11245. (function (BABYLON) {
  11246. var CubeTexture = (function (_super) {
  11247. __extends(CubeTexture, _super);
  11248. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  11249. _super.call(this, scene);
  11250. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  11251. this.name = rootUrl;
  11252. this.url = rootUrl;
  11253. this._noMipmap = noMipmap;
  11254. this.hasAlpha = false;
  11255. this._texture = this._getFromCache(rootUrl, noMipmap);
  11256. if (!extensions) {
  11257. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  11258. }
  11259. this._extensions = extensions;
  11260. if (!this._texture) {
  11261. if (!scene.useDelayedTextureLoading) {
  11262. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  11263. }
  11264. else {
  11265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  11266. }
  11267. }
  11268. this.isCube = true;
  11269. this._textureMatrix = BABYLON.Matrix.Identity();
  11270. }
  11271. CubeTexture.prototype.clone = function () {
  11272. var newTexture = new BABYLON.CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  11273. // Base texture
  11274. newTexture.level = this.level;
  11275. newTexture.wrapU = this.wrapU;
  11276. newTexture.wrapV = this.wrapV;
  11277. newTexture.coordinatesIndex = this.coordinatesIndex;
  11278. newTexture.coordinatesMode = this.coordinatesMode;
  11279. return newTexture;
  11280. };
  11281. // Methods
  11282. CubeTexture.prototype.delayLoad = function () {
  11283. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11284. return;
  11285. }
  11286. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11287. this._texture = this._getFromCache(this.url, this._noMipmap);
  11288. if (!this._texture) {
  11289. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  11290. }
  11291. };
  11292. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  11293. return this._textureMatrix;
  11294. };
  11295. return CubeTexture;
  11296. })(BABYLON.BaseTexture);
  11297. BABYLON.CubeTexture = CubeTexture;
  11298. })(BABYLON || (BABYLON = {}));
  11299. //# sourceMappingURL=babylon.cubeTexture.js.map
  11300. var BABYLON;
  11301. (function (BABYLON) {
  11302. var RenderTargetTexture = (function (_super) {
  11303. __extends(RenderTargetTexture, _super);
  11304. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio) {
  11305. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  11306. _super.call(this, null, scene, !generateMipMaps);
  11307. this.renderList = new Array();
  11308. this.renderParticles = true;
  11309. this.renderSprites = false;
  11310. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  11311. this._currentRefreshId = -1;
  11312. this._refreshRate = 1;
  11313. this.name = name;
  11314. this.isRenderTarget = true;
  11315. this._size = size;
  11316. this._generateMipMaps = generateMipMaps;
  11317. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  11318. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11319. // Rendering groups
  11320. this._renderingManager = new BABYLON.RenderingManager(scene);
  11321. }
  11322. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  11323. this._currentRefreshId = -1;
  11324. };
  11325. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  11326. get: function () {
  11327. return this._refreshRate;
  11328. },
  11329. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11330. set: function (value) {
  11331. this._refreshRate = value;
  11332. this.resetRefreshCounter();
  11333. },
  11334. enumerable: true,
  11335. configurable: true
  11336. });
  11337. RenderTargetTexture.prototype._shouldRender = function () {
  11338. if (this._currentRefreshId === -1) {
  11339. this._currentRefreshId = 1;
  11340. return true;
  11341. }
  11342. if (this.refreshRate == this._currentRefreshId) {
  11343. this._currentRefreshId = 1;
  11344. return true;
  11345. }
  11346. this._currentRefreshId++;
  11347. return false;
  11348. };
  11349. RenderTargetTexture.prototype.isReady = function () {
  11350. if (!this.getScene().renderTargetsEnabled) {
  11351. return false;
  11352. }
  11353. return _super.prototype.isReady.call(this);
  11354. };
  11355. RenderTargetTexture.prototype.getRenderSize = function () {
  11356. return this._size;
  11357. };
  11358. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  11359. get: function () {
  11360. return true;
  11361. },
  11362. enumerable: true,
  11363. configurable: true
  11364. });
  11365. RenderTargetTexture.prototype.scale = function (ratio) {
  11366. var newSize = this._size * ratio;
  11367. this.resize(newSize, this._generateMipMaps);
  11368. };
  11369. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  11370. this.releaseInternalTexture();
  11371. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11372. };
  11373. RenderTargetTexture.prototype.render = function (useCameraPostProcess) {
  11374. var scene = this.getScene();
  11375. var engine = scene.getEngine();
  11376. if (this._waitingRenderList) {
  11377. this.renderList = [];
  11378. for (var index = 0; index < this._waitingRenderList.length; index++) {
  11379. var id = this._waitingRenderList[index];
  11380. this.renderList.push(scene.getMeshByID(id));
  11381. }
  11382. delete this._waitingRenderList;
  11383. }
  11384. if (!this.renderList) {
  11385. return;
  11386. }
  11387. // Bind
  11388. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  11389. engine.bindFramebuffer(this._texture);
  11390. }
  11391. // Clear
  11392. engine.clear(scene.clearColor, true, true);
  11393. this._renderingManager.reset();
  11394. for (var meshIndex = 0; meshIndex < this.renderList.length; meshIndex++) {
  11395. var mesh = this.renderList[meshIndex];
  11396. if (mesh) {
  11397. if (!mesh.isReady() || (mesh.material && !mesh.material.isReady())) {
  11398. // Reset _currentRefreshId
  11399. this.resetRefreshCounter();
  11400. continue;
  11401. }
  11402. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) != 0)) {
  11403. mesh._activate(scene.getRenderId());
  11404. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  11405. var subMesh = mesh.subMeshes[subIndex];
  11406. scene._activeVertices += subMesh.indexCount;
  11407. this._renderingManager.dispatch(subMesh);
  11408. }
  11409. }
  11410. }
  11411. }
  11412. if (!this._doNotChangeAspectRatio) {
  11413. scene.updateTransformMatrix(true);
  11414. }
  11415. if (this.onBeforeRender) {
  11416. this.onBeforeRender();
  11417. }
  11418. // Render
  11419. this._renderingManager.render(this.customRenderFunction, this.renderList, this.renderParticles, this.renderSprites);
  11420. if (useCameraPostProcess) {
  11421. scene.postProcessManager._finalizeFrame(false, this._texture);
  11422. }
  11423. if (this.onAfterRender) {
  11424. this.onAfterRender();
  11425. }
  11426. // Unbind
  11427. engine.unBindFramebuffer(this._texture);
  11428. if (!this._doNotChangeAspectRatio) {
  11429. scene.updateTransformMatrix(true);
  11430. }
  11431. };
  11432. RenderTargetTexture.prototype.clone = function () {
  11433. var textureSize = this.getSize();
  11434. var newTexture = new BABYLON.RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  11435. // Base texture
  11436. newTexture.hasAlpha = this.hasAlpha;
  11437. newTexture.level = this.level;
  11438. // RenderTarget Texture
  11439. newTexture.coordinatesMode = this.coordinatesMode;
  11440. newTexture.renderList = this.renderList.slice(0);
  11441. return newTexture;
  11442. };
  11443. return RenderTargetTexture;
  11444. })(BABYLON.Texture);
  11445. BABYLON.RenderTargetTexture = RenderTargetTexture;
  11446. })(BABYLON || (BABYLON = {}));
  11447. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  11448. var BABYLON;
  11449. (function (BABYLON) {
  11450. var ProceduralTexture = (function (_super) {
  11451. __extends(ProceduralTexture, _super);
  11452. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  11453. if (generateMipMaps === void 0) { generateMipMaps = true; }
  11454. _super.call(this, null, scene, !generateMipMaps);
  11455. this._currentRefreshId = -1;
  11456. this._refreshRate = 1;
  11457. this._vertexDeclaration = [2];
  11458. this._vertexStrideSize = 2 * 4;
  11459. this._uniforms = new Array();
  11460. this._samplers = new Array();
  11461. this._textures = new Array();
  11462. this._floats = new Array();
  11463. this._floatsArrays = {};
  11464. this._colors3 = new Array();
  11465. this._colors4 = new Array();
  11466. this._vectors2 = new Array();
  11467. this._vectors3 = new Array();
  11468. this._matrices = new Array();
  11469. this._fallbackTextureUsed = false;
  11470. scene._proceduralTextures.push(this);
  11471. this.name = name;
  11472. this.isRenderTarget = true;
  11473. this._size = size;
  11474. this._generateMipMaps = generateMipMaps;
  11475. this.setFragment(fragment);
  11476. this._fallbackTexture = fallbackTexture;
  11477. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  11478. // VBO
  11479. var vertices = [];
  11480. vertices.push(1, 1);
  11481. vertices.push(-1, 1);
  11482. vertices.push(-1, -1);
  11483. vertices.push(1, -1);
  11484. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  11485. // Indices
  11486. var indices = [];
  11487. indices.push(0);
  11488. indices.push(1);
  11489. indices.push(2);
  11490. indices.push(0);
  11491. indices.push(2);
  11492. indices.push(3);
  11493. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  11494. }
  11495. ProceduralTexture.prototype.reset = function () {
  11496. if (this._effect === undefined) {
  11497. return;
  11498. }
  11499. var engine = this.getScene().getEngine();
  11500. engine._releaseEffect(this._effect);
  11501. };
  11502. ProceduralTexture.prototype.isReady = function () {
  11503. var _this = this;
  11504. var engine = this.getScene().getEngine();
  11505. var shaders;
  11506. if (!this._fragment) {
  11507. return false;
  11508. }
  11509. if (this._fallbackTextureUsed) {
  11510. return true;
  11511. }
  11512. if (this._fragment.fragmentElement !== undefined) {
  11513. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  11514. }
  11515. else {
  11516. shaders = { vertex: "procedural", fragment: this._fragment };
  11517. }
  11518. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  11519. _this.releaseInternalTexture();
  11520. if (_this._fallbackTexture) {
  11521. _this._texture = _this._fallbackTexture._texture;
  11522. _this._texture.references++;
  11523. }
  11524. _this._fallbackTextureUsed = true;
  11525. });
  11526. return this._effect.isReady();
  11527. };
  11528. ProceduralTexture.prototype.resetRefreshCounter = function () {
  11529. this._currentRefreshId = -1;
  11530. };
  11531. ProceduralTexture.prototype.setFragment = function (fragment) {
  11532. this._fragment = fragment;
  11533. };
  11534. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  11535. get: function () {
  11536. return this._refreshRate;
  11537. },
  11538. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  11539. set: function (value) {
  11540. this._refreshRate = value;
  11541. this.resetRefreshCounter();
  11542. },
  11543. enumerable: true,
  11544. configurable: true
  11545. });
  11546. ProceduralTexture.prototype._shouldRender = function () {
  11547. if (!this.isReady() || !this._texture) {
  11548. return false;
  11549. }
  11550. if (this._fallbackTextureUsed) {
  11551. return false;
  11552. }
  11553. if (this._currentRefreshId === -1) {
  11554. this._currentRefreshId = 1;
  11555. return true;
  11556. }
  11557. if (this.refreshRate === this._currentRefreshId) {
  11558. this._currentRefreshId = 1;
  11559. return true;
  11560. }
  11561. this._currentRefreshId++;
  11562. return false;
  11563. };
  11564. ProceduralTexture.prototype.getRenderSize = function () {
  11565. return this._size;
  11566. };
  11567. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  11568. if (this._fallbackTextureUsed) {
  11569. return;
  11570. }
  11571. this.releaseInternalTexture();
  11572. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  11573. };
  11574. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  11575. if (this._uniforms.indexOf(uniformName) === -1) {
  11576. this._uniforms.push(uniformName);
  11577. }
  11578. };
  11579. ProceduralTexture.prototype.setTexture = function (name, texture) {
  11580. if (this._samplers.indexOf(name) === -1) {
  11581. this._samplers.push(name);
  11582. }
  11583. this._textures[name] = texture;
  11584. return this;
  11585. };
  11586. ProceduralTexture.prototype.setFloat = function (name, value) {
  11587. this._checkUniform(name);
  11588. this._floats[name] = value;
  11589. return this;
  11590. };
  11591. ProceduralTexture.prototype.setFloats = function (name, value) {
  11592. this._checkUniform(name);
  11593. this._floatsArrays[name] = value;
  11594. return this;
  11595. };
  11596. ProceduralTexture.prototype.setColor3 = function (name, value) {
  11597. this._checkUniform(name);
  11598. this._colors3[name] = value;
  11599. return this;
  11600. };
  11601. ProceduralTexture.prototype.setColor4 = function (name, value) {
  11602. this._checkUniform(name);
  11603. this._colors4[name] = value;
  11604. return this;
  11605. };
  11606. ProceduralTexture.prototype.setVector2 = function (name, value) {
  11607. this._checkUniform(name);
  11608. this._vectors2[name] = value;
  11609. return this;
  11610. };
  11611. ProceduralTexture.prototype.setVector3 = function (name, value) {
  11612. this._checkUniform(name);
  11613. this._vectors3[name] = value;
  11614. return this;
  11615. };
  11616. ProceduralTexture.prototype.setMatrix = function (name, value) {
  11617. this._checkUniform(name);
  11618. this._matrices[name] = value;
  11619. return this;
  11620. };
  11621. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11622. var scene = this.getScene();
  11623. var engine = scene.getEngine();
  11624. engine.bindFramebuffer(this._texture);
  11625. // Clear
  11626. engine.clear(scene.clearColor, true, true);
  11627. // Render
  11628. engine.enableEffect(this._effect);
  11629. engine.setState(false);
  11630. for (var name in this._textures) {
  11631. this._effect.setTexture(name, this._textures[name]);
  11632. }
  11633. for (name in this._floats) {
  11634. this._effect.setFloat(name, this._floats[name]);
  11635. }
  11636. for (name in this._floatsArrays) {
  11637. this._effect.setArray(name, this._floatsArrays[name]);
  11638. }
  11639. for (name in this._colors3) {
  11640. this._effect.setColor3(name, this._colors3[name]);
  11641. }
  11642. for (name in this._colors4) {
  11643. var color = this._colors4[name];
  11644. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  11645. }
  11646. for (name in this._vectors2) {
  11647. this._effect.setVector2(name, this._vectors2[name]);
  11648. }
  11649. for (name in this._vectors3) {
  11650. this._effect.setVector3(name, this._vectors3[name]);
  11651. }
  11652. for (name in this._matrices) {
  11653. this._effect.setMatrix(name, this._matrices[name]);
  11654. }
  11655. // VBOs
  11656. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  11657. // Draw order
  11658. engine.draw(true, 0, 6);
  11659. // Unbind
  11660. engine.unBindFramebuffer(this._texture);
  11661. };
  11662. ProceduralTexture.prototype.clone = function () {
  11663. var textureSize = this.getSize();
  11664. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  11665. // Base texture
  11666. newTexture.hasAlpha = this.hasAlpha;
  11667. newTexture.level = this.level;
  11668. // RenderTarget Texture
  11669. newTexture.coordinatesMode = this.coordinatesMode;
  11670. return newTexture;
  11671. };
  11672. ProceduralTexture.prototype.dispose = function () {
  11673. var index = this.getScene()._proceduralTextures.indexOf(this);
  11674. if (index >= 0) {
  11675. this.getScene()._proceduralTextures.splice(index, 1);
  11676. }
  11677. _super.prototype.dispose.call(this);
  11678. };
  11679. return ProceduralTexture;
  11680. })(BABYLON.Texture);
  11681. BABYLON.ProceduralTexture = ProceduralTexture;
  11682. })(BABYLON || (BABYLON = {}));
  11683. //# sourceMappingURL=babylon.proceduralTexture.js.map
  11684. var BABYLON;
  11685. (function (BABYLON) {
  11686. var WoodProceduralTexture = (function (_super) {
  11687. __extends(WoodProceduralTexture, _super);
  11688. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11689. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  11690. this._ampScale = 100.0;
  11691. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  11692. this.updateShaderUniforms();
  11693. this.refreshRate = 0;
  11694. }
  11695. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  11696. this.setFloat("ampScale", this._ampScale);
  11697. this.setColor3("woodColor", this._woodColor);
  11698. };
  11699. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  11700. get: function () {
  11701. return this._ampScale;
  11702. },
  11703. set: function (value) {
  11704. this._ampScale = value;
  11705. this.updateShaderUniforms();
  11706. },
  11707. enumerable: true,
  11708. configurable: true
  11709. });
  11710. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  11711. get: function () {
  11712. return this._woodColor;
  11713. },
  11714. set: function (value) {
  11715. this._woodColor = value;
  11716. this.updateShaderUniforms();
  11717. },
  11718. enumerable: true,
  11719. configurable: true
  11720. });
  11721. return WoodProceduralTexture;
  11722. })(BABYLON.ProceduralTexture);
  11723. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  11724. var FireProceduralTexture = (function (_super) {
  11725. __extends(FireProceduralTexture, _super);
  11726. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11727. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  11728. this._time = 0.0;
  11729. this._speed = new BABYLON.Vector2(0.5, 0.3);
  11730. this._shift = 1.6;
  11731. this._autoGenerateTime = true;
  11732. this._alphaThreshold = 0.5;
  11733. this._fireColors = FireProceduralTexture.RedFireColors;
  11734. this.updateShaderUniforms();
  11735. this.refreshRate = 1;
  11736. }
  11737. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  11738. this.setFloat("time", this._time);
  11739. this.setVector2("speed", this._speed);
  11740. this.setFloat("shift", this._shift);
  11741. this.setColor3("c1", this._fireColors[0]);
  11742. this.setColor3("c2", this._fireColors[1]);
  11743. this.setColor3("c3", this._fireColors[2]);
  11744. this.setColor3("c4", this._fireColors[3]);
  11745. this.setColor3("c5", this._fireColors[4]);
  11746. this.setColor3("c6", this._fireColors[5]);
  11747. this.setFloat("alphaThreshold", this._alphaThreshold);
  11748. };
  11749. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  11750. if (this._autoGenerateTime) {
  11751. this._time += this.getScene().getAnimationRatio() * 0.03;
  11752. this.updateShaderUniforms();
  11753. }
  11754. _super.prototype.render.call(this, useCameraPostProcess);
  11755. };
  11756. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  11757. get: function () {
  11758. return [
  11759. new BABYLON.Color3(0.5, 0.0, 1.0),
  11760. new BABYLON.Color3(0.9, 0.0, 1.0),
  11761. new BABYLON.Color3(0.2, 0.0, 1.0),
  11762. new BABYLON.Color3(1.0, 0.9, 1.0),
  11763. new BABYLON.Color3(0.1, 0.1, 1.0),
  11764. new BABYLON.Color3(0.9, 0.9, 1.0)
  11765. ];
  11766. },
  11767. enumerable: true,
  11768. configurable: true
  11769. });
  11770. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  11771. get: function () {
  11772. return [
  11773. new BABYLON.Color3(0.5, 1.0, 0.0),
  11774. new BABYLON.Color3(0.5, 1.0, 0.0),
  11775. new BABYLON.Color3(0.3, 0.4, 0.0),
  11776. new BABYLON.Color3(0.5, 1.0, 0.0),
  11777. new BABYLON.Color3(0.2, 0.0, 0.0),
  11778. new BABYLON.Color3(0.5, 1.0, 0.0)
  11779. ];
  11780. },
  11781. enumerable: true,
  11782. configurable: true
  11783. });
  11784. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  11785. get: function () {
  11786. return [
  11787. new BABYLON.Color3(0.5, 0.0, 0.1),
  11788. new BABYLON.Color3(0.9, 0.0, 0.0),
  11789. new BABYLON.Color3(0.2, 0.0, 0.0),
  11790. new BABYLON.Color3(1.0, 0.9, 0.0),
  11791. new BABYLON.Color3(0.1, 0.1, 0.1),
  11792. new BABYLON.Color3(0.9, 0.9, 0.9)
  11793. ];
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  11799. get: function () {
  11800. return [
  11801. new BABYLON.Color3(0.1, 0.0, 0.5),
  11802. new BABYLON.Color3(0.0, 0.0, 0.5),
  11803. new BABYLON.Color3(0.1, 0.0, 0.2),
  11804. new BABYLON.Color3(0.0, 0.0, 1.0),
  11805. new BABYLON.Color3(0.1, 0.2, 0.3),
  11806. new BABYLON.Color3(0.0, 0.2, 0.9)
  11807. ];
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  11813. get: function () {
  11814. return this._fireColors;
  11815. },
  11816. set: function (value) {
  11817. this._fireColors = value;
  11818. this.updateShaderUniforms();
  11819. },
  11820. enumerable: true,
  11821. configurable: true
  11822. });
  11823. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  11824. get: function () {
  11825. return this._time;
  11826. },
  11827. set: function (value) {
  11828. this._time = value;
  11829. this.updateShaderUniforms();
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  11835. get: function () {
  11836. return this._speed;
  11837. },
  11838. set: function (value) {
  11839. this._speed = value;
  11840. this.updateShaderUniforms();
  11841. },
  11842. enumerable: true,
  11843. configurable: true
  11844. });
  11845. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  11846. get: function () {
  11847. return this._shift;
  11848. },
  11849. set: function (value) {
  11850. this._shift = value;
  11851. this.updateShaderUniforms();
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  11857. get: function () {
  11858. return this._alphaThreshold;
  11859. },
  11860. set: function (value) {
  11861. this._alphaThreshold = value;
  11862. this.updateShaderUniforms();
  11863. },
  11864. enumerable: true,
  11865. configurable: true
  11866. });
  11867. return FireProceduralTexture;
  11868. })(BABYLON.ProceduralTexture);
  11869. BABYLON.FireProceduralTexture = FireProceduralTexture;
  11870. var CloudProceduralTexture = (function (_super) {
  11871. __extends(CloudProceduralTexture, _super);
  11872. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11873. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  11874. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  11875. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  11876. this.updateShaderUniforms();
  11877. this.refreshRate = 0;
  11878. }
  11879. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  11880. this.setColor3("skyColor", this._skyColor);
  11881. this.setColor3("cloudColor", this._cloudColor);
  11882. };
  11883. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  11884. get: function () {
  11885. return this._skyColor;
  11886. },
  11887. set: function (value) {
  11888. this._skyColor = value;
  11889. this.updateShaderUniforms();
  11890. },
  11891. enumerable: true,
  11892. configurable: true
  11893. });
  11894. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  11895. get: function () {
  11896. return this._cloudColor;
  11897. },
  11898. set: function (value) {
  11899. this._cloudColor = value;
  11900. this.updateShaderUniforms();
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. return CloudProceduralTexture;
  11906. })(BABYLON.ProceduralTexture);
  11907. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  11908. var GrassProceduralTexture = (function (_super) {
  11909. __extends(GrassProceduralTexture, _super);
  11910. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11911. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  11912. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  11913. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  11914. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  11915. this._groundColor = new BABYLON.Color3(1, 1, 1);
  11916. this._grassColors = [
  11917. new BABYLON.Color3(0.29, 0.38, 0.02),
  11918. new BABYLON.Color3(0.36, 0.49, 0.09),
  11919. new BABYLON.Color3(0.51, 0.6, 0.28)
  11920. ];
  11921. this.updateShaderUniforms();
  11922. this.refreshRate = 0;
  11923. }
  11924. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  11925. this.setColor3("herb1Color", this._grassColors[0]);
  11926. this.setColor3("herb2Color", this._grassColors[1]);
  11927. this.setColor3("herb3Color", this._grassColors[2]);
  11928. this.setColor3("groundColor", this._groundColor);
  11929. };
  11930. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  11931. get: function () {
  11932. return this._grassColors;
  11933. },
  11934. set: function (value) {
  11935. this._grassColors = value;
  11936. this.updateShaderUniforms();
  11937. },
  11938. enumerable: true,
  11939. configurable: true
  11940. });
  11941. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  11942. get: function () {
  11943. return this._groundColor;
  11944. },
  11945. set: function (value) {
  11946. this.groundColor = value;
  11947. this.updateShaderUniforms();
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. return GrassProceduralTexture;
  11953. })(BABYLON.ProceduralTexture);
  11954. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  11955. var RoadProceduralTexture = (function (_super) {
  11956. __extends(RoadProceduralTexture, _super);
  11957. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11958. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  11959. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  11960. this.updateShaderUniforms();
  11961. this.refreshRate = 0;
  11962. }
  11963. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  11964. this.setColor3("roadColor", this._roadColor);
  11965. };
  11966. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  11967. get: function () {
  11968. return this._roadColor;
  11969. },
  11970. set: function (value) {
  11971. this._roadColor = value;
  11972. this.updateShaderUniforms();
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. return RoadProceduralTexture;
  11978. })(BABYLON.ProceduralTexture);
  11979. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  11980. var BrickProceduralTexture = (function (_super) {
  11981. __extends(BrickProceduralTexture, _super);
  11982. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  11983. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  11984. this._numberOfBricksHeight = 15;
  11985. this._numberOfBricksWidth = 5;
  11986. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  11987. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  11988. this.updateShaderUniforms();
  11989. this.refreshRate = 0;
  11990. }
  11991. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  11992. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  11993. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  11994. this.setColor3("brickColor", this._brickColor);
  11995. this.setColor3("jointColor", this._jointColor);
  11996. };
  11997. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  11998. get: function () {
  11999. return this._numberOfBricksHeight;
  12000. },
  12001. enumerable: true,
  12002. configurable: true
  12003. });
  12004. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12005. set: function (value) {
  12006. this._numberOfBricksHeight = value;
  12007. this.updateShaderUniforms();
  12008. },
  12009. enumerable: true,
  12010. configurable: true
  12011. });
  12012. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12013. get: function () {
  12014. return this._numberOfBricksWidth;
  12015. },
  12016. set: function (value) {
  12017. this._numberOfBricksHeight = value;
  12018. this.updateShaderUniforms();
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12024. get: function () {
  12025. return this._jointColor;
  12026. },
  12027. set: function (value) {
  12028. this._jointColor = value;
  12029. this.updateShaderUniforms();
  12030. },
  12031. enumerable: true,
  12032. configurable: true
  12033. });
  12034. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12035. get: function () {
  12036. return this._brickColor;
  12037. },
  12038. set: function (value) {
  12039. this._brickColor = value;
  12040. this.updateShaderUniforms();
  12041. },
  12042. enumerable: true,
  12043. configurable: true
  12044. });
  12045. return BrickProceduralTexture;
  12046. })(BABYLON.ProceduralTexture);
  12047. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12048. var MarbleProceduralTexture = (function (_super) {
  12049. __extends(MarbleProceduralTexture, _super);
  12050. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12051. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12052. this._numberOfTilesHeight = 3;
  12053. this._numberOfTilesWidth = 3;
  12054. this._amplitude = 9.0;
  12055. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12056. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12057. this.updateShaderUniforms();
  12058. this.refreshRate = 0;
  12059. }
  12060. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12061. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12062. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12063. this.setFloat("amplitude", this._amplitude);
  12064. this.setColor3("marbleColor", this._marbleColor);
  12065. this.setColor3("jointColor", this._jointColor);
  12066. };
  12067. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12068. get: function () {
  12069. return this._numberOfTilesHeight;
  12070. },
  12071. set: function (value) {
  12072. this._numberOfTilesHeight = value;
  12073. this.updateShaderUniforms();
  12074. },
  12075. enumerable: true,
  12076. configurable: true
  12077. });
  12078. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12079. get: function () {
  12080. return this._numberOfTilesWidth;
  12081. },
  12082. set: function (value) {
  12083. this._numberOfTilesWidth = value;
  12084. this.updateShaderUniforms();
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  12090. get: function () {
  12091. return this._jointColor;
  12092. },
  12093. set: function (value) {
  12094. this._jointColor = value;
  12095. this.updateShaderUniforms();
  12096. },
  12097. enumerable: true,
  12098. configurable: true
  12099. });
  12100. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  12101. get: function () {
  12102. return this._marbleColor;
  12103. },
  12104. set: function (value) {
  12105. this._marbleColor = value;
  12106. this.updateShaderUniforms();
  12107. },
  12108. enumerable: true,
  12109. configurable: true
  12110. });
  12111. return MarbleProceduralTexture;
  12112. })(BABYLON.ProceduralTexture);
  12113. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  12114. })(BABYLON || (BABYLON = {}));
  12115. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  12116. var BABYLON;
  12117. (function (BABYLON) {
  12118. var CustomProceduralTexture = (function (_super) {
  12119. __extends(CustomProceduralTexture, _super);
  12120. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  12121. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  12122. this._animate = true;
  12123. this._time = 0;
  12124. this._texturePath = texturePath;
  12125. //Try to load json
  12126. this.loadJson(texturePath);
  12127. this.refreshRate = 1;
  12128. }
  12129. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  12130. var _this = this;
  12131. var that = this;
  12132. function noConfigFile() {
  12133. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShaderStore or DOM element");
  12134. try {
  12135. that.setFragment(that._texturePath);
  12136. }
  12137. catch (ex) {
  12138. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  12139. }
  12140. }
  12141. var configFileUrl = jsonUrl + "/config.json";
  12142. var xhr = new XMLHttpRequest();
  12143. xhr.open("GET", configFileUrl, true);
  12144. xhr.addEventListener("load", function () {
  12145. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  12146. try {
  12147. _this._config = JSON.parse(xhr.response);
  12148. _this.updateShaderUniforms();
  12149. _this.updateTextures();
  12150. _this.setFragment(_this._texturePath + "/custom");
  12151. _this._animate = _this._config.animate;
  12152. _this.refreshRate = _this._config.refreshrate;
  12153. }
  12154. catch (ex) {
  12155. noConfigFile();
  12156. }
  12157. }
  12158. else {
  12159. noConfigFile();
  12160. }
  12161. }, false);
  12162. xhr.addEventListener("error", function (event) {
  12163. noConfigFile();
  12164. }, false);
  12165. try {
  12166. xhr.send();
  12167. }
  12168. catch (ex) {
  12169. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  12170. }
  12171. };
  12172. CustomProceduralTexture.prototype.isReady = function () {
  12173. if (!_super.prototype.isReady.call(this)) {
  12174. return false;
  12175. }
  12176. for (var name in this._textures) {
  12177. var texture = this._textures[name];
  12178. if (!texture.isReady()) {
  12179. return false;
  12180. }
  12181. }
  12182. return true;
  12183. };
  12184. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12185. if (this._animate) {
  12186. this._time += this.getScene().getAnimationRatio() * 0.03;
  12187. this.updateShaderUniforms();
  12188. }
  12189. _super.prototype.render.call(this, useCameraPostProcess);
  12190. };
  12191. CustomProceduralTexture.prototype.updateTextures = function () {
  12192. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  12193. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  12194. }
  12195. };
  12196. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  12197. if (this._config) {
  12198. for (var j = 0; j < this._config.uniforms.length; j++) {
  12199. var uniform = this._config.uniforms[j];
  12200. switch (uniform.type) {
  12201. case "float":
  12202. this.setFloat(uniform.name, uniform.value);
  12203. break;
  12204. case "color3":
  12205. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  12206. break;
  12207. case "color4":
  12208. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  12209. break;
  12210. case "vector2":
  12211. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  12212. break;
  12213. case "vector3":
  12214. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  12215. break;
  12216. }
  12217. }
  12218. }
  12219. this.setFloat("time", this._time);
  12220. };
  12221. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  12222. get: function () {
  12223. return this._animate;
  12224. },
  12225. set: function (value) {
  12226. this._animate = value;
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. return CustomProceduralTexture;
  12232. })(BABYLON.ProceduralTexture);
  12233. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  12234. })(BABYLON || (BABYLON = {}));
  12235. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  12236. var BABYLON;
  12237. (function (BABYLON) {
  12238. var MirrorTexture = (function (_super) {
  12239. __extends(MirrorTexture, _super);
  12240. function MirrorTexture(name, size, scene, generateMipMaps) {
  12241. var _this = this;
  12242. _super.call(this, name, size, scene, generateMipMaps, true);
  12243. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  12244. this._transformMatrix = BABYLON.Matrix.Zero();
  12245. this._mirrorMatrix = BABYLON.Matrix.Zero();
  12246. this.onBeforeRender = function () {
  12247. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  12248. _this._savedViewMatrix = scene.getViewMatrix();
  12249. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  12250. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  12251. scene.clipPlane = _this.mirrorPlane;
  12252. scene.getEngine().cullBackFaces = false;
  12253. };
  12254. this.onAfterRender = function () {
  12255. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  12256. scene.getEngine().cullBackFaces = true;
  12257. delete scene.clipPlane;
  12258. };
  12259. }
  12260. MirrorTexture.prototype.clone = function () {
  12261. var textureSize = this.getSize();
  12262. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12263. // Base texture
  12264. newTexture.hasAlpha = this.hasAlpha;
  12265. newTexture.level = this.level;
  12266. // Mirror Texture
  12267. newTexture.mirrorPlane = this.mirrorPlane.clone();
  12268. newTexture.renderList = this.renderList.slice(0);
  12269. return newTexture;
  12270. };
  12271. return MirrorTexture;
  12272. })(BABYLON.RenderTargetTexture);
  12273. BABYLON.MirrorTexture = MirrorTexture;
  12274. })(BABYLON || (BABYLON = {}));
  12275. //# sourceMappingURL=babylon.mirrorTexture.js.map
  12276. var BABYLON;
  12277. (function (BABYLON) {
  12278. var DynamicTexture = (function (_super) {
  12279. __extends(DynamicTexture, _super);
  12280. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  12281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12282. _super.call(this, null, scene, !generateMipMaps);
  12283. this.name = name;
  12284. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12285. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12286. this._generateMipMaps = generateMipMaps;
  12287. if (options.getContext) {
  12288. this._canvas = options;
  12289. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12290. }
  12291. else {
  12292. this._canvas = document.createElement("canvas");
  12293. if (options.width) {
  12294. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  12295. }
  12296. else {
  12297. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  12298. }
  12299. }
  12300. var textureSize = this.getSize();
  12301. this._canvas.width = textureSize.width;
  12302. this._canvas.height = textureSize.height;
  12303. this._context = this._canvas.getContext("2d");
  12304. }
  12305. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  12306. get: function () {
  12307. return true;
  12308. },
  12309. enumerable: true,
  12310. configurable: true
  12311. });
  12312. DynamicTexture.prototype.scale = function (ratio) {
  12313. var textureSize = this.getSize();
  12314. textureSize.width *= ratio;
  12315. textureSize.height *= ratio;
  12316. this._canvas.width = textureSize.width;
  12317. this._canvas.height = textureSize.height;
  12318. this.releaseInternalTexture();
  12319. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  12320. };
  12321. DynamicTexture.prototype.getContext = function () {
  12322. return this._context;
  12323. };
  12324. DynamicTexture.prototype.clear = function () {
  12325. var size = this.getSize();
  12326. this._context.fillRect(0, 0, size.width, size.height);
  12327. };
  12328. DynamicTexture.prototype.update = function (invertY) {
  12329. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  12330. };
  12331. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  12332. if (update === void 0) { update = true; }
  12333. var size = this.getSize();
  12334. if (clearColor) {
  12335. this._context.fillStyle = clearColor;
  12336. this._context.fillRect(0, 0, size.width, size.height);
  12337. }
  12338. this._context.font = font;
  12339. if (x === null) {
  12340. var textSize = this._context.measureText(text);
  12341. x = (size.width - textSize.width) / 2;
  12342. }
  12343. this._context.fillStyle = color;
  12344. this._context.fillText(text, x, y);
  12345. if (update) {
  12346. this.update(invertY);
  12347. }
  12348. };
  12349. DynamicTexture.prototype.clone = function () {
  12350. var textureSize = this.getSize();
  12351. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12352. // Base texture
  12353. newTexture.hasAlpha = this.hasAlpha;
  12354. newTexture.level = this.level;
  12355. // Dynamic Texture
  12356. newTexture.wrapU = this.wrapU;
  12357. newTexture.wrapV = this.wrapV;
  12358. return newTexture;
  12359. };
  12360. return DynamicTexture;
  12361. })(BABYLON.Texture);
  12362. BABYLON.DynamicTexture = DynamicTexture;
  12363. })(BABYLON || (BABYLON = {}));
  12364. //# sourceMappingURL=babylon.dynamicTexture.js.map
  12365. var BABYLON;
  12366. (function (BABYLON) {
  12367. var VideoTexture = (function (_super) {
  12368. __extends(VideoTexture, _super);
  12369. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  12370. var _this = this;
  12371. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  12372. _super.call(this, null, scene, !generateMipMaps, invertY);
  12373. this._autoLaunch = true;
  12374. this.name = name;
  12375. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12376. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12377. var requiredWidth = size.width || size;
  12378. var requiredHeight = size.height || size;
  12379. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  12380. var textureSize = this.getSize();
  12381. this.video = document.createElement("video");
  12382. this.video.width = textureSize.width;
  12383. this.video.height = textureSize.height;
  12384. this.video.autoplay = false;
  12385. this.video.loop = true;
  12386. this.video.addEventListener("canplaythrough", function () {
  12387. if (_this._texture) {
  12388. _this._texture.isReady = true;
  12389. }
  12390. });
  12391. urls.forEach(function (url) {
  12392. var source = document.createElement("source");
  12393. source.src = url;
  12394. _this.video.appendChild(source);
  12395. });
  12396. this._lastUpdate = BABYLON.Tools.Now;
  12397. }
  12398. VideoTexture.prototype.update = function () {
  12399. if (this._autoLaunch) {
  12400. this._autoLaunch = false;
  12401. this.video.play();
  12402. }
  12403. var now = BABYLON.Tools.Now;
  12404. if (now - this._lastUpdate < 15) {
  12405. return false;
  12406. }
  12407. this._lastUpdate = now;
  12408. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  12409. return true;
  12410. };
  12411. return VideoTexture;
  12412. })(BABYLON.Texture);
  12413. BABYLON.VideoTexture = VideoTexture;
  12414. })(BABYLON || (BABYLON = {}));
  12415. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  12416. (function (BABYLON) {
  12417. var EffectFallbacks = (function () {
  12418. function EffectFallbacks() {
  12419. this._defines = {};
  12420. this._currentRank = 32;
  12421. this._maxRank = -1;
  12422. }
  12423. EffectFallbacks.prototype.addFallback = function (rank, define) {
  12424. if (!this._defines[rank]) {
  12425. if (rank < this._currentRank) {
  12426. this._currentRank = rank;
  12427. }
  12428. if (rank > this._maxRank) {
  12429. this._maxRank = rank;
  12430. }
  12431. this._defines[rank] = new Array();
  12432. }
  12433. this._defines[rank].push(define);
  12434. };
  12435. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  12436. get: function () {
  12437. return this._currentRank <= this._maxRank;
  12438. },
  12439. enumerable: true,
  12440. configurable: true
  12441. });
  12442. EffectFallbacks.prototype.reduce = function (currentDefines) {
  12443. var currentFallbacks = this._defines[this._currentRank];
  12444. for (var index = 0; index < currentFallbacks.length; index++) {
  12445. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  12446. }
  12447. this._currentRank++;
  12448. return currentDefines;
  12449. };
  12450. return EffectFallbacks;
  12451. })();
  12452. BABYLON.EffectFallbacks = EffectFallbacks;
  12453. var Effect = (function () {
  12454. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  12455. var _this = this;
  12456. this._isReady = false;
  12457. this._compilationError = "";
  12458. this._valueCache = [];
  12459. this._engine = engine;
  12460. this.name = baseName;
  12461. this.defines = defines;
  12462. this._uniformsNames = uniformsNames.concat(samplers);
  12463. this._samplers = samplers;
  12464. this._attributesNames = attributesNames;
  12465. this.onError = onError;
  12466. this.onCompiled = onCompiled;
  12467. var vertexSource;
  12468. var fragmentSource;
  12469. if (baseName.vertexElement) {
  12470. vertexSource = document.getElementById(baseName.vertexElement);
  12471. if (!vertexSource) {
  12472. vertexSource = baseName.vertexElement;
  12473. }
  12474. }
  12475. else {
  12476. vertexSource = baseName.vertex || baseName;
  12477. }
  12478. if (baseName.fragmentElement) {
  12479. fragmentSource = document.getElementById(baseName.fragmentElement);
  12480. if (!fragmentSource) {
  12481. fragmentSource = baseName.fragmentElement;
  12482. }
  12483. }
  12484. else {
  12485. fragmentSource = baseName.fragment || baseName;
  12486. }
  12487. this._loadVertexShader(vertexSource, function (vertexCode) {
  12488. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  12489. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  12490. });
  12491. });
  12492. }
  12493. // Properties
  12494. Effect.prototype.isReady = function () {
  12495. return this._isReady;
  12496. };
  12497. Effect.prototype.getProgram = function () {
  12498. return this._program;
  12499. };
  12500. Effect.prototype.getAttributesNames = function () {
  12501. return this._attributesNames;
  12502. };
  12503. Effect.prototype.getAttributeLocation = function (index) {
  12504. return this._attributes[index];
  12505. };
  12506. Effect.prototype.getAttributeLocationByName = function (name) {
  12507. var index = this._attributesNames.indexOf(name);
  12508. return this._attributes[index];
  12509. };
  12510. Effect.prototype.getAttributesCount = function () {
  12511. return this._attributes.length;
  12512. };
  12513. Effect.prototype.getUniformIndex = function (uniformName) {
  12514. return this._uniformsNames.indexOf(uniformName);
  12515. };
  12516. Effect.prototype.getUniform = function (uniformName) {
  12517. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  12518. };
  12519. Effect.prototype.getSamplers = function () {
  12520. return this._samplers;
  12521. };
  12522. Effect.prototype.getCompilationError = function () {
  12523. return this._compilationError;
  12524. };
  12525. // Methods
  12526. Effect.prototype._loadVertexShader = function (vertex, callback) {
  12527. // DOM element ?
  12528. if (vertex instanceof HTMLElement) {
  12529. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  12530. callback(vertexCode);
  12531. return;
  12532. }
  12533. // Is in local store ?
  12534. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  12535. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  12536. return;
  12537. }
  12538. var vertexShaderUrl;
  12539. if (vertex[0] === ".") {
  12540. vertexShaderUrl = vertex;
  12541. }
  12542. else {
  12543. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  12544. }
  12545. // Vertex shader
  12546. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  12547. };
  12548. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  12549. // DOM element ?
  12550. if (fragment instanceof HTMLElement) {
  12551. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  12552. callback(fragmentCode);
  12553. return;
  12554. }
  12555. // Is in local store ?
  12556. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  12557. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  12558. return;
  12559. }
  12560. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  12561. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  12562. return;
  12563. }
  12564. var fragmentShaderUrl;
  12565. if (fragment[0] === ".") {
  12566. fragmentShaderUrl = fragment;
  12567. }
  12568. else {
  12569. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  12570. }
  12571. // Fragment shader
  12572. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  12573. };
  12574. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  12575. try {
  12576. var engine = this._engine;
  12577. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  12578. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  12579. this._attributes = engine.getAttributes(this._program, attributesNames);
  12580. for (var index = 0; index < this._samplers.length; index++) {
  12581. var sampler = this.getUniform(this._samplers[index]);
  12582. if (sampler == null) {
  12583. this._samplers.splice(index, 1);
  12584. index--;
  12585. }
  12586. }
  12587. engine.bindSamplers(this);
  12588. this._isReady = true;
  12589. if (this.onCompiled) {
  12590. this.onCompiled(this);
  12591. }
  12592. }
  12593. catch (e) {
  12594. // Is it a problem with precision?
  12595. if (e.message.indexOf("highp") !== -1) {
  12596. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  12597. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  12598. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12599. return;
  12600. }
  12601. // Let's go through fallbacks then
  12602. if (fallbacks && fallbacks.isMoreFallbacks) {
  12603. defines = fallbacks.reduce(defines);
  12604. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  12605. }
  12606. else {
  12607. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  12608. BABYLON.Tools.Error("Defines: " + defines);
  12609. BABYLON.Tools.Error("Error: " + e.message);
  12610. this._compilationError = e.message;
  12611. if (this.onError) {
  12612. this.onError(this, this._compilationError);
  12613. }
  12614. }
  12615. }
  12616. };
  12617. Effect.prototype._bindTexture = function (channel, texture) {
  12618. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  12619. };
  12620. Effect.prototype.setTexture = function (channel, texture) {
  12621. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  12622. };
  12623. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  12624. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  12625. };
  12626. //public _cacheMatrix(uniformName, matrix) {
  12627. // if (!this._valueCache[uniformName]) {
  12628. // this._valueCache[uniformName] = new BABYLON.Matrix();
  12629. // }
  12630. // for (var index = 0; index < 16; index++) {
  12631. // this._valueCache[uniformName].m[index] = matrix.m[index];
  12632. // }
  12633. //};
  12634. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  12635. if (!this._valueCache[uniformName]) {
  12636. this._valueCache[uniformName] = [x, y];
  12637. return;
  12638. }
  12639. this._valueCache[uniformName][0] = x;
  12640. this._valueCache[uniformName][1] = y;
  12641. };
  12642. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  12643. if (!this._valueCache[uniformName]) {
  12644. this._valueCache[uniformName] = [x, y, z];
  12645. return;
  12646. }
  12647. this._valueCache[uniformName][0] = x;
  12648. this._valueCache[uniformName][1] = y;
  12649. this._valueCache[uniformName][2] = z;
  12650. };
  12651. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  12652. if (!this._valueCache[uniformName]) {
  12653. this._valueCache[uniformName] = [x, y, z, w];
  12654. return;
  12655. }
  12656. this._valueCache[uniformName][0] = x;
  12657. this._valueCache[uniformName][1] = y;
  12658. this._valueCache[uniformName][2] = z;
  12659. this._valueCache[uniformName][3] = w;
  12660. };
  12661. Effect.prototype.setArray = function (uniformName, array) {
  12662. this._engine.setArray(this.getUniform(uniformName), array);
  12663. return this;
  12664. };
  12665. Effect.prototype.setMatrices = function (uniformName, matrices) {
  12666. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  12667. return this;
  12668. };
  12669. Effect.prototype.setMatrix = function (uniformName, matrix) {
  12670. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  12671. // return;
  12672. //this._cacheMatrix(uniformName, matrix);
  12673. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  12674. return this;
  12675. };
  12676. Effect.prototype.setFloat = function (uniformName, value) {
  12677. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  12678. return this;
  12679. this._valueCache[uniformName] = value;
  12680. this._engine.setFloat(this.getUniform(uniformName), value);
  12681. return this;
  12682. };
  12683. Effect.prototype.setBool = function (uniformName, bool) {
  12684. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  12685. return this;
  12686. this._valueCache[uniformName] = bool;
  12687. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  12688. return this;
  12689. };
  12690. Effect.prototype.setVector2 = function (uniformName, vector2) {
  12691. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  12692. return this;
  12693. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  12694. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  12695. return this;
  12696. };
  12697. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  12698. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  12699. return this;
  12700. this._cacheFloat2(uniformName, x, y);
  12701. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  12702. return this;
  12703. };
  12704. Effect.prototype.setVector3 = function (uniformName, vector3) {
  12705. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  12706. return this;
  12707. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  12708. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  12709. return this;
  12710. };
  12711. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  12712. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  12713. return this;
  12714. this._cacheFloat3(uniformName, x, y, z);
  12715. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  12716. return this;
  12717. };
  12718. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  12719. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  12720. return this;
  12721. this._cacheFloat4(uniformName, x, y, z, w);
  12722. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  12723. return this;
  12724. };
  12725. Effect.prototype.setColor3 = function (uniformName, color3) {
  12726. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  12727. return this;
  12728. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  12729. this._engine.setColor3(this.getUniform(uniformName), color3);
  12730. return this;
  12731. };
  12732. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  12733. 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)
  12734. return this;
  12735. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  12736. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  12737. return this;
  12738. };
  12739. // Statics
  12740. 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}",
  12741. 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}",
  12742. 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}",
  12743. 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}",
  12744. 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}",
  12745. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  12746. 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}",
  12747. 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}",
  12748. 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}",
  12749. 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}",
  12750. 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}",
  12751. 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}",
  12752. 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}",
  12753. 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}",
  12754. 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}",
  12755. 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}",
  12756. 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}",
  12757. 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}",
  12758. 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}",
  12759. 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}",
  12760. 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}",
  12761. 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}",
  12762. 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}",
  12763. 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}",
  12764. 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}",
  12765. 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}",
  12766. 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}",
  12767. 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}",
  12768. 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}",
  12769. 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}",
  12770. 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}",
  12771. 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}",
  12772. 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}",
  12773. 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}",
  12774. 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}",
  12775. 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}",
  12776. 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}",
  12777. };
  12778. return Effect;
  12779. })();
  12780. BABYLON.Effect = Effect;
  12781. })(BABYLON || (BABYLON = {}));
  12782. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  12783. (function (BABYLON) {
  12784. var Material = (function () {
  12785. function Material(name, scene, doNotAdd) {
  12786. this.name = name;
  12787. this.checkReadyOnEveryCall = true;
  12788. this.checkReadyOnlyOnce = false;
  12789. this.state = "";
  12790. this.alpha = 1.0;
  12791. this.backFaceCulling = true;
  12792. this._wasPreviouslyReady = false;
  12793. this._fillMode = Material.TriangleFillMode;
  12794. this.pointSize = 1.0;
  12795. this.id = name;
  12796. this._scene = scene;
  12797. if (!doNotAdd) {
  12798. scene.materials.push(this);
  12799. }
  12800. }
  12801. Object.defineProperty(Material, "TriangleFillMode", {
  12802. get: function () {
  12803. return Material._TriangleFillMode;
  12804. },
  12805. enumerable: true,
  12806. configurable: true
  12807. });
  12808. Object.defineProperty(Material, "WireFrameFillMode", {
  12809. get: function () {
  12810. return Material._WireFrameFillMode;
  12811. },
  12812. enumerable: true,
  12813. configurable: true
  12814. });
  12815. Object.defineProperty(Material, "PointFillMode", {
  12816. get: function () {
  12817. return Material._PointFillMode;
  12818. },
  12819. enumerable: true,
  12820. configurable: true
  12821. });
  12822. Object.defineProperty(Material.prototype, "wireframe", {
  12823. get: function () {
  12824. return this._fillMode === Material.WireFrameFillMode;
  12825. },
  12826. set: function (value) {
  12827. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  12828. },
  12829. enumerable: true,
  12830. configurable: true
  12831. });
  12832. Object.defineProperty(Material.prototype, "pointsCloud", {
  12833. get: function () {
  12834. return this._fillMode === Material.PointFillMode;
  12835. },
  12836. set: function (value) {
  12837. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  12838. },
  12839. enumerable: true,
  12840. configurable: true
  12841. });
  12842. Object.defineProperty(Material.prototype, "fillMode", {
  12843. get: function () {
  12844. return this._fillMode;
  12845. },
  12846. set: function (value) {
  12847. this._fillMode = value;
  12848. },
  12849. enumerable: true,
  12850. configurable: true
  12851. });
  12852. Material.prototype.isReady = function (mesh, useInstances) {
  12853. return true;
  12854. };
  12855. Material.prototype.getEffect = function () {
  12856. return this._effect;
  12857. };
  12858. Material.prototype.getScene = function () {
  12859. return this._scene;
  12860. };
  12861. Material.prototype.needAlphaBlending = function () {
  12862. return (this.alpha < 1.0);
  12863. };
  12864. Material.prototype.needAlphaTesting = function () {
  12865. return false;
  12866. };
  12867. Material.prototype.getAlphaTestTexture = function () {
  12868. return null;
  12869. };
  12870. Material.prototype.trackCreation = function (onCompiled, onError) {
  12871. };
  12872. Material.prototype._preBind = function () {
  12873. var engine = this._scene.getEngine();
  12874. engine.enableEffect(this._effect);
  12875. engine.setState(this.backFaceCulling);
  12876. };
  12877. Material.prototype.bind = function (world, mesh) {
  12878. this._scene._cachedMaterial = this;
  12879. if (this.onBind) {
  12880. this.onBind(this);
  12881. }
  12882. };
  12883. Material.prototype.bindOnlyWorldMatrix = function (world) {
  12884. };
  12885. Material.prototype.unbind = function () {
  12886. };
  12887. Material.prototype.dispose = function (forceDisposeEffect) {
  12888. // Remove from scene
  12889. var index = this._scene.materials.indexOf(this);
  12890. this._scene.materials.splice(index, 1);
  12891. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  12892. if (forceDisposeEffect && this._effect) {
  12893. this._scene.getEngine()._releaseEffect(this._effect);
  12894. this._effect = null;
  12895. }
  12896. // Callback
  12897. if (this.onDispose) {
  12898. this.onDispose();
  12899. }
  12900. };
  12901. Material._TriangleFillMode = 0;
  12902. Material._WireFrameFillMode = 1;
  12903. Material._PointFillMode = 2;
  12904. return Material;
  12905. })();
  12906. BABYLON.Material = Material;
  12907. })(BABYLON || (BABYLON = {}));
  12908. //# sourceMappingURL=babylon.material.js.map
  12909. var BABYLON;
  12910. (function (BABYLON) {
  12911. var maxSimultaneousLights = 4;
  12912. var FresnelParameters = (function () {
  12913. function FresnelParameters() {
  12914. this.isEnabled = true;
  12915. this.leftColor = BABYLON.Color3.White();
  12916. this.rightColor = BABYLON.Color3.Black();
  12917. this.bias = 0;
  12918. this.power = 1;
  12919. }
  12920. return FresnelParameters;
  12921. })();
  12922. BABYLON.FresnelParameters = FresnelParameters;
  12923. var StandardMaterial = (function (_super) {
  12924. __extends(StandardMaterial, _super);
  12925. function StandardMaterial(name, scene) {
  12926. var _this = this;
  12927. _super.call(this, name, scene);
  12928. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  12929. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  12930. this.specularColor = new BABYLON.Color3(1, 1, 1);
  12931. this.specularPower = 64;
  12932. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  12933. this.useAlphaFromDiffuseTexture = false;
  12934. this.useSpecularOverAlpha = true;
  12935. this.fogEnabled = true;
  12936. this._cachedDefines = null;
  12937. this._renderTargets = new BABYLON.SmartArray(16);
  12938. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  12939. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  12940. this._scaledDiffuse = new BABYLON.Color3();
  12941. this._scaledSpecular = new BABYLON.Color3();
  12942. this.getRenderTargetTextures = function () {
  12943. _this._renderTargets.reset();
  12944. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  12945. _this._renderTargets.push(_this.reflectionTexture);
  12946. }
  12947. return _this._renderTargets;
  12948. };
  12949. }
  12950. StandardMaterial.prototype.needAlphaBlending = function () {
  12951. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  12952. };
  12953. StandardMaterial.prototype.needAlphaTesting = function () {
  12954. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  12955. };
  12956. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  12957. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  12958. };
  12959. StandardMaterial.prototype.getAlphaTestTexture = function () {
  12960. return this.diffuseTexture;
  12961. };
  12962. // Methods
  12963. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  12964. if (this.checkReadyOnlyOnce) {
  12965. if (this._wasPreviouslyReady) {
  12966. return true;
  12967. }
  12968. }
  12969. var scene = this.getScene();
  12970. if (!this.checkReadyOnEveryCall) {
  12971. if (this._renderId === scene.getRenderId()) {
  12972. return true;
  12973. }
  12974. }
  12975. var engine = scene.getEngine();
  12976. var defines = [];
  12977. var fallbacks = new BABYLON.EffectFallbacks();
  12978. // Textures
  12979. if (scene.texturesEnabled) {
  12980. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  12981. if (!this.diffuseTexture.isReady()) {
  12982. return false;
  12983. }
  12984. else {
  12985. defines.push("#define DIFFUSE");
  12986. }
  12987. }
  12988. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  12989. if (!this.ambientTexture.isReady()) {
  12990. return false;
  12991. }
  12992. else {
  12993. defines.push("#define AMBIENT");
  12994. }
  12995. }
  12996. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  12997. if (!this.opacityTexture.isReady()) {
  12998. return false;
  12999. }
  13000. else {
  13001. defines.push("#define OPACITY");
  13002. if (this.opacityTexture.getAlphaFromRGB) {
  13003. defines.push("#define OPACITYRGB");
  13004. }
  13005. }
  13006. }
  13007. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13008. if (!this.reflectionTexture.isReady()) {
  13009. return false;
  13010. }
  13011. else {
  13012. defines.push("#define REFLECTION");
  13013. fallbacks.addFallback(0, "REFLECTION");
  13014. }
  13015. }
  13016. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13017. if (!this.emissiveTexture.isReady()) {
  13018. return false;
  13019. }
  13020. else {
  13021. defines.push("#define EMISSIVE");
  13022. }
  13023. }
  13024. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13025. if (!this.specularTexture.isReady()) {
  13026. return false;
  13027. }
  13028. else {
  13029. defines.push("#define SPECULAR");
  13030. fallbacks.addFallback(0, "SPECULAR");
  13031. }
  13032. }
  13033. }
  13034. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13035. if (!this.bumpTexture.isReady()) {
  13036. return false;
  13037. }
  13038. else {
  13039. defines.push("#define BUMP");
  13040. fallbacks.addFallback(0, "BUMP");
  13041. }
  13042. }
  13043. // Effect
  13044. if (this.useSpecularOverAlpha) {
  13045. defines.push("#define SPECULAROVERALPHA");
  13046. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13047. }
  13048. if (scene.clipPlane) {
  13049. defines.push("#define CLIPPLANE");
  13050. }
  13051. if (engine.getAlphaTesting()) {
  13052. defines.push("#define ALPHATEST");
  13053. }
  13054. if (this._shouldUseAlphaFromDiffuseTexture()) {
  13055. defines.push("#define ALPHAFROMDIFFUSE");
  13056. }
  13057. // Point size
  13058. if (this.pointsCloud || scene.forcePointsCloud) {
  13059. defines.push("#define POINTSIZE");
  13060. }
  13061. // Fog
  13062. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  13063. defines.push("#define FOG");
  13064. fallbacks.addFallback(1, "FOG");
  13065. }
  13066. var shadowsActivated = false;
  13067. var lightIndex = 0;
  13068. if (scene.lightsEnabled) {
  13069. for (var index = 0; index < scene.lights.length; index++) {
  13070. var light = scene.lights[index];
  13071. if (!light.isEnabled()) {
  13072. continue;
  13073. }
  13074. // Excluded check
  13075. if (light._excludedMeshesIds.length > 0) {
  13076. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  13077. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  13078. if (excludedMesh) {
  13079. light.excludedMeshes.push(excludedMesh);
  13080. }
  13081. }
  13082. light._excludedMeshesIds = [];
  13083. }
  13084. // Included check
  13085. if (light._includedOnlyMeshesIds.length > 0) {
  13086. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  13087. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  13088. if (includedOnlyMesh) {
  13089. light.includedOnlyMeshes.push(includedOnlyMesh);
  13090. }
  13091. }
  13092. light._includedOnlyMeshesIds = [];
  13093. }
  13094. if (!light.canAffectMesh(mesh)) {
  13095. continue;
  13096. }
  13097. defines.push("#define LIGHT" + lightIndex);
  13098. if (lightIndex > 0) {
  13099. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  13100. }
  13101. var type;
  13102. if (light instanceof BABYLON.SpotLight) {
  13103. type = "#define SPOTLIGHT" + lightIndex;
  13104. }
  13105. else if (light instanceof BABYLON.HemisphericLight) {
  13106. type = "#define HEMILIGHT" + lightIndex;
  13107. }
  13108. else {
  13109. type = "#define POINTDIRLIGHT" + lightIndex;
  13110. }
  13111. defines.push(type);
  13112. if (lightIndex > 0) {
  13113. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  13114. }
  13115. // Shadows
  13116. if (scene.shadowsEnabled) {
  13117. var shadowGenerator = light.getShadowGenerator();
  13118. if (mesh && mesh.receiveShadows && shadowGenerator) {
  13119. defines.push("#define SHADOW" + lightIndex);
  13120. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  13121. if (!shadowsActivated) {
  13122. defines.push("#define SHADOWS");
  13123. shadowsActivated = true;
  13124. }
  13125. if (shadowGenerator.useVarianceShadowMap) {
  13126. defines.push("#define SHADOWVSM" + lightIndex);
  13127. if (lightIndex > 0) {
  13128. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  13129. }
  13130. }
  13131. if (shadowGenerator.usePoissonSampling) {
  13132. defines.push("#define SHADOWPCF" + lightIndex);
  13133. if (lightIndex > 0) {
  13134. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  13135. }
  13136. }
  13137. }
  13138. }
  13139. lightIndex++;
  13140. if (lightIndex === maxSimultaneousLights)
  13141. break;
  13142. }
  13143. }
  13144. if (StandardMaterial.FresnelEnabled) {
  13145. // Fresnel
  13146. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13147. var fresnelRank = 1;
  13148. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13149. defines.push("#define DIFFUSEFRESNEL");
  13150. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  13151. fresnelRank++;
  13152. }
  13153. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13154. defines.push("#define OPACITYFRESNEL");
  13155. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  13156. fresnelRank++;
  13157. }
  13158. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13159. defines.push("#define REFLECTIONFRESNEL");
  13160. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  13161. fresnelRank++;
  13162. }
  13163. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13164. defines.push("#define EMISSIVEFRESNEL");
  13165. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  13166. fresnelRank++;
  13167. }
  13168. defines.push("#define FRESNEL");
  13169. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  13170. }
  13171. }
  13172. // Attribs
  13173. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  13174. if (mesh) {
  13175. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13176. attribs.push(BABYLON.VertexBuffer.UVKind);
  13177. defines.push("#define UV1");
  13178. }
  13179. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13180. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13181. defines.push("#define UV2");
  13182. }
  13183. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  13184. attribs.push(BABYLON.VertexBuffer.ColorKind);
  13185. defines.push("#define VERTEXCOLOR");
  13186. if (mesh.hasVertexAlpha) {
  13187. defines.push("#define VERTEXALPHA");
  13188. }
  13189. }
  13190. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13193. defines.push("#define BONES");
  13194. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13195. defines.push("#define BONES4");
  13196. fallbacks.addFallback(0, "BONES4");
  13197. }
  13198. // Instances
  13199. if (useInstances) {
  13200. defines.push("#define INSTANCES");
  13201. attribs.push("world0");
  13202. attribs.push("world1");
  13203. attribs.push("world2");
  13204. attribs.push("world3");
  13205. }
  13206. }
  13207. // Get correct effect
  13208. var join = defines.join("\n");
  13209. if (this._cachedDefines !== join) {
  13210. this._cachedDefines = join;
  13211. scene.resetCachedMaterial();
  13212. // Legacy browser patch
  13213. var shaderName = "default";
  13214. if (!scene.getEngine().getCaps().standardDerivatives) {
  13215. shaderName = "legacydefault";
  13216. }
  13217. this._effect = scene.getEngine().createEffect(shaderName, attribs, ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor", "vLightData0", "vLightDiffuse0", "vLightSpecular0", "vLightDirection0", "vLightGround0", "lightMatrix0", "vLightData1", "vLightDiffuse1", "vLightSpecular1", "vLightDirection1", "vLightGround1", "lightMatrix1", "vLightData2", "vLightDiffuse2", "vLightSpecular2", "vLightDirection2", "vLightGround2", "lightMatrix2", "vLightData3", "vLightDiffuse3", "vLightSpecular3", "vLightDirection3", "vLightGround3", "lightMatrix3", "vFogInfos", "vFogColor", "pointSize", "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "mBones", "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "darkness0", "darkness1", "darkness2", "darkness3", "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor"], ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "shadowSampler0", "shadowSampler1", "shadowSampler2", "shadowSampler3"], join, fallbacks, this.onCompiled, this.onError);
  13218. }
  13219. if (!this._effect.isReady()) {
  13220. return false;
  13221. }
  13222. this._renderId = scene.getRenderId();
  13223. this._wasPreviouslyReady = true;
  13224. return true;
  13225. };
  13226. StandardMaterial.prototype.unbind = function () {
  13227. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  13228. this._effect.setTexture("reflection2DSampler", null);
  13229. }
  13230. };
  13231. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  13232. this._effect.setMatrix("world", world);
  13233. };
  13234. StandardMaterial.prototype.bind = function (world, mesh) {
  13235. var scene = this.getScene();
  13236. // Matrices
  13237. this.bindOnlyWorldMatrix(world);
  13238. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  13239. // Bones
  13240. if (mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  13241. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  13242. }
  13243. if (scene.getCachedMaterial() !== this) {
  13244. if (StandardMaterial.FresnelEnabled) {
  13245. // Fresnel
  13246. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  13247. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  13248. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  13249. }
  13250. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  13251. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  13252. }
  13253. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  13254. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  13255. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  13256. }
  13257. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  13258. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  13259. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  13260. }
  13261. }
  13262. // Textures
  13263. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13264. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  13265. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  13266. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  13267. }
  13268. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13269. this._effect.setTexture("ambientSampler", this.ambientTexture);
  13270. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  13271. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  13272. }
  13273. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13274. this._effect.setTexture("opacitySampler", this.opacityTexture);
  13275. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  13276. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  13277. }
  13278. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13279. if (this.reflectionTexture.isCube) {
  13280. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  13281. }
  13282. else {
  13283. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  13284. }
  13285. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  13286. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  13287. }
  13288. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13289. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  13290. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  13291. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  13292. }
  13293. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13294. this._effect.setTexture("specularSampler", this.specularTexture);
  13295. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  13296. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  13297. }
  13298. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  13299. this._effect.setTexture("bumpSampler", this.bumpTexture);
  13300. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  13301. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  13302. }
  13303. // Clip plane
  13304. if (scene.clipPlane) {
  13305. var clipPlane = scene.clipPlane;
  13306. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  13307. }
  13308. // Point size
  13309. if (this.pointsCloud) {
  13310. this._effect.setFloat("pointSize", this.pointSize);
  13311. }
  13312. // Colors
  13313. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  13314. // Scaling down color according to emissive
  13315. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13316. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13317. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13318. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  13319. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  13320. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  13321. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  13322. }
  13323. // Scaling down color according to emissive
  13324. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  13325. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  13326. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  13327. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  13328. if (scene.lightsEnabled) {
  13329. var lightIndex = 0;
  13330. for (var index = 0; index < scene.lights.length; index++) {
  13331. var light = scene.lights[index];
  13332. if (!light.isEnabled()) {
  13333. continue;
  13334. }
  13335. if (!light.canAffectMesh(mesh)) {
  13336. continue;
  13337. }
  13338. if (light instanceof BABYLON.PointLight) {
  13339. // Point Light
  13340. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13341. }
  13342. else if (light instanceof BABYLON.DirectionalLight) {
  13343. // Directional Light
  13344. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  13345. }
  13346. else if (light instanceof BABYLON.SpotLight) {
  13347. // Spot Light
  13348. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  13349. }
  13350. else if (light instanceof BABYLON.HemisphericLight) {
  13351. // Hemispheric Light
  13352. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  13353. }
  13354. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  13355. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  13356. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  13357. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  13358. // Shadows
  13359. if (scene.shadowsEnabled) {
  13360. var shadowGenerator = light.getShadowGenerator();
  13361. if (mesh.receiveShadows && shadowGenerator) {
  13362. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  13363. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  13364. this._effect.setFloat("darkness" + lightIndex, shadowGenerator.getDarkness());
  13365. }
  13366. }
  13367. lightIndex++;
  13368. if (lightIndex === maxSimultaneousLights)
  13369. break;
  13370. }
  13371. }
  13372. // View
  13373. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  13374. this._effect.setMatrix("view", scene.getViewMatrix());
  13375. }
  13376. // Fog
  13377. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  13378. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  13379. this._effect.setColor3("vFogColor", scene.fogColor);
  13380. }
  13381. _super.prototype.bind.call(this, world, mesh);
  13382. };
  13383. StandardMaterial.prototype.getAnimatables = function () {
  13384. var results = [];
  13385. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  13386. results.push(this.diffuseTexture);
  13387. }
  13388. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  13389. results.push(this.ambientTexture);
  13390. }
  13391. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  13392. results.push(this.opacityTexture);
  13393. }
  13394. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  13395. results.push(this.reflectionTexture);
  13396. }
  13397. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  13398. results.push(this.emissiveTexture);
  13399. }
  13400. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  13401. results.push(this.specularTexture);
  13402. }
  13403. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  13404. results.push(this.bumpTexture);
  13405. }
  13406. return results;
  13407. };
  13408. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  13409. if (this.diffuseTexture) {
  13410. this.diffuseTexture.dispose();
  13411. }
  13412. if (this.ambientTexture) {
  13413. this.ambientTexture.dispose();
  13414. }
  13415. if (this.opacityTexture) {
  13416. this.opacityTexture.dispose();
  13417. }
  13418. if (this.reflectionTexture) {
  13419. this.reflectionTexture.dispose();
  13420. }
  13421. if (this.emissiveTexture) {
  13422. this.emissiveTexture.dispose();
  13423. }
  13424. if (this.specularTexture) {
  13425. this.specularTexture.dispose();
  13426. }
  13427. if (this.bumpTexture) {
  13428. this.bumpTexture.dispose();
  13429. }
  13430. _super.prototype.dispose.call(this, forceDisposeEffect);
  13431. };
  13432. StandardMaterial.prototype.clone = function (name) {
  13433. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  13434. // Base material
  13435. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  13436. newStandardMaterial.alpha = this.alpha;
  13437. newStandardMaterial.fillMode = this.fillMode;
  13438. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  13439. // Standard material
  13440. if (this.diffuseTexture && this.diffuseTexture.clone) {
  13441. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  13442. }
  13443. if (this.ambientTexture && this.ambientTexture.clone) {
  13444. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  13445. }
  13446. if (this.opacityTexture && this.opacityTexture.clone) {
  13447. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  13448. }
  13449. if (this.reflectionTexture && this.reflectionTexture.clone) {
  13450. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  13451. }
  13452. if (this.emissiveTexture && this.emissiveTexture.clone) {
  13453. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  13454. }
  13455. if (this.specularTexture && this.specularTexture.clone) {
  13456. newStandardMaterial.specularTexture = this.specularTexture.clone();
  13457. }
  13458. if (this.bumpTexture && this.bumpTexture.clone) {
  13459. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  13460. }
  13461. newStandardMaterial.ambientColor = this.ambientColor.clone();
  13462. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  13463. newStandardMaterial.specularColor = this.specularColor.clone();
  13464. newStandardMaterial.specularPower = this.specularPower;
  13465. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  13466. return newStandardMaterial;
  13467. };
  13468. // Statics
  13469. // Flags used to enable or disable a type of texture for all Standard Materials
  13470. StandardMaterial.DiffuseTextureEnabled = true;
  13471. StandardMaterial.AmbientTextureEnabled = true;
  13472. StandardMaterial.OpacityTextureEnabled = true;
  13473. StandardMaterial.ReflectionTextureEnabled = true;
  13474. StandardMaterial.EmissiveTextureEnabled = true;
  13475. StandardMaterial.SpecularTextureEnabled = true;
  13476. StandardMaterial.BumpTextureEnabled = true;
  13477. StandardMaterial.FresnelEnabled = true;
  13478. return StandardMaterial;
  13479. })(BABYLON.Material);
  13480. BABYLON.StandardMaterial = StandardMaterial;
  13481. })(BABYLON || (BABYLON = {}));
  13482. //# sourceMappingURL=babylon.standardMaterial.js.map
  13483. var BABYLON;
  13484. (function (BABYLON) {
  13485. var MultiMaterial = (function (_super) {
  13486. __extends(MultiMaterial, _super);
  13487. function MultiMaterial(name, scene) {
  13488. _super.call(this, name, scene, true);
  13489. this.subMaterials = new Array();
  13490. scene.multiMaterials.push(this);
  13491. }
  13492. // Properties
  13493. MultiMaterial.prototype.getSubMaterial = function (index) {
  13494. if (index < 0 || index >= this.subMaterials.length) {
  13495. return this.getScene().defaultMaterial;
  13496. }
  13497. return this.subMaterials[index];
  13498. };
  13499. // Methods
  13500. MultiMaterial.prototype.isReady = function (mesh) {
  13501. for (var index = 0; index < this.subMaterials.length; index++) {
  13502. var subMaterial = this.subMaterials[index];
  13503. if (subMaterial) {
  13504. if (!this.subMaterials[index].isReady(mesh)) {
  13505. return false;
  13506. }
  13507. }
  13508. }
  13509. return true;
  13510. };
  13511. return MultiMaterial;
  13512. })(BABYLON.Material);
  13513. BABYLON.MultiMaterial = MultiMaterial;
  13514. })(BABYLON || (BABYLON = {}));
  13515. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  13516. (function (BABYLON) {
  13517. var Database = (function () {
  13518. function Database(urlToScene, callbackManifestChecked) {
  13519. // Handling various flavors of prefixed version of IndexedDB
  13520. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  13521. this.callbackManifestChecked = callbackManifestChecked;
  13522. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  13523. this.db = null;
  13524. this.enableSceneOffline = false;
  13525. this.enableTexturesOffline = false;
  13526. this.manifestVersionFound = 0;
  13527. this.mustUpdateRessources = false;
  13528. this.hasReachedQuota = false;
  13529. this.checkManifestFile();
  13530. }
  13531. Database.prototype.checkManifestFile = function () {
  13532. var _this = this;
  13533. function noManifestFile() {
  13534. BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  13535. that.enableSceneOffline = false;
  13536. that.enableTexturesOffline = false;
  13537. that.callbackManifestChecked(false);
  13538. }
  13539. var that = this;
  13540. var manifestURL = this.currentSceneUrl + ".manifest";
  13541. var xhr = new XMLHttpRequest();
  13542. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  13543. xhr.open("GET", manifestURLTimeStamped, true);
  13544. xhr.addEventListener("load", function () {
  13545. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13546. try {
  13547. var manifestFile = JSON.parse(xhr.response);
  13548. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  13549. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  13550. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  13551. _this.manifestVersionFound = manifestFile.version;
  13552. }
  13553. if (_this.callbackManifestChecked) {
  13554. _this.callbackManifestChecked(true);
  13555. }
  13556. }
  13557. catch (ex) {
  13558. noManifestFile();
  13559. }
  13560. }
  13561. else {
  13562. noManifestFile();
  13563. }
  13564. }, false);
  13565. xhr.addEventListener("error", function (event) {
  13566. noManifestFile();
  13567. }, false);
  13568. try {
  13569. xhr.send();
  13570. }
  13571. catch (ex) {
  13572. BABYLON.Tools.Error("Error on XHR send request.");
  13573. that.callbackManifestChecked(false);
  13574. }
  13575. };
  13576. Database.prototype.openAsync = function (successCallback, errorCallback) {
  13577. var _this = this;
  13578. function handleError() {
  13579. that.isSupported = false;
  13580. if (errorCallback)
  13581. errorCallback();
  13582. }
  13583. var that = this;
  13584. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  13585. // Your browser doesn't support IndexedDB
  13586. this.isSupported = false;
  13587. if (errorCallback)
  13588. errorCallback();
  13589. }
  13590. else {
  13591. // If the DB hasn't been opened or created yet
  13592. if (!this.db) {
  13593. this.hasReachedQuota = false;
  13594. this.isSupported = true;
  13595. var request = this.idbFactory.open("babylonjs", 1);
  13596. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  13597. request.onerror = function (event) {
  13598. handleError();
  13599. };
  13600. // executes when a version change transaction cannot complete due to other active transactions
  13601. request.onblocked = function (event) {
  13602. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  13603. handleError();
  13604. };
  13605. // DB has been opened successfully
  13606. request.onsuccess = function (event) {
  13607. _this.db = request.result;
  13608. successCallback();
  13609. };
  13610. // Initialization of the DB. Creating Scenes & Textures stores
  13611. request.onupgradeneeded = function (event) {
  13612. _this.db = (event.target).result;
  13613. try {
  13614. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  13615. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  13616. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  13617. }
  13618. catch (ex) {
  13619. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  13620. handleError();
  13621. }
  13622. };
  13623. }
  13624. else {
  13625. if (successCallback)
  13626. successCallback();
  13627. }
  13628. }
  13629. };
  13630. Database.prototype.loadImageFromDB = function (url, image) {
  13631. var _this = this;
  13632. var completeURL = BABYLON.Database.ReturnFullUrlLocation(url);
  13633. var saveAndLoadImage = function () {
  13634. if (!_this.hasReachedQuota && _this.db !== null) {
  13635. // the texture is not yet in the DB, let's try to save it
  13636. _this._saveImageIntoDBAsync(completeURL, image);
  13637. }
  13638. else {
  13639. image.src = url;
  13640. }
  13641. };
  13642. if (!this.mustUpdateRessources) {
  13643. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  13644. }
  13645. else {
  13646. saveAndLoadImage();
  13647. }
  13648. };
  13649. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  13650. if (this.isSupported && this.db !== null) {
  13651. var texture;
  13652. var transaction = this.db.transaction(["textures"]);
  13653. transaction.onabort = function (event) {
  13654. image.src = url;
  13655. };
  13656. transaction.oncomplete = function (event) {
  13657. var blobTextureURL;
  13658. if (texture) {
  13659. var URL = window.URL || window.webkitURL;
  13660. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  13661. image.onerror = function () {
  13662. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  13663. image.src = url;
  13664. };
  13665. image.src = blobTextureURL;
  13666. }
  13667. else {
  13668. notInDBCallback();
  13669. }
  13670. };
  13671. var getRequest = transaction.objectStore("textures").get(url);
  13672. getRequest.onsuccess = function (event) {
  13673. texture = (event.target).result;
  13674. };
  13675. getRequest.onerror = function (event) {
  13676. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  13677. image.src = url;
  13678. };
  13679. }
  13680. else {
  13681. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13682. image.src = url;
  13683. }
  13684. };
  13685. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  13686. var _this = this;
  13687. if (this.isSupported) {
  13688. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  13689. var generateBlobUrl = function () {
  13690. var blobTextureURL;
  13691. if (blob) {
  13692. var URL = window.URL || window.webkitURL;
  13693. try {
  13694. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  13695. }
  13696. catch (ex) {
  13697. blobTextureURL = URL.createObjectURL(blob);
  13698. }
  13699. }
  13700. image.src = blobTextureURL;
  13701. };
  13702. if (BABYLON.Database.isUASupportingBlobStorage) {
  13703. var xhr = new XMLHttpRequest(), blob;
  13704. xhr.open("GET", url, true);
  13705. xhr.responseType = "blob";
  13706. xhr.addEventListener("load", function () {
  13707. if (xhr.status === 200) {
  13708. // Blob as response (XHR2)
  13709. blob = xhr.response;
  13710. var transaction = _this.db.transaction(["textures"], "readwrite");
  13711. // the transaction could abort because of a QuotaExceededError error
  13712. transaction.onabort = function (event) {
  13713. try {
  13714. if (event.srcElement.error.name === "QuotaExceededError") {
  13715. this.hasReachedQuota = true;
  13716. }
  13717. }
  13718. catch (ex) {
  13719. }
  13720. generateBlobUrl();
  13721. };
  13722. transaction.oncomplete = function (event) {
  13723. generateBlobUrl();
  13724. };
  13725. var newTexture = { textureUrl: url, data: blob };
  13726. try {
  13727. // Put the blob into the dabase
  13728. var addRequest = transaction.objectStore("textures").put(newTexture);
  13729. addRequest.onsuccess = function (event) {
  13730. };
  13731. addRequest.onerror = function (event) {
  13732. generateBlobUrl();
  13733. };
  13734. }
  13735. catch (ex) {
  13736. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  13737. if (ex.code === 25) {
  13738. BABYLON.Database.isUASupportingBlobStorage = false;
  13739. }
  13740. image.src = url;
  13741. }
  13742. }
  13743. else {
  13744. image.src = url;
  13745. }
  13746. }, false);
  13747. xhr.addEventListener("error", function (event) {
  13748. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  13749. image.src = url;
  13750. }, false);
  13751. xhr.send();
  13752. }
  13753. else {
  13754. image.src = url;
  13755. }
  13756. }
  13757. else {
  13758. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13759. image.src = url;
  13760. }
  13761. };
  13762. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  13763. var _this = this;
  13764. var updateVersion = function (event) {
  13765. // the version is not yet in the DB or we need to update it
  13766. _this._saveVersionIntoDBAsync(url, versionLoaded);
  13767. };
  13768. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  13769. };
  13770. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  13771. var _this = this;
  13772. if (this.isSupported) {
  13773. var version;
  13774. try {
  13775. var transaction = this.db.transaction(["versions"]);
  13776. transaction.oncomplete = function (event) {
  13777. if (version) {
  13778. // If the version in the JSON file is > than the version in DB
  13779. if (_this.manifestVersionFound > version.data) {
  13780. _this.mustUpdateRessources = true;
  13781. updateInDBCallback();
  13782. }
  13783. else {
  13784. callback(version.data);
  13785. }
  13786. }
  13787. else {
  13788. _this.mustUpdateRessources = true;
  13789. updateInDBCallback();
  13790. }
  13791. };
  13792. transaction.onabort = function (event) {
  13793. callback(-1);
  13794. };
  13795. var getRequest = transaction.objectStore("versions").get(url);
  13796. getRequest.onsuccess = function (event) {
  13797. version = (event.target).result;
  13798. };
  13799. getRequest.onerror = function (event) {
  13800. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  13801. callback(-1);
  13802. };
  13803. }
  13804. catch (ex) {
  13805. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  13806. callback(-1);
  13807. }
  13808. }
  13809. else {
  13810. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13811. callback(-1);
  13812. }
  13813. };
  13814. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  13815. var _this = this;
  13816. if (this.isSupported && !this.hasReachedQuota) {
  13817. try {
  13818. // Open a transaction to the database
  13819. var transaction = this.db.transaction(["versions"], "readwrite");
  13820. // the transaction could abort because of a QuotaExceededError error
  13821. transaction.onabort = function (event) {
  13822. try {
  13823. if (event.srcElement.error.name === "QuotaExceededError") {
  13824. _this.hasReachedQuota = true;
  13825. }
  13826. }
  13827. catch (ex) {
  13828. }
  13829. callback(-1);
  13830. };
  13831. transaction.oncomplete = function (event) {
  13832. callback(_this.manifestVersionFound);
  13833. };
  13834. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  13835. // Put the scene into the database
  13836. var addRequest = transaction.objectStore("versions").put(newVersion);
  13837. addRequest.onsuccess = function (event) {
  13838. };
  13839. addRequest.onerror = function (event) {
  13840. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  13841. };
  13842. }
  13843. catch (ex) {
  13844. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  13845. callback(-1);
  13846. }
  13847. }
  13848. else {
  13849. callback(-1);
  13850. }
  13851. };
  13852. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  13853. var _this = this;
  13854. var completeUrl = BABYLON.Database.ReturnFullUrlLocation(url);
  13855. var saveAndLoadFile = function (event) {
  13856. // the scene is not yet in the DB, let's try to save it
  13857. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  13858. };
  13859. this._checkVersionFromDB(completeUrl, function (version) {
  13860. if (version !== -1) {
  13861. if (!_this.mustUpdateRessources) {
  13862. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  13863. }
  13864. else {
  13865. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  13866. }
  13867. }
  13868. else {
  13869. errorCallback();
  13870. }
  13871. });
  13872. };
  13873. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  13874. if (this.isSupported) {
  13875. var targetStore;
  13876. if (url.indexOf(".babylon") !== -1) {
  13877. targetStore = "scenes";
  13878. }
  13879. else {
  13880. targetStore = "textures";
  13881. }
  13882. var file;
  13883. var transaction = this.db.transaction([targetStore]);
  13884. transaction.oncomplete = function (event) {
  13885. if (file) {
  13886. callback(file.data);
  13887. }
  13888. else {
  13889. notInDBCallback();
  13890. }
  13891. };
  13892. transaction.onabort = function (event) {
  13893. notInDBCallback();
  13894. };
  13895. var getRequest = transaction.objectStore(targetStore).get(url);
  13896. getRequest.onsuccess = function (event) {
  13897. file = (event.target).result;
  13898. };
  13899. getRequest.onerror = function (event) {
  13900. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  13901. notInDBCallback();
  13902. };
  13903. }
  13904. else {
  13905. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13906. callback();
  13907. }
  13908. };
  13909. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  13910. var _this = this;
  13911. if (this.isSupported) {
  13912. var targetStore;
  13913. if (url.indexOf(".babylon") !== -1) {
  13914. targetStore = "scenes";
  13915. }
  13916. else {
  13917. targetStore = "textures";
  13918. }
  13919. // Create XHR
  13920. var xhr = new XMLHttpRequest(), fileData;
  13921. xhr.open("GET", url, true);
  13922. if (useArrayBuffer) {
  13923. xhr.responseType = "arraybuffer";
  13924. }
  13925. xhr.onprogress = progressCallback;
  13926. xhr.addEventListener("load", function () {
  13927. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  13928. // Blob as response (XHR2)
  13929. //fileData = xhr.responseText;
  13930. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  13931. if (!_this.hasReachedQuota) {
  13932. // Open a transaction to the database
  13933. var transaction = _this.db.transaction([targetStore], "readwrite");
  13934. // the transaction could abort because of a QuotaExceededError error
  13935. transaction.onabort = function (event) {
  13936. try {
  13937. if (event.srcElement.error.name === "QuotaExceededError") {
  13938. this.hasReachedQuota = true;
  13939. }
  13940. }
  13941. catch (ex) {
  13942. }
  13943. callback(fileData);
  13944. };
  13945. transaction.oncomplete = function (event) {
  13946. callback(fileData);
  13947. };
  13948. var newFile;
  13949. if (targetStore === "scenes") {
  13950. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  13951. }
  13952. else {
  13953. newFile = { textureUrl: url, data: fileData };
  13954. }
  13955. try {
  13956. // Put the scene into the database
  13957. var addRequest = transaction.objectStore(targetStore).put(newFile);
  13958. addRequest.onsuccess = function (event) {
  13959. };
  13960. addRequest.onerror = function (event) {
  13961. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  13962. };
  13963. }
  13964. catch (ex) {
  13965. callback(fileData);
  13966. }
  13967. }
  13968. else {
  13969. callback(fileData);
  13970. }
  13971. }
  13972. else {
  13973. callback();
  13974. }
  13975. }, false);
  13976. xhr.addEventListener("error", function (event) {
  13977. BABYLON.Tools.Error("error on XHR request.");
  13978. callback();
  13979. }, false);
  13980. xhr.send();
  13981. }
  13982. else {
  13983. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  13984. callback();
  13985. }
  13986. };
  13987. Database.isUASupportingBlobStorage = true;
  13988. Database.parseURL = function (url) {
  13989. var a = document.createElement('a');
  13990. a.href = url;
  13991. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  13992. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  13993. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  13994. return absLocation;
  13995. };
  13996. Database.ReturnFullUrlLocation = function (url) {
  13997. if (url.indexOf("http:/") === -1) {
  13998. return (BABYLON.Database.parseURL(window.location.href) + url);
  13999. }
  14000. else {
  14001. return url;
  14002. }
  14003. };
  14004. return Database;
  14005. })();
  14006. BABYLON.Database = Database;
  14007. })(BABYLON || (BABYLON = {}));
  14008. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14009. (function (BABYLON) {
  14010. var SpriteManager = (function () {
  14011. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14012. this.name = name;
  14013. this.cellSize = cellSize;
  14014. this.sprites = new Array();
  14015. this.renderingGroupId = 0;
  14016. this.fogEnabled = true;
  14017. this._vertexDeclaration = [3, 4, 4, 4];
  14018. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14019. this._capacity = capacity;
  14020. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14021. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14022. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14023. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14024. this._scene = scene;
  14025. this._scene.spriteManagers.push(this);
  14026. // VBO
  14027. this._vertexDeclaration = [3, 4, 4, 4];
  14028. this._vertexStrideSize = 15 * 4;
  14029. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14030. var indices = [];
  14031. var index = 0;
  14032. for (var count = 0; count < capacity; count++) {
  14033. indices.push(index);
  14034. indices.push(index + 1);
  14035. indices.push(index + 2);
  14036. indices.push(index);
  14037. indices.push(index + 2);
  14038. indices.push(index + 3);
  14039. index += 4;
  14040. }
  14041. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14042. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14043. // Effects
  14044. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  14045. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  14046. }
  14047. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  14048. var arrayOffset = index * 15;
  14049. if (offsetX == 0)
  14050. offsetX = this._epsilon;
  14051. else if (offsetX == 1)
  14052. offsetX = 1 - this._epsilon;
  14053. if (offsetY == 0)
  14054. offsetY = this._epsilon;
  14055. else if (offsetY == 1)
  14056. offsetY = 1 - this._epsilon;
  14057. this._vertices[arrayOffset] = sprite.position.x;
  14058. this._vertices[arrayOffset + 1] = sprite.position.y;
  14059. this._vertices[arrayOffset + 2] = sprite.position.z;
  14060. this._vertices[arrayOffset + 3] = sprite.angle;
  14061. this._vertices[arrayOffset + 4] = sprite.size;
  14062. this._vertices[arrayOffset + 5] = offsetX;
  14063. this._vertices[arrayOffset + 6] = offsetY;
  14064. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  14065. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  14066. var offset = (sprite.cellIndex / rowSize) >> 0;
  14067. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  14068. this._vertices[arrayOffset + 10] = offset;
  14069. // Color
  14070. this._vertices[arrayOffset + 11] = sprite.color.r;
  14071. this._vertices[arrayOffset + 12] = sprite.color.g;
  14072. this._vertices[arrayOffset + 13] = sprite.color.b;
  14073. this._vertices[arrayOffset + 14] = sprite.color.a;
  14074. };
  14075. SpriteManager.prototype.render = function () {
  14076. // Check
  14077. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  14078. return;
  14079. var engine = this._scene.getEngine();
  14080. var baseSize = this._spriteTexture.getBaseSize();
  14081. // Sprites
  14082. var deltaTime = engine.getDeltaTime();
  14083. var max = Math.min(this._capacity, this.sprites.length);
  14084. var rowSize = baseSize.width / this.cellSize;
  14085. var offset = 0;
  14086. for (var index = 0; index < max; index++) {
  14087. var sprite = this.sprites[index];
  14088. if (!sprite) {
  14089. continue;
  14090. }
  14091. sprite._animate(deltaTime);
  14092. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  14093. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  14094. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  14095. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  14096. }
  14097. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14098. // Render
  14099. var effect = this._effectBase;
  14100. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14101. effect = this._effectFog;
  14102. }
  14103. engine.enableEffect(effect);
  14104. var viewMatrix = this._scene.getViewMatrix();
  14105. effect.setTexture("diffuseSampler", this._spriteTexture);
  14106. effect.setMatrix("view", viewMatrix);
  14107. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14108. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  14109. // Fog
  14110. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14111. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  14112. effect.setColor3("vFogColor", this._scene.fogColor);
  14113. }
  14114. // VBOs
  14115. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14116. // Draw order
  14117. effect.setBool("alphaTest", true);
  14118. engine.setColorWrite(false);
  14119. engine.draw(true, 0, max * 6);
  14120. engine.setColorWrite(true);
  14121. effect.setBool("alphaTest", false);
  14122. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14123. engine.draw(true, 0, max * 6);
  14124. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14125. };
  14126. SpriteManager.prototype.dispose = function () {
  14127. if (this._vertexBuffer) {
  14128. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14129. this._vertexBuffer = null;
  14130. }
  14131. if (this._indexBuffer) {
  14132. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14133. this._indexBuffer = null;
  14134. }
  14135. if (this._spriteTexture) {
  14136. this._spriteTexture.dispose();
  14137. this._spriteTexture = null;
  14138. }
  14139. // Remove from scene
  14140. var index = this._scene.spriteManagers.indexOf(this);
  14141. this._scene.spriteManagers.splice(index, 1);
  14142. // Callback
  14143. if (this.onDispose) {
  14144. this.onDispose();
  14145. }
  14146. };
  14147. return SpriteManager;
  14148. })();
  14149. BABYLON.SpriteManager = SpriteManager;
  14150. })(BABYLON || (BABYLON = {}));
  14151. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  14152. (function (BABYLON) {
  14153. var Sprite = (function () {
  14154. function Sprite(name, manager) {
  14155. this.name = name;
  14156. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14157. this.size = 1.0;
  14158. this.angle = 0;
  14159. this.cellIndex = 0;
  14160. this.invertU = 0;
  14161. this.invertV = 0;
  14162. this.animations = new Array();
  14163. this._animationStarted = false;
  14164. this._loopAnimation = false;
  14165. this._fromIndex = 0;
  14166. this._toIndex = 0;
  14167. this._delay = 0;
  14168. this._direction = 1;
  14169. this._frameCount = 0;
  14170. this._time = 0;
  14171. this._manager = manager;
  14172. this._manager.sprites.push(this);
  14173. this.position = BABYLON.Vector3.Zero();
  14174. }
  14175. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  14176. this._fromIndex = from;
  14177. this._toIndex = to;
  14178. this._loopAnimation = loop;
  14179. this._delay = delay;
  14180. this._animationStarted = true;
  14181. this._direction = from < to ? 1 : -1;
  14182. this.cellIndex = from;
  14183. this._time = 0;
  14184. };
  14185. Sprite.prototype.stopAnimation = function () {
  14186. this._animationStarted = false;
  14187. };
  14188. Sprite.prototype._animate = function (deltaTime) {
  14189. if (!this._animationStarted)
  14190. return;
  14191. this._time += deltaTime;
  14192. if (this._time > this._delay) {
  14193. this._time = this._time % this._delay;
  14194. this.cellIndex += this._direction;
  14195. if (this.cellIndex == this._toIndex) {
  14196. if (this._loopAnimation) {
  14197. this.cellIndex = this._fromIndex;
  14198. }
  14199. else {
  14200. this._animationStarted = false;
  14201. if (this.disposeWhenFinishedAnimating) {
  14202. this.dispose();
  14203. }
  14204. }
  14205. }
  14206. }
  14207. };
  14208. Sprite.prototype.dispose = function () {
  14209. for (var i = 0; i < this._manager.sprites.length; i++) {
  14210. if (this._manager.sprites[i] == this) {
  14211. this._manager.sprites.splice(i, 1);
  14212. }
  14213. }
  14214. };
  14215. return Sprite;
  14216. })();
  14217. BABYLON.Sprite = Sprite;
  14218. })(BABYLON || (BABYLON = {}));
  14219. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  14220. (function (BABYLON) {
  14221. var Layer = (function () {
  14222. function Layer(name, imgUrl, scene, isBackground, color) {
  14223. this.name = name;
  14224. this._vertexDeclaration = [2];
  14225. this._vertexStrideSize = 2 * 4;
  14226. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  14227. this.isBackground = isBackground === undefined ? true : isBackground;
  14228. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  14229. this._scene = scene;
  14230. this._scene.layers.push(this);
  14231. // VBO
  14232. var vertices = [];
  14233. vertices.push(1, 1);
  14234. vertices.push(-1, 1);
  14235. vertices.push(-1, -1);
  14236. vertices.push(1, -1);
  14237. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  14238. // Indices
  14239. var indices = [];
  14240. indices.push(0);
  14241. indices.push(1);
  14242. indices.push(2);
  14243. indices.push(0);
  14244. indices.push(2);
  14245. indices.push(3);
  14246. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14247. // Effects
  14248. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  14249. }
  14250. Layer.prototype.render = function () {
  14251. // Check
  14252. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  14253. return;
  14254. var engine = this._scene.getEngine();
  14255. // Render
  14256. engine.enableEffect(this._effect);
  14257. engine.setState(false);
  14258. // Texture
  14259. this._effect.setTexture("textureSampler", this.texture);
  14260. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  14261. // Color
  14262. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  14263. // VBOs
  14264. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  14265. // Draw order
  14266. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14267. engine.draw(true, 0, 6);
  14268. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14269. };
  14270. Layer.prototype.dispose = function () {
  14271. if (this._vertexBuffer) {
  14272. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14273. this._vertexBuffer = null;
  14274. }
  14275. if (this._indexBuffer) {
  14276. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14277. this._indexBuffer = null;
  14278. }
  14279. if (this.texture) {
  14280. this.texture.dispose();
  14281. this.texture = null;
  14282. }
  14283. // Remove from scene
  14284. var index = this._scene.layers.indexOf(this);
  14285. this._scene.layers.splice(index, 1);
  14286. // Callback
  14287. if (this.onDispose) {
  14288. this.onDispose();
  14289. }
  14290. };
  14291. return Layer;
  14292. })();
  14293. BABYLON.Layer = Layer;
  14294. })(BABYLON || (BABYLON = {}));
  14295. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  14296. (function (BABYLON) {
  14297. var Particle = (function () {
  14298. function Particle() {
  14299. this.position = BABYLON.Vector3.Zero();
  14300. this.direction = BABYLON.Vector3.Zero();
  14301. this.color = new BABYLON.Color4(0, 0, 0, 0);
  14302. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  14303. this.lifeTime = 1.0;
  14304. this.age = 0;
  14305. this.size = 0;
  14306. this.angle = 0;
  14307. this.angularSpeed = 0;
  14308. }
  14309. Particle.prototype.copyTo = function (other) {
  14310. other.position.copyFrom(this.position);
  14311. other.direction.copyFrom(this.direction);
  14312. other.color.copyFrom(this.color);
  14313. other.colorStep.copyFrom(this.colorStep);
  14314. other.lifeTime = this.lifeTime;
  14315. other.age = this.age;
  14316. other.size = this.size;
  14317. other.angle = this.angle;
  14318. other.angularSpeed = this.angularSpeed;
  14319. };
  14320. return Particle;
  14321. })();
  14322. BABYLON.Particle = Particle;
  14323. })(BABYLON || (BABYLON = {}));
  14324. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  14325. (function (BABYLON) {
  14326. var randomNumber = function (min, max) {
  14327. if (min === max) {
  14328. return (min);
  14329. }
  14330. var random = Math.random();
  14331. return ((random * (max - min)) + min);
  14332. };
  14333. var ParticleSystem = (function () {
  14334. function ParticleSystem(name, capacity, scene, customEffect) {
  14335. var _this = this;
  14336. this.name = name;
  14337. this.renderingGroupId = 0;
  14338. this.emitter = null;
  14339. this.emitRate = 10;
  14340. this.manualEmitCount = -1;
  14341. this.updateSpeed = 0.01;
  14342. this.targetStopDuration = 0;
  14343. this.disposeOnStop = false;
  14344. this.minEmitPower = 1;
  14345. this.maxEmitPower = 1;
  14346. this.minLifeTime = 1;
  14347. this.maxLifeTime = 1;
  14348. this.minSize = 1;
  14349. this.maxSize = 1;
  14350. this.minAngularSpeed = 0;
  14351. this.maxAngularSpeed = 0;
  14352. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  14353. this.forceDepthWrite = false;
  14354. this.gravity = BABYLON.Vector3.Zero();
  14355. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  14356. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  14357. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  14358. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  14359. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14360. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14361. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  14362. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  14363. this.particles = new Array();
  14364. this._vertexDeclaration = [3, 4, 4];
  14365. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  14366. this._stockParticles = new Array();
  14367. this._newPartsExcess = 0;
  14368. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  14369. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  14370. this._scaledDirection = BABYLON.Vector3.Zero();
  14371. this._scaledGravity = BABYLON.Vector3.Zero();
  14372. this._currentRenderId = -1;
  14373. this._started = false;
  14374. this._stopped = false;
  14375. this._actualFrame = 0;
  14376. this.id = name;
  14377. this._capacity = capacity;
  14378. this._scene = scene;
  14379. this._customEffect = customEffect;
  14380. scene.particleSystems.push(this);
  14381. // VBO
  14382. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14383. var indices = [];
  14384. var index = 0;
  14385. for (var count = 0; count < capacity; count++) {
  14386. indices.push(index);
  14387. indices.push(index + 1);
  14388. indices.push(index + 2);
  14389. indices.push(index);
  14390. indices.push(index + 2);
  14391. indices.push(index + 3);
  14392. index += 4;
  14393. }
  14394. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14395. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  14396. // Default behaviors
  14397. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  14398. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  14399. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  14400. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  14401. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  14402. };
  14403. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  14404. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  14405. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  14406. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  14407. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  14408. };
  14409. this.updateFunction = function (particles) {
  14410. for (var index = 0; index < particles.length; index++) {
  14411. var particle = particles[index];
  14412. particle.age += _this._scaledUpdateSpeed;
  14413. if (particle.age >= particle.lifeTime) {
  14414. _this.recycleParticle(particle);
  14415. index--;
  14416. continue;
  14417. }
  14418. else {
  14419. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  14420. particle.color.addInPlace(_this._scaledColorStep);
  14421. if (particle.color.a < 0)
  14422. particle.color.a = 0;
  14423. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  14424. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  14425. particle.position.addInPlace(_this._scaledDirection);
  14426. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  14427. particle.direction.addInPlace(_this._scaledGravity);
  14428. }
  14429. }
  14430. };
  14431. }
  14432. ParticleSystem.prototype.recycleParticle = function (particle) {
  14433. var lastParticle = this.particles.pop();
  14434. if (lastParticle !== particle) {
  14435. lastParticle.copyTo(particle);
  14436. this._stockParticles.push(lastParticle);
  14437. }
  14438. };
  14439. ParticleSystem.prototype.getCapacity = function () {
  14440. return this._capacity;
  14441. };
  14442. ParticleSystem.prototype.isAlive = function () {
  14443. return this._alive;
  14444. };
  14445. ParticleSystem.prototype.isStarted = function () {
  14446. return this._started;
  14447. };
  14448. ParticleSystem.prototype.start = function () {
  14449. this._started = true;
  14450. this._stopped = false;
  14451. this._actualFrame = 0;
  14452. };
  14453. ParticleSystem.prototype.stop = function () {
  14454. this._stopped = true;
  14455. };
  14456. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  14457. var offset = index * 11;
  14458. this._vertices[offset] = particle.position.x;
  14459. this._vertices[offset + 1] = particle.position.y;
  14460. this._vertices[offset + 2] = particle.position.z;
  14461. this._vertices[offset + 3] = particle.color.r;
  14462. this._vertices[offset + 4] = particle.color.g;
  14463. this._vertices[offset + 5] = particle.color.b;
  14464. this._vertices[offset + 6] = particle.color.a;
  14465. this._vertices[offset + 7] = particle.angle;
  14466. this._vertices[offset + 8] = particle.size;
  14467. this._vertices[offset + 9] = offsetX;
  14468. this._vertices[offset + 10] = offsetY;
  14469. };
  14470. ParticleSystem.prototype._update = function (newParticles) {
  14471. // Update current
  14472. this._alive = this.particles.length > 0;
  14473. this.updateFunction(this.particles);
  14474. // Add new ones
  14475. var worldMatrix;
  14476. if (this.emitter.position) {
  14477. worldMatrix = this.emitter.getWorldMatrix();
  14478. }
  14479. else {
  14480. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  14481. }
  14482. for (var index = 0; index < newParticles; index++) {
  14483. if (this.particles.length === this._capacity) {
  14484. break;
  14485. }
  14486. if (this._stockParticles.length !== 0) {
  14487. var particle = this._stockParticles.pop();
  14488. particle.age = 0;
  14489. }
  14490. else {
  14491. particle = new BABYLON.Particle();
  14492. }
  14493. this.particles.push(particle);
  14494. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  14495. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  14496. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  14497. particle.size = randomNumber(this.minSize, this.maxSize);
  14498. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  14499. this.startPositionFunction(worldMatrix, particle.position);
  14500. var step = randomNumber(0, 1.0);
  14501. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  14502. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  14503. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  14504. }
  14505. };
  14506. ParticleSystem.prototype._getEffect = function () {
  14507. if (this._customEffect) {
  14508. return this._customEffect;
  14509. }
  14510. ;
  14511. var defines = [];
  14512. if (this._scene.clipPlane) {
  14513. defines.push("#define CLIPPLANE");
  14514. }
  14515. // Effect
  14516. var join = defines.join("\n");
  14517. if (this._cachedDefines !== join) {
  14518. this._cachedDefines = join;
  14519. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  14520. }
  14521. return this._effect;
  14522. };
  14523. ParticleSystem.prototype.animate = function () {
  14524. if (!this._started)
  14525. return;
  14526. var effect = this._getEffect();
  14527. // Check
  14528. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  14529. return;
  14530. if (this._currentRenderId === this._scene.getRenderId()) {
  14531. return;
  14532. }
  14533. this._currentRenderId = this._scene.getRenderId();
  14534. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  14535. // determine the number of particles we need to create
  14536. var emitCout;
  14537. if (this.manualEmitCount > -1) {
  14538. emitCout = this.manualEmitCount;
  14539. this.manualEmitCount = 0;
  14540. }
  14541. else {
  14542. emitCout = this.emitRate;
  14543. }
  14544. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  14545. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  14546. if (this._newPartsExcess > 1.0) {
  14547. newParticles += this._newPartsExcess >> 0;
  14548. this._newPartsExcess -= this._newPartsExcess >> 0;
  14549. }
  14550. this._alive = false;
  14551. if (!this._stopped) {
  14552. this._actualFrame += this._scaledUpdateSpeed;
  14553. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  14554. this.stop();
  14555. }
  14556. else {
  14557. newParticles = 0;
  14558. }
  14559. this._update(newParticles);
  14560. // Stopped?
  14561. if (this._stopped) {
  14562. if (!this._alive) {
  14563. this._started = false;
  14564. if (this.disposeOnStop) {
  14565. this._scene._toBeDisposed.push(this);
  14566. }
  14567. }
  14568. }
  14569. // Update VBO
  14570. var offset = 0;
  14571. for (var index = 0; index < this.particles.length; index++) {
  14572. var particle = this.particles[index];
  14573. this._appendParticleVertex(offset++, particle, 0, 0);
  14574. this._appendParticleVertex(offset++, particle, 1, 0);
  14575. this._appendParticleVertex(offset++, particle, 1, 1);
  14576. this._appendParticleVertex(offset++, particle, 0, 1);
  14577. }
  14578. var engine = this._scene.getEngine();
  14579. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  14580. };
  14581. ParticleSystem.prototype.render = function () {
  14582. var effect = this._getEffect();
  14583. // Check
  14584. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  14585. return 0;
  14586. var engine = this._scene.getEngine();
  14587. // Render
  14588. engine.enableEffect(effect);
  14589. engine.setState(false);
  14590. var viewMatrix = this._scene.getViewMatrix();
  14591. effect.setTexture("diffuseSampler", this.particleTexture);
  14592. effect.setMatrix("view", viewMatrix);
  14593. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  14594. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  14595. if (this._scene.clipPlane) {
  14596. var clipPlane = this._scene.clipPlane;
  14597. var invView = viewMatrix.clone();
  14598. invView.invert();
  14599. effect.setMatrix("invView", invView);
  14600. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14601. }
  14602. // VBOs
  14603. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  14604. // Draw order
  14605. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  14606. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  14607. }
  14608. else {
  14609. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  14610. }
  14611. if (this.forceDepthWrite) {
  14612. engine.setDepthWrite(true);
  14613. }
  14614. engine.draw(true, 0, this.particles.length * 6);
  14615. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  14616. return this.particles.length;
  14617. };
  14618. ParticleSystem.prototype.dispose = function () {
  14619. if (this._vertexBuffer) {
  14620. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  14621. this._vertexBuffer = null;
  14622. }
  14623. if (this._indexBuffer) {
  14624. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  14625. this._indexBuffer = null;
  14626. }
  14627. if (this.particleTexture) {
  14628. this.particleTexture.dispose();
  14629. this.particleTexture = null;
  14630. }
  14631. // Remove from scene
  14632. var index = this._scene.particleSystems.indexOf(this);
  14633. this._scene.particleSystems.splice(index, 1);
  14634. // Callback
  14635. if (this.onDispose) {
  14636. this.onDispose();
  14637. }
  14638. };
  14639. // Clone
  14640. ParticleSystem.prototype.clone = function (name, newEmitter) {
  14641. var result = new ParticleSystem(name, this._capacity, this._scene);
  14642. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  14643. if (newEmitter === undefined) {
  14644. newEmitter = this.emitter;
  14645. }
  14646. result.emitter = newEmitter;
  14647. if (this.particleTexture) {
  14648. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  14649. }
  14650. result.start();
  14651. return result;
  14652. };
  14653. // Statics
  14654. ParticleSystem.BLENDMODE_ONEONE = 0;
  14655. ParticleSystem.BLENDMODE_STANDARD = 1;
  14656. return ParticleSystem;
  14657. })();
  14658. BABYLON.ParticleSystem = ParticleSystem;
  14659. })(BABYLON || (BABYLON = {}));
  14660. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  14661. (function (BABYLON) {
  14662. var Animation = (function () {
  14663. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  14664. this.name = name;
  14665. this.targetProperty = targetProperty;
  14666. this.framePerSecond = framePerSecond;
  14667. this.dataType = dataType;
  14668. this.loopMode = loopMode;
  14669. this._offsetsCache = {};
  14670. this._highLimitsCache = {};
  14671. this._stopped = false;
  14672. this.targetPropertyPath = targetProperty.split(".");
  14673. this.dataType = dataType;
  14674. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  14675. }
  14676. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  14677. var dataType = undefined;
  14678. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  14679. dataType = Animation.ANIMATIONTYPE_FLOAT;
  14680. }
  14681. else if (from instanceof BABYLON.Quaternion) {
  14682. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  14683. }
  14684. else if (from instanceof BABYLON.Vector3) {
  14685. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  14686. }
  14687. else if (from instanceof BABYLON.Vector2) {
  14688. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  14689. }
  14690. else if (from instanceof BABYLON.Color3) {
  14691. dataType = Animation.ANIMATIONTYPE_COLOR3;
  14692. }
  14693. if (dataType == undefined) {
  14694. return;
  14695. }
  14696. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  14697. var keys = [];
  14698. keys.push({ frame: 0, value: from });
  14699. keys.push({ frame: totalFrame, value: to });
  14700. animation.setKeys(keys);
  14701. mesh.animations.push(animation);
  14702. mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  14703. };
  14704. // Methods
  14705. Animation.prototype.isStopped = function () {
  14706. return this._stopped;
  14707. };
  14708. Animation.prototype.getKeys = function () {
  14709. return this._keys;
  14710. };
  14711. Animation.prototype.getEasingFunction = function () {
  14712. return this._easingFunction;
  14713. };
  14714. Animation.prototype.setEasingFunction = function (easingFunction) {
  14715. this._easingFunction = easingFunction;
  14716. };
  14717. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  14718. return startValue + (endValue - startValue) * gradient;
  14719. };
  14720. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  14721. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  14722. };
  14723. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  14724. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  14725. };
  14726. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  14727. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  14728. };
  14729. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  14730. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  14731. };
  14732. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  14733. var startScale = new BABYLON.Vector3(0, 0, 0);
  14734. var startRotation = new BABYLON.Quaternion();
  14735. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  14736. startValue.decompose(startScale, startRotation, startTranslation);
  14737. var endScale = new BABYLON.Vector3(0, 0, 0);
  14738. var endRotation = new BABYLON.Quaternion();
  14739. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  14740. endValue.decompose(endScale, endRotation, endTranslation);
  14741. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  14742. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  14743. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  14744. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  14745. return result;
  14746. };
  14747. Animation.prototype.clone = function () {
  14748. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  14749. clone.setKeys(this._keys);
  14750. return clone;
  14751. };
  14752. Animation.prototype.setKeys = function (values) {
  14753. this._keys = values.slice(0);
  14754. this._offsetsCache = {};
  14755. this._highLimitsCache = {};
  14756. };
  14757. Animation.prototype._getKeyValue = function (value) {
  14758. if (typeof value === "function") {
  14759. return value();
  14760. }
  14761. return value;
  14762. };
  14763. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  14764. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  14765. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  14766. }
  14767. this.currentFrame = currentFrame;
  14768. for (var key = 0; key < this._keys.length; key++) {
  14769. // for each frame, we need the key just before the frame superior
  14770. if (this._keys[key + 1].frame >= currentFrame) {
  14771. var startValue = this._getKeyValue(this._keys[key].value);
  14772. var endValue = this._getKeyValue(this._keys[key + 1].value);
  14773. // gradient : percent of currentFrame between the frame inf and the frame sup
  14774. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  14775. // check for easingFunction and correction of gradient
  14776. if (this._easingFunction != null) {
  14777. gradient = this._easingFunction.ease(gradient);
  14778. }
  14779. switch (this.dataType) {
  14780. case Animation.ANIMATIONTYPE_FLOAT:
  14781. switch (loopMode) {
  14782. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14783. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14784. return this.floatInterpolateFunction(startValue, endValue, gradient);
  14785. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14786. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  14787. }
  14788. break;
  14789. case Animation.ANIMATIONTYPE_QUATERNION:
  14790. var quaternion = null;
  14791. switch (loopMode) {
  14792. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14793. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14794. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  14795. break;
  14796. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14797. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14798. break;
  14799. }
  14800. return quaternion;
  14801. case Animation.ANIMATIONTYPE_VECTOR3:
  14802. switch (loopMode) {
  14803. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14804. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14805. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  14806. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14807. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14808. }
  14809. case Animation.ANIMATIONTYPE_VECTOR2:
  14810. switch (loopMode) {
  14811. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14812. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14813. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  14814. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14815. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14816. }
  14817. case Animation.ANIMATIONTYPE_COLOR3:
  14818. switch (loopMode) {
  14819. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14820. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14821. return this.color3InterpolateFunction(startValue, endValue, gradient);
  14822. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14823. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  14824. }
  14825. case Animation.ANIMATIONTYPE_MATRIX:
  14826. switch (loopMode) {
  14827. case Animation.ANIMATIONLOOPMODE_CYCLE:
  14828. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  14829. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  14830. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  14831. return startValue;
  14832. }
  14833. default:
  14834. break;
  14835. }
  14836. break;
  14837. }
  14838. }
  14839. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  14840. };
  14841. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  14842. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  14843. this._stopped = true;
  14844. return false;
  14845. }
  14846. var returnValue = true;
  14847. // Adding a start key at frame 0 if missing
  14848. if (this._keys[0].frame !== 0) {
  14849. var newKey = { frame: 0, value: this._keys[0].value };
  14850. this._keys.splice(0, 0, newKey);
  14851. }
  14852. // Check limits
  14853. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  14854. from = this._keys[0].frame;
  14855. }
  14856. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  14857. to = this._keys[this._keys.length - 1].frame;
  14858. }
  14859. // Compute ratio
  14860. var range = to - from;
  14861. var offsetValue;
  14862. // ratio represents the frame delta between from and to
  14863. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  14864. var highLimitValue = 0;
  14865. if (ratio > range && !loop) {
  14866. returnValue = false;
  14867. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  14868. }
  14869. else {
  14870. // Get max value if required
  14871. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  14872. var keyOffset = to.toString() + from.toString();
  14873. if (!this._offsetsCache[keyOffset]) {
  14874. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14875. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  14876. switch (this.dataType) {
  14877. case Animation.ANIMATIONTYPE_FLOAT:
  14878. this._offsetsCache[keyOffset] = toValue - fromValue;
  14879. break;
  14880. case Animation.ANIMATIONTYPE_QUATERNION:
  14881. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14882. break;
  14883. case Animation.ANIMATIONTYPE_VECTOR3:
  14884. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14885. case Animation.ANIMATIONTYPE_VECTOR2:
  14886. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14887. case Animation.ANIMATIONTYPE_COLOR3:
  14888. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  14889. default:
  14890. break;
  14891. }
  14892. this._highLimitsCache[keyOffset] = toValue;
  14893. }
  14894. highLimitValue = this._highLimitsCache[keyOffset];
  14895. offsetValue = this._offsetsCache[keyOffset];
  14896. }
  14897. }
  14898. if (offsetValue === undefined) {
  14899. switch (this.dataType) {
  14900. case Animation.ANIMATIONTYPE_FLOAT:
  14901. offsetValue = 0;
  14902. break;
  14903. case Animation.ANIMATIONTYPE_QUATERNION:
  14904. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  14905. break;
  14906. case Animation.ANIMATIONTYPE_VECTOR3:
  14907. offsetValue = BABYLON.Vector3.Zero();
  14908. break;
  14909. case Animation.ANIMATIONTYPE_VECTOR2:
  14910. offsetValue = BABYLON.Vector2.Zero();
  14911. break;
  14912. case Animation.ANIMATIONTYPE_COLOR3:
  14913. offsetValue = BABYLON.Color3.Black();
  14914. }
  14915. }
  14916. // Compute value
  14917. var repeatCount = (ratio / range) >> 0;
  14918. var currentFrame = returnValue ? from + ratio % range : to;
  14919. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  14920. // Set value
  14921. if (this.targetPropertyPath.length > 1) {
  14922. var property = this._target[this.targetPropertyPath[0]];
  14923. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  14924. property = property[this.targetPropertyPath[index]];
  14925. }
  14926. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  14927. }
  14928. else {
  14929. this._target[this.targetPropertyPath[0]] = currentValue;
  14930. }
  14931. if (this._target.markAsDirty) {
  14932. this._target.markAsDirty(this.targetProperty);
  14933. }
  14934. if (!returnValue) {
  14935. this._stopped = true;
  14936. }
  14937. return returnValue;
  14938. };
  14939. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  14940. get: function () {
  14941. return Animation._ANIMATIONTYPE_FLOAT;
  14942. },
  14943. enumerable: true,
  14944. configurable: true
  14945. });
  14946. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  14947. get: function () {
  14948. return Animation._ANIMATIONTYPE_VECTOR3;
  14949. },
  14950. enumerable: true,
  14951. configurable: true
  14952. });
  14953. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  14954. get: function () {
  14955. return Animation._ANIMATIONTYPE_VECTOR2;
  14956. },
  14957. enumerable: true,
  14958. configurable: true
  14959. });
  14960. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  14961. get: function () {
  14962. return Animation._ANIMATIONTYPE_QUATERNION;
  14963. },
  14964. enumerable: true,
  14965. configurable: true
  14966. });
  14967. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  14968. get: function () {
  14969. return Animation._ANIMATIONTYPE_MATRIX;
  14970. },
  14971. enumerable: true,
  14972. configurable: true
  14973. });
  14974. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  14975. get: function () {
  14976. return Animation._ANIMATIONTYPE_COLOR3;
  14977. },
  14978. enumerable: true,
  14979. configurable: true
  14980. });
  14981. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  14982. get: function () {
  14983. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  14984. },
  14985. enumerable: true,
  14986. configurable: true
  14987. });
  14988. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  14989. get: function () {
  14990. return Animation._ANIMATIONLOOPMODE_CYCLE;
  14991. },
  14992. enumerable: true,
  14993. configurable: true
  14994. });
  14995. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  14996. get: function () {
  14997. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  14998. },
  14999. enumerable: true,
  15000. configurable: true
  15001. });
  15002. // Statics
  15003. Animation._ANIMATIONTYPE_FLOAT = 0;
  15004. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15005. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15006. Animation._ANIMATIONTYPE_MATRIX = 3;
  15007. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15008. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15009. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15010. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15011. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15012. return Animation;
  15013. })();
  15014. BABYLON.Animation = Animation;
  15015. })(BABYLON || (BABYLON = {}));
  15016. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15017. (function (BABYLON) {
  15018. var Animatable = (function () {
  15019. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15020. if (fromFrame === void 0) { fromFrame = 0; }
  15021. if (toFrame === void 0) { toFrame = 100; }
  15022. if (loopAnimation === void 0) { loopAnimation = false; }
  15023. if (speedRatio === void 0) { speedRatio = 1.0; }
  15024. this.target = target;
  15025. this.fromFrame = fromFrame;
  15026. this.toFrame = toFrame;
  15027. this.loopAnimation = loopAnimation;
  15028. this.speedRatio = speedRatio;
  15029. this.onAnimationEnd = onAnimationEnd;
  15030. this._animations = new Array();
  15031. this._paused = false;
  15032. this.animationStarted = false;
  15033. if (animations) {
  15034. this.appendAnimations(target, animations);
  15035. }
  15036. this._scene = scene;
  15037. scene._activeAnimatables.push(this);
  15038. }
  15039. // Methods
  15040. Animatable.prototype.appendAnimations = function (target, animations) {
  15041. for (var index = 0; index < animations.length; index++) {
  15042. var animation = animations[index];
  15043. animation._target = target;
  15044. this._animations.push(animation);
  15045. }
  15046. };
  15047. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  15048. var animations = this._animations;
  15049. for (var index = 0; index < animations.length; index++) {
  15050. if (animations[index].targetProperty === property) {
  15051. return animations[index];
  15052. }
  15053. }
  15054. return null;
  15055. };
  15056. Animatable.prototype.pause = function () {
  15057. if (this._paused) {
  15058. return;
  15059. }
  15060. this._paused = true;
  15061. };
  15062. Animatable.prototype.restart = function () {
  15063. this._paused = false;
  15064. };
  15065. Animatable.prototype.stop = function () {
  15066. var index = this._scene._activeAnimatables.indexOf(this);
  15067. if (index > -1) {
  15068. this._scene._activeAnimatables.splice(index, 1);
  15069. }
  15070. if (this.onAnimationEnd) {
  15071. this.onAnimationEnd();
  15072. }
  15073. };
  15074. Animatable.prototype._animate = function (delay) {
  15075. if (this._paused) {
  15076. if (!this._pausedDelay) {
  15077. this._pausedDelay = delay;
  15078. }
  15079. return true;
  15080. }
  15081. if (!this._localDelayOffset) {
  15082. this._localDelayOffset = delay;
  15083. }
  15084. else if (this._pausedDelay) {
  15085. this._localDelayOffset += delay - this._pausedDelay;
  15086. this._pausedDelay = null;
  15087. }
  15088. // Animating
  15089. var running = false;
  15090. var animations = this._animations;
  15091. for (var index = 0; index < animations.length; index++) {
  15092. var animation = animations[index];
  15093. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  15094. running = running || isRunning;
  15095. }
  15096. if (!running && this.onAnimationEnd) {
  15097. this.onAnimationEnd();
  15098. }
  15099. return running;
  15100. };
  15101. return Animatable;
  15102. })();
  15103. BABYLON.Animatable = Animatable;
  15104. })(BABYLON || (BABYLON = {}));
  15105. //# sourceMappingURL=babylon.animatable.js.map
  15106. var BABYLON;
  15107. (function (BABYLON) {
  15108. var EasingFunction = (function () {
  15109. function EasingFunction() {
  15110. // Properties
  15111. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  15112. }
  15113. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  15114. get: function () {
  15115. return EasingFunction._EASINGMODE_EASEIN;
  15116. },
  15117. enumerable: true,
  15118. configurable: true
  15119. });
  15120. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  15121. get: function () {
  15122. return EasingFunction._EASINGMODE_EASEOUT;
  15123. },
  15124. enumerable: true,
  15125. configurable: true
  15126. });
  15127. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  15128. get: function () {
  15129. return EasingFunction._EASINGMODE_EASEINOUT;
  15130. },
  15131. enumerable: true,
  15132. configurable: true
  15133. });
  15134. EasingFunction.prototype.setEasingMode = function (easingMode) {
  15135. var n = Math.min(Math.max(easingMode, 0), 2);
  15136. this._easingMode = n;
  15137. };
  15138. EasingFunction.prototype.getEasingMode = function () {
  15139. return this._easingMode;
  15140. };
  15141. EasingFunction.prototype.easeInCore = function (gradient) {
  15142. throw new Error('You must implement this method');
  15143. };
  15144. EasingFunction.prototype.ease = function (gradient) {
  15145. switch (this._easingMode) {
  15146. case EasingFunction.EASINGMODE_EASEIN:
  15147. return this.easeInCore(gradient);
  15148. case EasingFunction.EASINGMODE_EASEOUT:
  15149. return (1 - this.easeInCore(1 - gradient));
  15150. }
  15151. if (gradient >= 0.5) {
  15152. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  15153. }
  15154. return (this.easeInCore(gradient * 2) * 0.5);
  15155. };
  15156. //Statics
  15157. EasingFunction._EASINGMODE_EASEIN = 0;
  15158. EasingFunction._EASINGMODE_EASEOUT = 1;
  15159. EasingFunction._EASINGMODE_EASEINOUT = 2;
  15160. return EasingFunction;
  15161. })();
  15162. BABYLON.EasingFunction = EasingFunction;
  15163. var CircleEase = (function (_super) {
  15164. __extends(CircleEase, _super);
  15165. function CircleEase() {
  15166. _super.apply(this, arguments);
  15167. }
  15168. CircleEase.prototype.easeInCore = function (gradient) {
  15169. gradient = Math.max(0, Math.min(1, gradient));
  15170. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  15171. };
  15172. return CircleEase;
  15173. })(EasingFunction);
  15174. BABYLON.CircleEase = CircleEase;
  15175. var BackEase = (function (_super) {
  15176. __extends(BackEase, _super);
  15177. function BackEase(amplitude) {
  15178. if (amplitude === void 0) { amplitude = 1; }
  15179. _super.call(this);
  15180. this.amplitude = amplitude;
  15181. }
  15182. BackEase.prototype.easeInCore = function (gradient) {
  15183. var num = Math.max(0, this.amplitude);
  15184. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  15185. };
  15186. return BackEase;
  15187. })(EasingFunction);
  15188. BABYLON.BackEase = BackEase;
  15189. var BounceEase = (function (_super) {
  15190. __extends(BounceEase, _super);
  15191. function BounceEase(bounces, bounciness) {
  15192. if (bounces === void 0) { bounces = 3; }
  15193. if (bounciness === void 0) { bounciness = 2; }
  15194. _super.call(this);
  15195. this.bounces = bounces;
  15196. this.bounciness = bounciness;
  15197. }
  15198. BounceEase.prototype.easeInCore = function (gradient) {
  15199. var y = Math.max(0.0, this.bounces);
  15200. var bounciness = this.bounciness;
  15201. if (bounciness <= 1.0) {
  15202. bounciness = 1.001;
  15203. }
  15204. var num9 = Math.pow(bounciness, y);
  15205. var num5 = 1.0 - bounciness;
  15206. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  15207. var num15 = gradient * num4;
  15208. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  15209. var num3 = Math.floor(num65);
  15210. var num13 = num3 + 1.0;
  15211. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  15212. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  15213. var num7 = (num8 + num12) * 0.5;
  15214. var num6 = gradient - num7;
  15215. var num2 = num7 - num8;
  15216. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  15217. };
  15218. return BounceEase;
  15219. })(EasingFunction);
  15220. BABYLON.BounceEase = BounceEase;
  15221. var CubicEase = (function (_super) {
  15222. __extends(CubicEase, _super);
  15223. function CubicEase() {
  15224. _super.apply(this, arguments);
  15225. }
  15226. CubicEase.prototype.easeInCore = function (gradient) {
  15227. return (gradient * gradient * gradient);
  15228. };
  15229. return CubicEase;
  15230. })(EasingFunction);
  15231. BABYLON.CubicEase = CubicEase;
  15232. var ElasticEase = (function (_super) {
  15233. __extends(ElasticEase, _super);
  15234. function ElasticEase(oscillations, springiness) {
  15235. if (oscillations === void 0) { oscillations = 3; }
  15236. if (springiness === void 0) { springiness = 3; }
  15237. _super.call(this);
  15238. this.oscillations = oscillations;
  15239. this.springiness = springiness;
  15240. }
  15241. ElasticEase.prototype.easeInCore = function (gradient) {
  15242. var num2;
  15243. var num3 = Math.max(0.0, this.oscillations);
  15244. var num = Math.max(0.0, this.springiness);
  15245. if (num == 0) {
  15246. num2 = gradient;
  15247. }
  15248. else {
  15249. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  15250. }
  15251. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  15252. };
  15253. return ElasticEase;
  15254. })(EasingFunction);
  15255. BABYLON.ElasticEase = ElasticEase;
  15256. var ExponentialEase = (function (_super) {
  15257. __extends(ExponentialEase, _super);
  15258. function ExponentialEase(exponent) {
  15259. if (exponent === void 0) { exponent = 2; }
  15260. _super.call(this);
  15261. this.exponent = exponent;
  15262. }
  15263. ExponentialEase.prototype.easeInCore = function (gradient) {
  15264. if (this.exponent <= 0) {
  15265. return gradient;
  15266. }
  15267. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  15268. };
  15269. return ExponentialEase;
  15270. })(EasingFunction);
  15271. BABYLON.ExponentialEase = ExponentialEase;
  15272. var PowerEase = (function (_super) {
  15273. __extends(PowerEase, _super);
  15274. function PowerEase(power) {
  15275. if (power === void 0) { power = 2; }
  15276. _super.call(this);
  15277. this.power = power;
  15278. }
  15279. PowerEase.prototype.easeInCore = function (gradient) {
  15280. var y = Math.max(0.0, this.power);
  15281. return Math.pow(gradient, y);
  15282. };
  15283. return PowerEase;
  15284. })(EasingFunction);
  15285. BABYLON.PowerEase = PowerEase;
  15286. var QuadraticEase = (function (_super) {
  15287. __extends(QuadraticEase, _super);
  15288. function QuadraticEase() {
  15289. _super.apply(this, arguments);
  15290. }
  15291. QuadraticEase.prototype.easeInCore = function (gradient) {
  15292. return (gradient * gradient);
  15293. };
  15294. return QuadraticEase;
  15295. })(EasingFunction);
  15296. BABYLON.QuadraticEase = QuadraticEase;
  15297. var QuarticEase = (function (_super) {
  15298. __extends(QuarticEase, _super);
  15299. function QuarticEase() {
  15300. _super.apply(this, arguments);
  15301. }
  15302. QuarticEase.prototype.easeInCore = function (gradient) {
  15303. return (gradient * gradient * gradient * gradient);
  15304. };
  15305. return QuarticEase;
  15306. })(EasingFunction);
  15307. BABYLON.QuarticEase = QuarticEase;
  15308. var QuinticEase = (function (_super) {
  15309. __extends(QuinticEase, _super);
  15310. function QuinticEase() {
  15311. _super.apply(this, arguments);
  15312. }
  15313. QuinticEase.prototype.easeInCore = function (gradient) {
  15314. return (gradient * gradient * gradient * gradient * gradient);
  15315. };
  15316. return QuinticEase;
  15317. })(EasingFunction);
  15318. BABYLON.QuinticEase = QuinticEase;
  15319. var SineEase = (function (_super) {
  15320. __extends(SineEase, _super);
  15321. function SineEase() {
  15322. _super.apply(this, arguments);
  15323. }
  15324. SineEase.prototype.easeInCore = function (gradient) {
  15325. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  15326. };
  15327. return SineEase;
  15328. })(EasingFunction);
  15329. BABYLON.SineEase = SineEase;
  15330. var BezierCurveEase = (function (_super) {
  15331. __extends(BezierCurveEase, _super);
  15332. function BezierCurveEase(x1, y1, x2, y2) {
  15333. if (x1 === void 0) { x1 = 0; }
  15334. if (y1 === void 0) { y1 = 0; }
  15335. if (x2 === void 0) { x2 = 1; }
  15336. if (y2 === void 0) { y2 = 1; }
  15337. _super.call(this);
  15338. this.x1 = x1;
  15339. this.y1 = y1;
  15340. this.x2 = x2;
  15341. this.y2 = y2;
  15342. }
  15343. BezierCurveEase.prototype.easeInCore = function (gradient) {
  15344. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  15345. };
  15346. return BezierCurveEase;
  15347. })(EasingFunction);
  15348. BABYLON.BezierCurveEase = BezierCurveEase;
  15349. })(BABYLON || (BABYLON = {}));
  15350. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  15351. (function (BABYLON) {
  15352. var Octree = (function () {
  15353. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  15354. if (maxDepth === void 0) { maxDepth = 2; }
  15355. this.maxDepth = maxDepth;
  15356. this.dynamicContent = new Array();
  15357. this._maxBlockCapacity = maxBlockCapacity || 64;
  15358. this._selectionContent = new BABYLON.SmartArray(1024);
  15359. this._creationFunc = creationFunc;
  15360. }
  15361. // Methods
  15362. Octree.prototype.update = function (worldMin, worldMax, entries) {
  15363. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  15364. };
  15365. Octree.prototype.addMesh = function (entry) {
  15366. for (var index = 0; index < this.blocks.length; index++) {
  15367. var block = this.blocks[index];
  15368. block.addEntry(entry);
  15369. }
  15370. };
  15371. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  15372. this._selectionContent.reset();
  15373. for (var index = 0; index < this.blocks.length; index++) {
  15374. var block = this.blocks[index];
  15375. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  15376. }
  15377. if (allowDuplicate) {
  15378. this._selectionContent.concat(this.dynamicContent);
  15379. }
  15380. else {
  15381. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15382. }
  15383. return this._selectionContent;
  15384. };
  15385. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  15386. this._selectionContent.reset();
  15387. for (var index = 0; index < this.blocks.length; index++) {
  15388. var block = this.blocks[index];
  15389. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  15390. }
  15391. if (allowDuplicate) {
  15392. this._selectionContent.concat(this.dynamicContent);
  15393. }
  15394. else {
  15395. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15396. }
  15397. return this._selectionContent;
  15398. };
  15399. Octree.prototype.intersectsRay = function (ray) {
  15400. this._selectionContent.reset();
  15401. for (var index = 0; index < this.blocks.length; index++) {
  15402. var block = this.blocks[index];
  15403. block.intersectsRay(ray, this._selectionContent);
  15404. }
  15405. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  15406. return this._selectionContent;
  15407. };
  15408. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  15409. target.blocks = new Array();
  15410. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  15411. for (var x = 0; x < 2; x++) {
  15412. for (var y = 0; y < 2; y++) {
  15413. for (var z = 0; z < 2; z++) {
  15414. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  15415. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  15416. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  15417. block.addEntries(entries);
  15418. target.blocks.push(block);
  15419. }
  15420. }
  15421. }
  15422. };
  15423. Octree.CreationFuncForMeshes = function (entry, block) {
  15424. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15425. block.entries.push(entry);
  15426. }
  15427. };
  15428. Octree.CreationFuncForSubMeshes = function (entry, block) {
  15429. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  15430. block.entries.push(entry);
  15431. }
  15432. };
  15433. return Octree;
  15434. })();
  15435. BABYLON.Octree = Octree;
  15436. })(BABYLON || (BABYLON = {}));
  15437. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  15438. (function (BABYLON) {
  15439. var OctreeBlock = (function () {
  15440. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  15441. this.entries = new Array();
  15442. this._boundingVectors = new Array();
  15443. this._capacity = capacity;
  15444. this._depth = depth;
  15445. this._maxDepth = maxDepth;
  15446. this._creationFunc = creationFunc;
  15447. this._minPoint = minPoint;
  15448. this._maxPoint = maxPoint;
  15449. this._boundingVectors.push(minPoint.clone());
  15450. this._boundingVectors.push(maxPoint.clone());
  15451. this._boundingVectors.push(minPoint.clone());
  15452. this._boundingVectors[2].x = maxPoint.x;
  15453. this._boundingVectors.push(minPoint.clone());
  15454. this._boundingVectors[3].y = maxPoint.y;
  15455. this._boundingVectors.push(minPoint.clone());
  15456. this._boundingVectors[4].z = maxPoint.z;
  15457. this._boundingVectors.push(maxPoint.clone());
  15458. this._boundingVectors[5].z = minPoint.z;
  15459. this._boundingVectors.push(maxPoint.clone());
  15460. this._boundingVectors[6].x = minPoint.x;
  15461. this._boundingVectors.push(maxPoint.clone());
  15462. this._boundingVectors[7].y = minPoint.y;
  15463. }
  15464. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  15465. // Property
  15466. get: function () {
  15467. return this._capacity;
  15468. },
  15469. enumerable: true,
  15470. configurable: true
  15471. });
  15472. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  15473. get: function () {
  15474. return this._minPoint;
  15475. },
  15476. enumerable: true,
  15477. configurable: true
  15478. });
  15479. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  15480. get: function () {
  15481. return this._maxPoint;
  15482. },
  15483. enumerable: true,
  15484. configurable: true
  15485. });
  15486. // Methods
  15487. OctreeBlock.prototype.addEntry = function (entry) {
  15488. if (this.blocks) {
  15489. for (var index = 0; index < this.blocks.length; index++) {
  15490. var block = this.blocks[index];
  15491. block.addEntry(entry);
  15492. }
  15493. return;
  15494. }
  15495. this._creationFunc(entry, this);
  15496. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  15497. this.createInnerBlocks();
  15498. }
  15499. };
  15500. OctreeBlock.prototype.addEntries = function (entries) {
  15501. for (var index = 0; index < entries.length; index++) {
  15502. var mesh = entries[index];
  15503. this.addEntry(mesh);
  15504. }
  15505. };
  15506. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  15507. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  15508. if (this.blocks) {
  15509. for (var index = 0; index < this.blocks.length; index++) {
  15510. var block = this.blocks[index];
  15511. block.select(frustumPlanes, selection, allowDuplicate);
  15512. }
  15513. return;
  15514. }
  15515. if (allowDuplicate) {
  15516. selection.concat(this.entries);
  15517. }
  15518. else {
  15519. selection.concatWithNoDuplicate(this.entries);
  15520. }
  15521. }
  15522. };
  15523. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  15524. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  15525. if (this.blocks) {
  15526. for (var index = 0; index < this.blocks.length; index++) {
  15527. var block = this.blocks[index];
  15528. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  15529. }
  15530. return;
  15531. }
  15532. if (allowDuplicate) {
  15533. selection.concat(this.entries);
  15534. }
  15535. else {
  15536. selection.concatWithNoDuplicate(this.entries);
  15537. }
  15538. }
  15539. };
  15540. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  15541. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  15542. if (this.blocks) {
  15543. for (var index = 0; index < this.blocks.length; index++) {
  15544. var block = this.blocks[index];
  15545. block.intersectsRay(ray, selection);
  15546. }
  15547. return;
  15548. }
  15549. selection.concatWithNoDuplicate(this.entries);
  15550. }
  15551. };
  15552. OctreeBlock.prototype.createInnerBlocks = function () {
  15553. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  15554. };
  15555. return OctreeBlock;
  15556. })();
  15557. BABYLON.OctreeBlock = OctreeBlock;
  15558. })(BABYLON || (BABYLON = {}));
  15559. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  15560. (function (BABYLON) {
  15561. var Bone = (function () {
  15562. function Bone(name, skeleton, parentBone, matrix) {
  15563. this.name = name;
  15564. this.children = new Array();
  15565. this.animations = new Array();
  15566. this._worldTransform = new BABYLON.Matrix();
  15567. this._absoluteTransform = new BABYLON.Matrix();
  15568. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  15569. this._skeleton = skeleton;
  15570. this._matrix = matrix;
  15571. this._baseMatrix = matrix;
  15572. skeleton.bones.push(this);
  15573. if (parentBone) {
  15574. this._parent = parentBone;
  15575. parentBone.children.push(this);
  15576. }
  15577. else {
  15578. this._parent = null;
  15579. }
  15580. this._updateDifferenceMatrix();
  15581. }
  15582. // Members
  15583. Bone.prototype.getParent = function () {
  15584. return this._parent;
  15585. };
  15586. Bone.prototype.getLocalMatrix = function () {
  15587. return this._matrix;
  15588. };
  15589. Bone.prototype.getBaseMatrix = function () {
  15590. return this._baseMatrix;
  15591. };
  15592. Bone.prototype.getWorldMatrix = function () {
  15593. return this._worldTransform;
  15594. };
  15595. Bone.prototype.getInvertedAbsoluteTransform = function () {
  15596. return this._invertedAbsoluteTransform;
  15597. };
  15598. Bone.prototype.getAbsoluteMatrix = function () {
  15599. var matrix = this._matrix.clone();
  15600. var parent = this._parent;
  15601. while (parent) {
  15602. matrix = matrix.multiply(parent.getLocalMatrix());
  15603. parent = parent.getParent();
  15604. }
  15605. return matrix;
  15606. };
  15607. // Methods
  15608. Bone.prototype.updateMatrix = function (matrix) {
  15609. this._matrix = matrix;
  15610. this._skeleton._markAsDirty();
  15611. this._updateDifferenceMatrix();
  15612. };
  15613. Bone.prototype._updateDifferenceMatrix = function () {
  15614. if (this._parent) {
  15615. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  15616. }
  15617. else {
  15618. this._absoluteTransform.copyFrom(this._matrix);
  15619. }
  15620. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  15621. for (var index = 0; index < this.children.length; index++) {
  15622. this.children[index]._updateDifferenceMatrix();
  15623. }
  15624. };
  15625. Bone.prototype.markAsDirty = function () {
  15626. this._skeleton._markAsDirty();
  15627. };
  15628. return Bone;
  15629. })();
  15630. BABYLON.Bone = Bone;
  15631. })(BABYLON || (BABYLON = {}));
  15632. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  15633. (function (BABYLON) {
  15634. var Skeleton = (function () {
  15635. function Skeleton(name, id, scene) {
  15636. this.name = name;
  15637. this.id = id;
  15638. this.bones = new Array();
  15639. this._isDirty = true;
  15640. this._identity = BABYLON.Matrix.Identity();
  15641. this.bones = [];
  15642. this._scene = scene;
  15643. scene.skeletons.push(this);
  15644. }
  15645. // Members
  15646. Skeleton.prototype.getTransformMatrices = function () {
  15647. return this._transformMatrices;
  15648. };
  15649. // Methods
  15650. Skeleton.prototype._markAsDirty = function () {
  15651. this._isDirty = true;
  15652. };
  15653. Skeleton.prototype.prepare = function () {
  15654. if (!this._isDirty) {
  15655. return;
  15656. }
  15657. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  15658. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  15659. }
  15660. for (var index = 0; index < this.bones.length; index++) {
  15661. var bone = this.bones[index];
  15662. var parentBone = bone.getParent();
  15663. if (parentBone) {
  15664. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  15665. }
  15666. else {
  15667. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  15668. }
  15669. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  15670. }
  15671. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  15672. this._isDirty = false;
  15673. };
  15674. Skeleton.prototype.getAnimatables = function () {
  15675. if (!this._animatables || this._animatables.length != this.bones.length) {
  15676. this._animatables = [];
  15677. for (var index = 0; index < this.bones.length; index++) {
  15678. this._animatables.push(this.bones[index]);
  15679. }
  15680. }
  15681. return this._animatables;
  15682. };
  15683. Skeleton.prototype.clone = function (name, id) {
  15684. var result = new BABYLON.Skeleton(name, id || name, this._scene);
  15685. for (var index = 0; index < this.bones.length; index++) {
  15686. var source = this.bones[index];
  15687. var parentBone = null;
  15688. if (source.getParent()) {
  15689. var parentIndex = this.bones.indexOf(source.getParent());
  15690. parentBone = result.bones[parentIndex];
  15691. }
  15692. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  15693. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  15694. }
  15695. return result;
  15696. };
  15697. return Skeleton;
  15698. })();
  15699. BABYLON.Skeleton = Skeleton;
  15700. })(BABYLON || (BABYLON = {}));
  15701. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  15702. (function (BABYLON) {
  15703. var PostProcess = (function () {
  15704. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable) {
  15705. this.name = name;
  15706. this.width = -1;
  15707. this.height = -1;
  15708. this._reusable = false;
  15709. this._textures = new BABYLON.SmartArray(2);
  15710. this._currentRenderTextureInd = 0;
  15711. if (camera != null) {
  15712. this._camera = camera;
  15713. this._scene = camera.getScene();
  15714. camera.attachPostProcess(this);
  15715. this._engine = this._scene.getEngine();
  15716. }
  15717. else {
  15718. this._engine = engine;
  15719. }
  15720. this._renderRatio = ratio;
  15721. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15722. this._reusable = reusable || false;
  15723. samplers = samplers || [];
  15724. samplers.push("textureSampler");
  15725. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, "");
  15726. }
  15727. PostProcess.prototype.isReusable = function () {
  15728. return this._reusable;
  15729. };
  15730. PostProcess.prototype.activate = function (camera, sourceTexture) {
  15731. camera = camera || this._camera;
  15732. var scene = camera.getScene();
  15733. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  15734. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  15735. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  15736. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  15737. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  15738. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  15739. if (this._textures.length > 0) {
  15740. for (var i = 0; i < this._textures.length; i++) {
  15741. this._engine._releaseTexture(this._textures.data[i]);
  15742. }
  15743. this._textures.reset();
  15744. }
  15745. this.width = desiredWidth;
  15746. this.height = desiredHeight;
  15747. 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 }));
  15748. if (this._reusable) {
  15749. 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 }));
  15750. }
  15751. if (this.onSizeChanged) {
  15752. this.onSizeChanged();
  15753. }
  15754. }
  15755. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  15756. if (this.onActivate) {
  15757. this.onActivate(camera);
  15758. }
  15759. // Clear
  15760. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  15761. if (this._reusable) {
  15762. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  15763. }
  15764. };
  15765. PostProcess.prototype.apply = function () {
  15766. // Check
  15767. if (!this._effect.isReady())
  15768. return null;
  15769. // States
  15770. this._engine.enableEffect(this._effect);
  15771. this._engine.setState(false);
  15772. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15773. this._engine.setDepthBuffer(false);
  15774. this._engine.setDepthWrite(false);
  15775. // Texture
  15776. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  15777. // Parameters
  15778. if (this.onApply) {
  15779. this.onApply(this._effect);
  15780. }
  15781. return this._effect;
  15782. };
  15783. PostProcess.prototype.dispose = function (camera) {
  15784. camera = camera || this._camera;
  15785. if (this._textures.length > 0) {
  15786. for (var i = 0; i < this._textures.length; i++) {
  15787. this._engine._releaseTexture(this._textures.data[i]);
  15788. }
  15789. this._textures.reset();
  15790. }
  15791. camera.detachPostProcess(this);
  15792. var index = camera._postProcesses.indexOf(this);
  15793. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  15794. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  15795. }
  15796. };
  15797. return PostProcess;
  15798. })();
  15799. BABYLON.PostProcess = PostProcess;
  15800. })(BABYLON || (BABYLON = {}));
  15801. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  15802. (function (BABYLON) {
  15803. var PostProcessManager = (function () {
  15804. function PostProcessManager(scene) {
  15805. this._vertexDeclaration = [2];
  15806. this._vertexStrideSize = 2 * 4;
  15807. this._scene = scene;
  15808. // VBO
  15809. var vertices = [];
  15810. vertices.push(1, 1);
  15811. vertices.push(-1, 1);
  15812. vertices.push(-1, -1);
  15813. vertices.push(1, -1);
  15814. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15815. // Indices
  15816. var indices = [];
  15817. indices.push(0);
  15818. indices.push(1);
  15819. indices.push(2);
  15820. indices.push(0);
  15821. indices.push(2);
  15822. indices.push(3);
  15823. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15824. }
  15825. // Methods
  15826. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  15827. var postProcesses = this._scene.activeCamera._postProcesses;
  15828. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15829. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15830. return false;
  15831. }
  15832. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  15833. return true;
  15834. };
  15835. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  15836. var postProcesses = this._scene.activeCamera._postProcesses;
  15837. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  15838. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  15839. return;
  15840. }
  15841. var engine = this._scene.getEngine();
  15842. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  15843. if (index < postProcessesTakenIndices.length - 1) {
  15844. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  15845. }
  15846. else {
  15847. if (targetTexture) {
  15848. engine.bindFramebuffer(targetTexture);
  15849. }
  15850. else {
  15851. engine.restoreDefaultFramebuffer();
  15852. }
  15853. }
  15854. if (doNotPresent) {
  15855. break;
  15856. }
  15857. var pp = postProcesses[postProcessesTakenIndices[index]];
  15858. var effect = pp.apply();
  15859. if (effect) {
  15860. if (pp.onBeforeRender) {
  15861. pp.onBeforeRender(effect);
  15862. }
  15863. // VBOs
  15864. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15865. // Draw order
  15866. engine.draw(true, 0, 6);
  15867. }
  15868. }
  15869. // Restore depth buffer
  15870. engine.setDepthBuffer(true);
  15871. engine.setDepthWrite(true);
  15872. };
  15873. PostProcessManager.prototype.dispose = function () {
  15874. if (this._vertexBuffer) {
  15875. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15876. this._vertexBuffer = null;
  15877. }
  15878. if (this._indexBuffer) {
  15879. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15880. this._indexBuffer = null;
  15881. }
  15882. };
  15883. return PostProcessManager;
  15884. })();
  15885. BABYLON.PostProcessManager = PostProcessManager;
  15886. })(BABYLON || (BABYLON = {}));
  15887. //# sourceMappingURL=babylon.postProcessManager.js.map
  15888. var BABYLON;
  15889. (function (BABYLON) {
  15890. var PassPostProcess = (function (_super) {
  15891. __extends(PassPostProcess, _super);
  15892. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15893. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  15894. }
  15895. return PassPostProcess;
  15896. })(BABYLON.PostProcess);
  15897. BABYLON.PassPostProcess = PassPostProcess;
  15898. })(BABYLON || (BABYLON = {}));
  15899. //# sourceMappingURL=babylon.passPostProcess.js.map
  15900. var BABYLON;
  15901. (function (BABYLON) {
  15902. var BlurPostProcess = (function (_super) {
  15903. __extends(BlurPostProcess, _super);
  15904. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  15905. var _this = this;
  15906. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  15907. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  15908. this.direction = direction;
  15909. this.blurWidth = blurWidth;
  15910. this.onApply = function (effect) {
  15911. effect.setFloat2("screenSize", _this.width, _this.height);
  15912. effect.setVector2("direction", _this.direction);
  15913. effect.setFloat("blurWidth", _this.blurWidth);
  15914. };
  15915. }
  15916. return BlurPostProcess;
  15917. })(BABYLON.PostProcess);
  15918. BABYLON.BlurPostProcess = BlurPostProcess;
  15919. })(BABYLON || (BABYLON = {}));
  15920. //# sourceMappingURL=babylon.blurPostProcess.js.map
  15921. var BABYLON;
  15922. (function (BABYLON) {
  15923. var FilterPostProcess = (function (_super) {
  15924. __extends(FilterPostProcess, _super);
  15925. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  15926. var _this = this;
  15927. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  15928. this.kernelMatrix = kernelMatrix;
  15929. this.onApply = function (effect) {
  15930. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  15931. };
  15932. }
  15933. return FilterPostProcess;
  15934. })(BABYLON.PostProcess);
  15935. BABYLON.FilterPostProcess = FilterPostProcess;
  15936. })(BABYLON || (BABYLON = {}));
  15937. //# sourceMappingURL=babylon.filterPostProcess.js.map
  15938. var BABYLON;
  15939. (function (BABYLON) {
  15940. var RefractionPostProcess = (function (_super) {
  15941. __extends(RefractionPostProcess, _super);
  15942. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  15943. var _this = this;
  15944. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  15945. this.color = color;
  15946. this.depth = depth;
  15947. this.colorLevel = colorLevel;
  15948. this.onActivate = function (cam) {
  15949. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  15950. };
  15951. this.onApply = function (effect) {
  15952. effect.setColor3("baseColor", _this.color);
  15953. effect.setFloat("depth", _this.depth);
  15954. effect.setFloat("colorLevel", _this.colorLevel);
  15955. effect.setTexture("refractionSampler", _this._refRexture);
  15956. };
  15957. }
  15958. // Methods
  15959. RefractionPostProcess.prototype.dispose = function (camera) {
  15960. if (this._refRexture) {
  15961. this._refRexture.dispose();
  15962. }
  15963. _super.prototype.dispose.call(this, camera);
  15964. };
  15965. return RefractionPostProcess;
  15966. })(BABYLON.PostProcess);
  15967. BABYLON.RefractionPostProcess = RefractionPostProcess;
  15968. })(BABYLON || (BABYLON = {}));
  15969. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  15970. var BABYLON;
  15971. (function (BABYLON) {
  15972. var BlackAndWhitePostProcess = (function (_super) {
  15973. __extends(BlackAndWhitePostProcess, _super);
  15974. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  15975. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  15976. }
  15977. return BlackAndWhitePostProcess;
  15978. })(BABYLON.PostProcess);
  15979. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  15980. })(BABYLON || (BABYLON = {}));
  15981. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  15982. var BABYLON;
  15983. (function (BABYLON) {
  15984. var ConvolutionPostProcess = (function (_super) {
  15985. __extends(ConvolutionPostProcess, _super);
  15986. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  15987. var _this = this;
  15988. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  15989. this.kernel = kernel;
  15990. this.onApply = function (effect) {
  15991. effect.setFloat2("screenSize", _this.width, _this.height);
  15992. effect.setArray("kernel", _this.kernel);
  15993. };
  15994. }
  15995. // Statics
  15996. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  15997. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  15998. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  15999. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16000. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16001. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16002. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16003. return ConvolutionPostProcess;
  16004. })(BABYLON.PostProcess);
  16005. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16006. })(BABYLON || (BABYLON = {}));
  16007. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16008. var BABYLON;
  16009. (function (BABYLON) {
  16010. var FxaaPostProcess = (function (_super) {
  16011. __extends(FxaaPostProcess, _super);
  16012. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16013. var _this = this;
  16014. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16015. this.onSizeChanged = function () {
  16016. _this.texelWidth = 1.0 / _this.width;
  16017. _this.texelHeight = 1.0 / _this.height;
  16018. };
  16019. this.onApply = function (effect) {
  16020. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16021. };
  16022. }
  16023. return FxaaPostProcess;
  16024. })(BABYLON.PostProcess);
  16025. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16026. })(BABYLON || (BABYLON = {}));
  16027. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16028. (function (BABYLON) {
  16029. var LensFlare = (function () {
  16030. function LensFlare(size, position, color, imgUrl, system) {
  16031. this.size = size;
  16032. this.position = position;
  16033. this.dispose = function () {
  16034. if (this.texture) {
  16035. this.texture.dispose();
  16036. }
  16037. // Remove from scene
  16038. var index = this._system.lensFlares.indexOf(this);
  16039. this._system.lensFlares.splice(index, 1);
  16040. };
  16041. this.color = color || new BABYLON.Color3(1, 1, 1);
  16042. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  16043. this._system = system;
  16044. system.lensFlares.push(this);
  16045. }
  16046. return LensFlare;
  16047. })();
  16048. BABYLON.LensFlare = LensFlare;
  16049. })(BABYLON || (BABYLON = {}));
  16050. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  16051. (function (BABYLON) {
  16052. var LensFlareSystem = (function () {
  16053. function LensFlareSystem(name, emitter, scene) {
  16054. this.name = name;
  16055. this.lensFlares = new Array();
  16056. this.borderLimit = 300;
  16057. this._vertexDeclaration = [2];
  16058. this._vertexStrideSize = 2 * 4;
  16059. this._isEnabled = true;
  16060. this._scene = scene;
  16061. this._emitter = emitter;
  16062. scene.lensFlareSystems.push(this);
  16063. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  16064. // VBO
  16065. var vertices = [];
  16066. vertices.push(1, 1);
  16067. vertices.push(-1, 1);
  16068. vertices.push(-1, -1);
  16069. vertices.push(1, -1);
  16070. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16071. // Indices
  16072. var indices = [];
  16073. indices.push(0);
  16074. indices.push(1);
  16075. indices.push(2);
  16076. indices.push(0);
  16077. indices.push(2);
  16078. indices.push(3);
  16079. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16080. // Effects
  16081. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  16082. }
  16083. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  16084. get: function () {
  16085. return this._isEnabled;
  16086. },
  16087. set: function (value) {
  16088. this._isEnabled = value;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. LensFlareSystem.prototype.getScene = function () {
  16094. return this._scene;
  16095. };
  16096. LensFlareSystem.prototype.getEmitter = function () {
  16097. return this._emitter;
  16098. };
  16099. LensFlareSystem.prototype.getEmitterPosition = function () {
  16100. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  16101. };
  16102. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  16103. var position = this.getEmitterPosition();
  16104. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  16105. this._positionX = position.x;
  16106. this._positionY = position.y;
  16107. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  16108. if (position.z > 0) {
  16109. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  16110. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  16111. return true;
  16112. }
  16113. }
  16114. return false;
  16115. };
  16116. LensFlareSystem.prototype._isVisible = function () {
  16117. if (!this._isEnabled) {
  16118. return false;
  16119. }
  16120. var emitterPosition = this.getEmitterPosition();
  16121. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  16122. var distance = direction.length();
  16123. direction.normalize();
  16124. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  16125. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  16126. return !pickInfo.hit || pickInfo.distance > distance;
  16127. };
  16128. LensFlareSystem.prototype.render = function () {
  16129. if (!this._effect.isReady())
  16130. return false;
  16131. var engine = this._scene.getEngine();
  16132. var viewport = this._scene.activeCamera.viewport;
  16133. var globalViewport = viewport.toGlobal(engine);
  16134. // Position
  16135. if (!this.computeEffectivePosition(globalViewport)) {
  16136. return false;
  16137. }
  16138. // Visibility
  16139. if (!this._isVisible()) {
  16140. return false;
  16141. }
  16142. // Intensity
  16143. var awayX;
  16144. var awayY;
  16145. if (this._positionX < this.borderLimit + globalViewport.x) {
  16146. awayX = this.borderLimit + globalViewport.x - this._positionX;
  16147. }
  16148. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  16149. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  16150. }
  16151. else {
  16152. awayX = 0;
  16153. }
  16154. if (this._positionY < this.borderLimit + globalViewport.y) {
  16155. awayY = this.borderLimit + globalViewport.y - this._positionY;
  16156. }
  16157. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  16158. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  16159. }
  16160. else {
  16161. awayY = 0;
  16162. }
  16163. var away = (awayX > awayY) ? awayX : awayY;
  16164. if (away > this.borderLimit) {
  16165. away = this.borderLimit;
  16166. }
  16167. var intensity = 1.0 - (away / this.borderLimit);
  16168. if (intensity < 0) {
  16169. return false;
  16170. }
  16171. if (intensity > 1.0) {
  16172. intensity = 1.0;
  16173. }
  16174. // Position
  16175. var centerX = globalViewport.x + globalViewport.width / 2;
  16176. var centerY = globalViewport.y + globalViewport.height / 2;
  16177. var distX = centerX - this._positionX;
  16178. var distY = centerY - this._positionY;
  16179. // Effects
  16180. engine.enableEffect(this._effect);
  16181. engine.setState(false);
  16182. engine.setDepthBuffer(false);
  16183. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16184. // VBOs
  16185. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  16186. for (var index = 0; index < this.lensFlares.length; index++) {
  16187. var flare = this.lensFlares[index];
  16188. var x = centerX - (distX * flare.position);
  16189. var y = centerY - (distY * flare.position);
  16190. var cw = flare.size;
  16191. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  16192. var cx = 2 * (x / globalViewport.width) - 1.0;
  16193. var cy = 1.0 - 2 * (y / globalViewport.height);
  16194. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  16195. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  16196. // Texture
  16197. this._effect.setTexture("textureSampler", flare.texture);
  16198. // Color
  16199. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  16200. // Draw order
  16201. engine.draw(true, 0, 6);
  16202. }
  16203. engine.setDepthBuffer(true);
  16204. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16205. return true;
  16206. };
  16207. LensFlareSystem.prototype.dispose = function () {
  16208. if (this._vertexBuffer) {
  16209. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16210. this._vertexBuffer = null;
  16211. }
  16212. if (this._indexBuffer) {
  16213. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16214. this._indexBuffer = null;
  16215. }
  16216. while (this.lensFlares.length) {
  16217. this.lensFlares[0].dispose();
  16218. }
  16219. // Remove from scene
  16220. var index = this._scene.lensFlareSystems.indexOf(this);
  16221. this._scene.lensFlareSystems.splice(index, 1);
  16222. };
  16223. return LensFlareSystem;
  16224. })();
  16225. BABYLON.LensFlareSystem = LensFlareSystem;
  16226. })(BABYLON || (BABYLON = {}));
  16227. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  16228. (function (BABYLON) {
  16229. var IntersectionInfo = (function () {
  16230. function IntersectionInfo(bu, bv, distance) {
  16231. this.bu = bu;
  16232. this.bv = bv;
  16233. this.distance = distance;
  16234. this.faceId = 0;
  16235. }
  16236. return IntersectionInfo;
  16237. })();
  16238. BABYLON.IntersectionInfo = IntersectionInfo;
  16239. var PickingInfo = (function () {
  16240. function PickingInfo() {
  16241. this.hit = false;
  16242. this.distance = 0;
  16243. this.pickedPoint = null;
  16244. this.pickedMesh = null;
  16245. this.bu = 0;
  16246. this.bv = 0;
  16247. this.faceId = -1;
  16248. }
  16249. // Methods
  16250. PickingInfo.prototype.getNormal = function () {
  16251. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  16252. return null;
  16253. }
  16254. var indices = this.pickedMesh.getIndices();
  16255. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  16256. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  16257. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  16258. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  16259. normal0 = normal0.scale(this.bu);
  16260. normal1 = normal1.scale(this.bv);
  16261. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  16262. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  16263. };
  16264. PickingInfo.prototype.getTextureCoordinates = function () {
  16265. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  16266. return null;
  16267. }
  16268. var indices = this.pickedMesh.getIndices();
  16269. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  16270. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  16271. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  16272. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  16273. uv0 = uv0.scale(this.bu);
  16274. uv1 = uv1.scale(this.bv);
  16275. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  16276. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  16277. };
  16278. return PickingInfo;
  16279. })();
  16280. BABYLON.PickingInfo = PickingInfo;
  16281. })(BABYLON || (BABYLON = {}));
  16282. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  16283. (function (BABYLON) {
  16284. var FilesInput = (function () {
  16285. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  16286. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  16287. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  16288. this.engine = p_engine;
  16289. this.canvas = p_canvas;
  16290. this.currentScene = p_scene;
  16291. this.sceneLoadedCallback = p_sceneLoadedCallback;
  16292. this.progressCallback = p_progressCallback;
  16293. this.additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  16294. this.textureLoadingCallback = p_textureLoadingCallback;
  16295. this.startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  16296. }
  16297. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  16298. var _this = this;
  16299. if (p_elementToMonitor) {
  16300. this.elementToMonitor = p_elementToMonitor;
  16301. this.elementToMonitor.addEventListener("dragenter", function (e) {
  16302. _this.drag(e);
  16303. }, false);
  16304. this.elementToMonitor.addEventListener("dragover", function (e) {
  16305. _this.drag(e);
  16306. }, false);
  16307. this.elementToMonitor.addEventListener("drop", function (e) {
  16308. _this.drop(e);
  16309. }, false);
  16310. }
  16311. };
  16312. FilesInput.prototype.renderFunction = function () {
  16313. if (this.additionnalRenderLoopLogicCallback) {
  16314. this.additionnalRenderLoopLogicCallback();
  16315. }
  16316. if (this.currentScene) {
  16317. if (this.textureLoadingCallback) {
  16318. var remaining = this.currentScene.getWaitingItemsCount();
  16319. if (remaining > 0) {
  16320. this.textureLoadingCallback(remaining);
  16321. }
  16322. }
  16323. this.currentScene.render();
  16324. }
  16325. };
  16326. FilesInput.prototype.drag = function (e) {
  16327. e.stopPropagation();
  16328. e.preventDefault();
  16329. };
  16330. FilesInput.prototype.drop = function (eventDrop) {
  16331. eventDrop.stopPropagation();
  16332. eventDrop.preventDefault();
  16333. this.loadFiles(eventDrop);
  16334. };
  16335. FilesInput.prototype.loadFiles = function (event) {
  16336. var _this = this;
  16337. var that = this;
  16338. if (this.startingProcessingFilesCallback)
  16339. this.startingProcessingFilesCallback();
  16340. var sceneFileToLoad;
  16341. var filesToLoad;
  16342. // Handling data transfer via drag'n'drop
  16343. if (event && event.dataTransfer && event.dataTransfer.files) {
  16344. filesToLoad = event.dataTransfer.files;
  16345. }
  16346. // Handling files from input files
  16347. if (event && event.target && event.target.files) {
  16348. filesToLoad = event.target.files;
  16349. }
  16350. if (filesToLoad && filesToLoad.length > 0) {
  16351. for (var i = 0; i < filesToLoad.length; i++) {
  16352. switch (filesToLoad[i].type) {
  16353. case "image/jpeg":
  16354. case "image/png":
  16355. BABYLON.FilesInput.FilesTextures[filesToLoad[i].name] = filesToLoad[i];
  16356. break;
  16357. case "image/targa":
  16358. case "image/vnd.ms-dds":
  16359. BABYLON.FilesInput.FilesToLoad[filesToLoad[i].name] = filesToLoad[i];
  16360. break;
  16361. default:
  16362. 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) {
  16363. sceneFileToLoad = filesToLoad[i];
  16364. }
  16365. break;
  16366. }
  16367. }
  16368. // If a ".babylon" file has been provided
  16369. if (sceneFileToLoad) {
  16370. if (this.currentScene) {
  16371. this.engine.stopRenderLoop();
  16372. this.currentScene.dispose();
  16373. }
  16374. BABYLON.SceneLoader.Load("file:", sceneFileToLoad, this.engine, function (newScene) {
  16375. that.currentScene = newScene;
  16376. // Wait for textures and shaders to be ready
  16377. that.currentScene.executeWhenReady(function () {
  16378. // Attach camera to canvas inputs
  16379. if (that.currentScene.activeCamera) {
  16380. that.currentScene.activeCamera.attachControl(that.canvas);
  16381. }
  16382. if (that.sceneLoadedCallback) {
  16383. that.sceneLoadedCallback(sceneFileToLoad, that.currentScene);
  16384. }
  16385. that.engine.runRenderLoop(function () {
  16386. that.renderFunction();
  16387. });
  16388. });
  16389. }, function (progress) {
  16390. if (_this.progressCallback) {
  16391. _this.progressCallback(progress);
  16392. }
  16393. });
  16394. }
  16395. else {
  16396. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  16397. }
  16398. }
  16399. };
  16400. FilesInput.FilesTextures = new Array();
  16401. FilesInput.FilesToLoad = new Array();
  16402. return FilesInput;
  16403. })();
  16404. BABYLON.FilesInput = FilesInput;
  16405. })(BABYLON || (BABYLON = {}));
  16406. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  16407. (function (BABYLON) {
  16408. var OimoJSPlugin = (function () {
  16409. function OimoJSPlugin() {
  16410. this._registeredMeshes = [];
  16411. /**
  16412. * Update the body position according to the mesh position
  16413. * @param mesh
  16414. */
  16415. this.updateBodyPosition = function (mesh) {
  16416. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16417. var registeredMesh = this._registeredMeshes[index];
  16418. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16419. var body = registeredMesh.body.body;
  16420. mesh.computeWorldMatrix(true);
  16421. var center = mesh.getBoundingInfo().boundingBox.center;
  16422. body.setPosition(center.x, center.y, center.z);
  16423. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  16424. return;
  16425. }
  16426. // Case where the parent has been updated
  16427. if (registeredMesh.mesh.parent === mesh) {
  16428. mesh.computeWorldMatrix(true);
  16429. registeredMesh.mesh.computeWorldMatrix(true);
  16430. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  16431. var absoluteRotation = mesh.rotation;
  16432. body = registeredMesh.body.body;
  16433. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  16434. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  16435. return;
  16436. }
  16437. }
  16438. };
  16439. }
  16440. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  16441. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  16442. };
  16443. OimoJSPlugin.prototype.initialize = function (iterations) {
  16444. this._world = new OIMO.World();
  16445. this._world.clear();
  16446. };
  16447. OimoJSPlugin.prototype.setGravity = function (gravity) {
  16448. this._world.gravity = gravity;
  16449. };
  16450. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  16451. var body = null;
  16452. this.unregisterMesh(mesh);
  16453. mesh.computeWorldMatrix(true);
  16454. switch (impostor) {
  16455. case BABYLON.PhysicsEngine.SphereImpostor:
  16456. var initialRotation = null;
  16457. if (mesh.rotationQuaternion) {
  16458. initialRotation = mesh.rotationQuaternion.clone();
  16459. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16460. mesh.computeWorldMatrix(true);
  16461. }
  16462. var bbox = mesh.getBoundingInfo().boundingBox;
  16463. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16464. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16465. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16466. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16467. // The delta between the mesh position and the mesh bounding box center
  16468. var deltaPosition = mesh.position.subtract(bbox.center);
  16469. // Transform delta position with the rotation
  16470. if (initialRotation) {
  16471. var m = new BABYLON.Matrix();
  16472. initialRotation.toRotationMatrix(m);
  16473. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16474. }
  16475. body = new OIMO.Body({
  16476. type: 'sphere',
  16477. size: [size],
  16478. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16479. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16480. move: options.mass != 0,
  16481. config: [options.mass, options.friction, options.restitution],
  16482. world: this._world
  16483. });
  16484. // Restore rotation
  16485. if (initialRotation) {
  16486. body.setQuaternion(initialRotation);
  16487. }
  16488. this._registeredMeshes.push({
  16489. mesh: mesh,
  16490. body: body,
  16491. delta: deltaPosition
  16492. });
  16493. break;
  16494. case BABYLON.PhysicsEngine.PlaneImpostor:
  16495. case BABYLON.PhysicsEngine.BoxImpostor:
  16496. initialRotation = null;
  16497. if (mesh.rotationQuaternion) {
  16498. initialRotation = mesh.rotationQuaternion.clone();
  16499. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16500. mesh.computeWorldMatrix(true);
  16501. }
  16502. bbox = mesh.getBoundingInfo().boundingBox;
  16503. var min = bbox.minimumWorld;
  16504. var max = bbox.maximumWorld;
  16505. var box = max.subtract(min);
  16506. var sizeX = this._checkWithEpsilon(box.x);
  16507. var sizeY = this._checkWithEpsilon(box.y);
  16508. var sizeZ = this._checkWithEpsilon(box.z);
  16509. // The delta between the mesh position and the mesh boudning box center
  16510. deltaPosition = mesh.position.subtract(bbox.center);
  16511. // Transform delta position with the rotation
  16512. if (initialRotation) {
  16513. m = new BABYLON.Matrix();
  16514. initialRotation.toRotationMatrix(m);
  16515. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  16516. }
  16517. body = new OIMO.Body({
  16518. type: 'box',
  16519. size: [sizeX, sizeY, sizeZ],
  16520. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  16521. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  16522. move: options.mass != 0,
  16523. config: [options.mass, options.friction, options.restitution],
  16524. world: this._world
  16525. });
  16526. if (initialRotation) {
  16527. body.setQuaternion(initialRotation);
  16528. }
  16529. this._registeredMeshes.push({
  16530. mesh: mesh,
  16531. body: body,
  16532. delta: deltaPosition
  16533. });
  16534. break;
  16535. }
  16536. return body;
  16537. };
  16538. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  16539. var types = [], sizes = [], positions = [], rotations = [];
  16540. var initialMesh = parts[0].mesh;
  16541. for (var index = 0; index < parts.length; index++) {
  16542. var part = parts[index];
  16543. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  16544. types.push(bodyParameters.type);
  16545. sizes.push.apply(sizes, bodyParameters.size);
  16546. positions.push.apply(positions, bodyParameters.pos);
  16547. rotations.push.apply(rotations, bodyParameters.rot);
  16548. }
  16549. var body = new OIMO.Body({
  16550. type: types,
  16551. size: sizes,
  16552. pos: positions,
  16553. rot: rotations,
  16554. move: options.mass != 0,
  16555. config: [options.mass, options.friction, options.restitution],
  16556. world: this._world
  16557. });
  16558. this._registeredMeshes.push({
  16559. mesh: initialMesh,
  16560. body: body
  16561. });
  16562. return body;
  16563. };
  16564. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  16565. var bodyParameters = null;
  16566. var mesh = part.mesh;
  16567. switch (part.impostor) {
  16568. case BABYLON.PhysicsEngine.SphereImpostor:
  16569. var bbox = mesh.getBoundingInfo().boundingBox;
  16570. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  16571. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  16572. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  16573. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  16574. bodyParameters = {
  16575. type: 'sphere',
  16576. /* bug with oimo : sphere needs 3 sizes in this case */
  16577. size: [size, -1, -1],
  16578. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  16579. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16580. };
  16581. break;
  16582. case BABYLON.PhysicsEngine.PlaneImpostor:
  16583. case BABYLON.PhysicsEngine.BoxImpostor:
  16584. bbox = mesh.getBoundingInfo().boundingBox;
  16585. var min = bbox.minimumWorld;
  16586. var max = bbox.maximumWorld;
  16587. var box = max.subtract(min);
  16588. var sizeX = this._checkWithEpsilon(box.x);
  16589. var sizeY = this._checkWithEpsilon(box.y);
  16590. var sizeZ = this._checkWithEpsilon(box.z);
  16591. var relativePosition = mesh.position;
  16592. bodyParameters = {
  16593. type: 'box',
  16594. size: [sizeX, sizeY, sizeZ],
  16595. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  16596. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  16597. };
  16598. break;
  16599. }
  16600. return bodyParameters;
  16601. };
  16602. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  16603. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16604. var registeredMesh = this._registeredMeshes[index];
  16605. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16606. if (registeredMesh.body) {
  16607. this._world.removeRigidBody(registeredMesh.body.body);
  16608. this._unbindBody(registeredMesh.body);
  16609. }
  16610. this._registeredMeshes.splice(index, 1);
  16611. return;
  16612. }
  16613. }
  16614. };
  16615. OimoJSPlugin.prototype._unbindBody = function (body) {
  16616. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16617. var registeredMesh = this._registeredMeshes[index];
  16618. if (registeredMesh.body === body) {
  16619. registeredMesh.body = null;
  16620. }
  16621. }
  16622. };
  16623. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  16624. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16625. var registeredMesh = this._registeredMeshes[index];
  16626. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  16627. // Get object mass to have a behaviour similar to cannon.js
  16628. var mass = registeredMesh.body.body.massInfo.mass;
  16629. // The force is scaled with the mass of object
  16630. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  16631. return;
  16632. }
  16633. }
  16634. };
  16635. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16636. var body1 = null, body2 = null;
  16637. for (var index = 0; index < this._registeredMeshes.length; index++) {
  16638. var registeredMesh = this._registeredMeshes[index];
  16639. if (registeredMesh.mesh === mesh1) {
  16640. body1 = registeredMesh.body.body;
  16641. }
  16642. else if (registeredMesh.mesh === mesh2) {
  16643. body2 = registeredMesh.body.body;
  16644. }
  16645. }
  16646. if (!body1 || !body2) {
  16647. return false;
  16648. }
  16649. if (!options) {
  16650. options = {};
  16651. }
  16652. new OIMO.Link({
  16653. type: options.type,
  16654. body1: body1,
  16655. body2: body2,
  16656. min: options.min,
  16657. max: options.max,
  16658. axe1: options.axe1,
  16659. axe2: options.axe2,
  16660. pos1: [pivot1.x, pivot1.y, pivot1.z],
  16661. pos2: [pivot2.x, pivot2.y, pivot2.z],
  16662. collision: options.collision,
  16663. spring: options.spring,
  16664. world: this._world
  16665. });
  16666. return true;
  16667. };
  16668. OimoJSPlugin.prototype.dispose = function () {
  16669. this._world.clear();
  16670. while (this._registeredMeshes.length) {
  16671. this.unregisterMesh(this._registeredMeshes[0].mesh);
  16672. }
  16673. };
  16674. OimoJSPlugin.prototype.isSupported = function () {
  16675. return OIMO !== undefined;
  16676. };
  16677. OimoJSPlugin.prototype._getLastShape = function (body) {
  16678. var lastShape = body.shapes;
  16679. while (lastShape.next) {
  16680. lastShape = lastShape.next;
  16681. }
  16682. return lastShape;
  16683. };
  16684. OimoJSPlugin.prototype.runOneStep = function (time) {
  16685. this._world.step();
  16686. // Update the position of all registered meshes
  16687. var i = this._registeredMeshes.length;
  16688. var m;
  16689. while (i--) {
  16690. var body = this._registeredMeshes[i].body.body;
  16691. var mesh = this._registeredMeshes[i].mesh;
  16692. var delta = this._registeredMeshes[i].delta;
  16693. if (!body.sleeping) {
  16694. if (body.shapes.next) {
  16695. var parentShape = this._getLastShape(body);
  16696. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  16697. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  16698. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  16699. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  16700. if (!mesh.rotationQuaternion) {
  16701. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16702. }
  16703. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16704. mesh.computeWorldMatrix();
  16705. }
  16706. else {
  16707. m = body.getMatrix();
  16708. mtx = BABYLON.Matrix.FromArray(m);
  16709. // Body position
  16710. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  16711. if (!delta) {
  16712. mesh.position.x = bodyX;
  16713. mesh.position.y = bodyY;
  16714. mesh.position.z = bodyZ;
  16715. }
  16716. else {
  16717. mesh.position.x = bodyX + delta.x;
  16718. mesh.position.y = bodyY + delta.y;
  16719. mesh.position.z = bodyZ + delta.z;
  16720. }
  16721. if (!mesh.rotationQuaternion) {
  16722. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  16723. }
  16724. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  16725. mesh.computeWorldMatrix();
  16726. }
  16727. }
  16728. }
  16729. };
  16730. return OimoJSPlugin;
  16731. })();
  16732. BABYLON.OimoJSPlugin = OimoJSPlugin;
  16733. })(BABYLON || (BABYLON = {}));
  16734. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  16735. (function (BABYLON) {
  16736. var PhysicsEngine = (function () {
  16737. function PhysicsEngine(plugin) {
  16738. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  16739. }
  16740. PhysicsEngine.prototype._initialize = function (gravity) {
  16741. this._currentPlugin.initialize();
  16742. this._setGravity(gravity);
  16743. };
  16744. PhysicsEngine.prototype._runOneStep = function (delta) {
  16745. if (delta > 0.1) {
  16746. delta = 0.1;
  16747. }
  16748. else if (delta <= 0) {
  16749. delta = 1.0 / 60.0;
  16750. }
  16751. this._currentPlugin.runOneStep(delta);
  16752. };
  16753. PhysicsEngine.prototype._setGravity = function (gravity) {
  16754. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  16755. this._currentPlugin.setGravity(this.gravity);
  16756. };
  16757. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  16758. return this._currentPlugin.registerMesh(mesh, impostor, options);
  16759. };
  16760. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  16761. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  16762. };
  16763. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  16764. this._currentPlugin.unregisterMesh(mesh);
  16765. };
  16766. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  16767. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  16768. };
  16769. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  16770. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  16771. };
  16772. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  16773. this._currentPlugin.updateBodyPosition(mesh);
  16774. };
  16775. PhysicsEngine.prototype.dispose = function () {
  16776. this._currentPlugin.dispose();
  16777. };
  16778. PhysicsEngine.prototype.isSupported = function () {
  16779. return this._currentPlugin.isSupported();
  16780. };
  16781. // Statics
  16782. PhysicsEngine.NoImpostor = 0;
  16783. PhysicsEngine.SphereImpostor = 1;
  16784. PhysicsEngine.BoxImpostor = 2;
  16785. PhysicsEngine.PlaneImpostor = 3;
  16786. PhysicsEngine.MeshImpostor = 4;
  16787. PhysicsEngine.CapsuleImpostor = 5;
  16788. PhysicsEngine.ConeImpostor = 6;
  16789. PhysicsEngine.CylinderImpostor = 7;
  16790. PhysicsEngine.ConvexHullImpostor = 8;
  16791. PhysicsEngine.Epsilon = 0.001;
  16792. return PhysicsEngine;
  16793. })();
  16794. BABYLON.PhysicsEngine = PhysicsEngine;
  16795. })(BABYLON || (BABYLON = {}));
  16796. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  16797. (function (BABYLON) {
  16798. var serializeLight = function (light) {
  16799. var serializationObject = {};
  16800. serializationObject.name = light.name;
  16801. serializationObject.id = light.id;
  16802. serializationObject.tags = BABYLON.Tags.GetTags(light);
  16803. if (light instanceof BABYLON.PointLight) {
  16804. serializationObject.type = 0;
  16805. serializationObject.position = light.position.asArray();
  16806. }
  16807. else if (light instanceof BABYLON.DirectionalLight) {
  16808. serializationObject.type = 1;
  16809. var directionalLight = light;
  16810. serializationObject.position = directionalLight.position.asArray();
  16811. serializationObject.direction = directionalLight.direction.asArray();
  16812. }
  16813. else if (light instanceof BABYLON.SpotLight) {
  16814. serializationObject.type = 2;
  16815. var spotLight = light;
  16816. serializationObject.position = spotLight.position.asArray();
  16817. serializationObject.direction = spotLight.position.asArray();
  16818. serializationObject.angle = spotLight.angle;
  16819. serializationObject.exponent = spotLight.exponent;
  16820. }
  16821. else if (light instanceof BABYLON.HemisphericLight) {
  16822. serializationObject.type = 3;
  16823. var hemisphericLight = light;
  16824. serializationObject.direction = hemisphericLight.direction.asArray();
  16825. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  16826. }
  16827. if (light.intensity) {
  16828. serializationObject.intensity = light.intensity;
  16829. }
  16830. serializationObject.range = light.range;
  16831. serializationObject.diffuse = light.diffuse.asArray();
  16832. serializationObject.specular = light.specular.asArray();
  16833. return serializationObject;
  16834. };
  16835. var serializeFresnelParameter = function (fresnelParameter) {
  16836. var serializationObject = {};
  16837. serializationObject.isEnabled = fresnelParameter.isEnabled;
  16838. serializationObject.leftColor = fresnelParameter.leftColor;
  16839. serializationObject.rightColor = fresnelParameter.rightColor;
  16840. serializationObject.bias = fresnelParameter.bias;
  16841. serializationObject.power = fresnelParameter.power;
  16842. return serializationObject;
  16843. };
  16844. var serializeCamera = function (camera) {
  16845. var serializationObject = {};
  16846. serializationObject.name = camera.name;
  16847. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  16848. serializationObject.id = camera.id;
  16849. serializationObject.position = camera.position.asArray();
  16850. // Parent
  16851. if (camera.parent) {
  16852. serializationObject.parentId = camera.parent.id;
  16853. }
  16854. // Target
  16855. serializationObject.rotation = camera.rotation.asArray();
  16856. // Locked target
  16857. if (camera.lockedTarget && camera.lockedTarget.id) {
  16858. serializationObject.lockedTargetId = camera.lockedTarget.id;
  16859. }
  16860. serializationObject.fov = camera.fov;
  16861. serializationObject.minZ = camera.minZ;
  16862. serializationObject.maxZ = camera.maxZ;
  16863. serializationObject.speed = camera.speed;
  16864. serializationObject.inertia = camera.inertia;
  16865. serializationObject.checkCollisions = camera.checkCollisions;
  16866. serializationObject.applyGravity = camera.applyGravity;
  16867. if (camera.ellipsoid) {
  16868. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  16869. }
  16870. // Animations
  16871. appendAnimations(camera, serializationObject);
  16872. // Layer mask
  16873. serializationObject.layerMask = camera.layerMask;
  16874. return serializationObject;
  16875. };
  16876. var appendAnimations = function (source, destination) {
  16877. if (source.animations) {
  16878. destination.animations = [];
  16879. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  16880. var animation = source.animations[animationIndex];
  16881. destination.animations.push(serializeAnimation(animation));
  16882. }
  16883. }
  16884. };
  16885. var serializeAnimation = function (animation) {
  16886. var serializationObject = {};
  16887. serializationObject.name = animation.name;
  16888. serializationObject.property = animation.targetProperty;
  16889. serializationObject.framePerSecond = animation.framePerSecond;
  16890. serializationObject.dataType = animation.dataType;
  16891. serializationObject.loopBehavior = animation.loopMode;
  16892. var dataType = animation.dataType;
  16893. serializationObject.keys = [];
  16894. var keys = animation.getKeys();
  16895. for (var index = 0; index < keys.length; index++) {
  16896. var animationKey = keys[index];
  16897. var key = {};
  16898. key.frame = animationKey.frame;
  16899. switch (dataType) {
  16900. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  16901. key.values = [animationKey.value];
  16902. break;
  16903. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  16904. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  16905. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  16906. key.values = animationKey.value.asArray();
  16907. break;
  16908. }
  16909. serializationObject.keys.push(key);
  16910. }
  16911. return serializationObject;
  16912. };
  16913. var serializeMultiMaterial = function (material) {
  16914. var serializationObject = {};
  16915. serializationObject.name = material.name;
  16916. serializationObject.id = material.id;
  16917. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16918. serializationObject.materials = [];
  16919. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  16920. var subMat = material.subMaterials[matIndex];
  16921. if (subMat) {
  16922. serializationObject.materials.push(subMat.id);
  16923. }
  16924. else {
  16925. serializationObject.materials.push(null);
  16926. }
  16927. }
  16928. return serializationObject;
  16929. };
  16930. var serializeMaterial = function (material) {
  16931. var serializationObject = {};
  16932. serializationObject.name = material.name;
  16933. serializationObject.ambient = material.ambientColor.asArray();
  16934. serializationObject.diffuse = material.diffuseColor.asArray();
  16935. serializationObject.specular = material.specularColor.asArray();
  16936. serializationObject.specularPower = material.specularPower;
  16937. serializationObject.emissive = material.emissiveColor.asArray();
  16938. serializationObject.alpha = material.alpha;
  16939. serializationObject.id = material.id;
  16940. serializationObject.tags = BABYLON.Tags.GetTags(material);
  16941. serializationObject.backFaceCulling = material.backFaceCulling;
  16942. if (material.diffuseTexture) {
  16943. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  16944. }
  16945. if (material.diffuseFresnelParameters) {
  16946. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  16947. }
  16948. if (material.ambientTexture) {
  16949. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  16950. }
  16951. if (material.opacityTexture) {
  16952. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  16953. }
  16954. if (material.opacityFresnelParameters) {
  16955. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  16956. }
  16957. if (material.reflectionTexture) {
  16958. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  16959. }
  16960. if (material.reflectionFresnelParameters) {
  16961. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  16962. }
  16963. if (material.emissiveTexture) {
  16964. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  16965. }
  16966. if (material.emissiveFresnelParameters) {
  16967. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  16968. }
  16969. if (material.specularTexture) {
  16970. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  16971. }
  16972. if (material.bumpTexture) {
  16973. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  16974. }
  16975. return serializationObject;
  16976. };
  16977. var serializeTexture = function (texture) {
  16978. var serializationObject = {};
  16979. if (!texture.name) {
  16980. return null;
  16981. }
  16982. if (texture instanceof BABYLON.CubeTexture) {
  16983. serializationObject.name = texture.name;
  16984. serializationObject.hasAlpha = texture.hasAlpha;
  16985. serializationObject.level = texture.level;
  16986. serializationObject.coordinatesMode = texture.coordinatesMode;
  16987. return serializationObject;
  16988. }
  16989. if (texture instanceof BABYLON.MirrorTexture) {
  16990. var mirrorTexture = texture;
  16991. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  16992. serializationObject.renderList = [];
  16993. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  16994. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  16995. }
  16996. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  16997. }
  16998. else if (texture instanceof BABYLON.RenderTargetTexture) {
  16999. var renderTargetTexture = texture;
  17000. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17001. serializationObject.renderList = [];
  17002. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17003. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17004. }
  17005. }
  17006. var regularTexture = texture;
  17007. serializationObject.name = texture.name;
  17008. serializationObject.hasAlpha = texture.hasAlpha;
  17009. serializationObject.level = texture.level;
  17010. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17011. serializationObject.coordinatesMode = texture.coordinatesMode;
  17012. serializationObject.uOffset = regularTexture.uOffset;
  17013. serializationObject.vOffset = regularTexture.vOffset;
  17014. serializationObject.uScale = regularTexture.uScale;
  17015. serializationObject.vScale = regularTexture.vScale;
  17016. serializationObject.uAng = regularTexture.uAng;
  17017. serializationObject.vAng = regularTexture.vAng;
  17018. serializationObject.wAng = regularTexture.wAng;
  17019. serializationObject.wrapU = texture.wrapU;
  17020. serializationObject.wrapV = texture.wrapV;
  17021. // Animations
  17022. appendAnimations(texture, serializationObject);
  17023. return serializationObject;
  17024. };
  17025. var serializeSkeleton = function (skeleton) {
  17026. var serializationObject = {};
  17027. serializationObject.name = skeleton.name;
  17028. serializationObject.id = skeleton.id;
  17029. serializationObject.bones = [];
  17030. for (var index = 0; index < skeleton.bones.length; index++) {
  17031. var bone = skeleton.bones[index];
  17032. var serializedBone = {
  17033. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17034. name: bone.name,
  17035. matrix: bone.getLocalMatrix().toArray()
  17036. };
  17037. serializationObject.bones.push(serializedBone);
  17038. if (bone.animations && bone.animations.length > 0) {
  17039. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17040. }
  17041. }
  17042. return serializationObject;
  17043. };
  17044. var serializeParticleSystem = function (particleSystem) {
  17045. var serializationObject = {};
  17046. serializationObject.emitterId = particleSystem.emitter.id;
  17047. serializationObject.capacity = particleSystem.getCapacity();
  17048. if (particleSystem.particleTexture) {
  17049. serializationObject.textureName = particleSystem.particleTexture.name;
  17050. }
  17051. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  17052. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  17053. serializationObject.minSize = particleSystem.minSize;
  17054. serializationObject.maxSize = particleSystem.maxSize;
  17055. serializationObject.minLifeTime = particleSystem.minLifeTime;
  17056. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  17057. serializationObject.emitRate = particleSystem.emitRate;
  17058. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  17059. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  17060. serializationObject.gravity = particleSystem.gravity.asArray();
  17061. serializationObject.direction1 = particleSystem.direction1.asArray();
  17062. serializationObject.direction2 = particleSystem.direction2.asArray();
  17063. serializationObject.color1 = particleSystem.color1.asArray();
  17064. serializationObject.color2 = particleSystem.color2.asArray();
  17065. serializationObject.colorDead = particleSystem.colorDead.asArray();
  17066. serializationObject.updateSpeed = particleSystem.updateSpeed;
  17067. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  17068. serializationObject.textureMask = particleSystem.textureMask.asArray();
  17069. serializationObject.blendMode = particleSystem.blendMode;
  17070. return serializationObject;
  17071. };
  17072. var serializeLensFlareSystem = function (lensFlareSystem) {
  17073. var serializationObject = {};
  17074. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  17075. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  17076. serializationObject.flares = [];
  17077. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  17078. var flare = lensFlareSystem.lensFlares[index];
  17079. serializationObject.flares.push({
  17080. size: flare.size,
  17081. position: flare.position,
  17082. color: flare.color.asArray(),
  17083. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  17084. });
  17085. }
  17086. return serializationObject;
  17087. };
  17088. var serializeShadowGenerator = function (light) {
  17089. var serializationObject = {};
  17090. var shadowGenerator = light.getShadowGenerator();
  17091. serializationObject.lightId = light.id;
  17092. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  17093. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  17094. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  17095. serializationObject.renderList = [];
  17096. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  17097. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  17098. serializationObject.renderList.push(mesh.id);
  17099. }
  17100. return serializationObject;
  17101. };
  17102. var serializedGeometries = [];
  17103. var serializeGeometry = function (geometry, serializationGeometries) {
  17104. if (serializedGeometries[geometry.id]) {
  17105. return;
  17106. }
  17107. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  17108. serializationGeometries.boxes.push(serializeBox(geometry));
  17109. }
  17110. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  17111. serializationGeometries.spheres.push(serializeSphere(geometry));
  17112. }
  17113. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  17114. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  17115. }
  17116. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  17117. serializationGeometries.toruses.push(serializeTorus(geometry));
  17118. }
  17119. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  17120. serializationGeometries.grounds.push(serializeGround(geometry));
  17121. }
  17122. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  17123. serializationGeometries.planes.push(serializePlane(geometry));
  17124. }
  17125. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  17126. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  17127. }
  17128. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  17129. throw new Error("Unknow primitive type");
  17130. }
  17131. else {
  17132. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  17133. }
  17134. serializedGeometries[geometry.id] = true;
  17135. };
  17136. var serializeGeometryBase = function (geometry) {
  17137. var serializationObject = {};
  17138. serializationObject.id = geometry.id;
  17139. if (BABYLON.Tags.HasTags(geometry)) {
  17140. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  17141. }
  17142. return serializationObject;
  17143. };
  17144. var serializeVertexData = function (vertexData) {
  17145. var serializationObject = serializeGeometryBase(vertexData);
  17146. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  17147. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  17148. }
  17149. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17150. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17151. }
  17152. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17153. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17154. }
  17155. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  17156. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  17157. }
  17158. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  17159. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  17160. }
  17161. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  17162. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  17163. serializationObject.matricesIndices._isExpanded = true;
  17164. }
  17165. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  17166. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  17167. }
  17168. serializationObject.indices = vertexData.getIndices();
  17169. return serializationObject;
  17170. };
  17171. var serializePrimitive = function (primitive) {
  17172. var serializationObject = serializeGeometryBase(primitive);
  17173. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  17174. return serializationObject;
  17175. };
  17176. var serializeBox = function (box) {
  17177. var serializationObject = serializePrimitive(box);
  17178. serializationObject.size = box.size;
  17179. return serializationObject;
  17180. };
  17181. var serializeSphere = function (sphere) {
  17182. var serializationObject = serializePrimitive(sphere);
  17183. serializationObject.segments = sphere.segments;
  17184. serializationObject.diameter = sphere.diameter;
  17185. return serializationObject;
  17186. };
  17187. var serializeCylinder = function (cylinder) {
  17188. var serializationObject = serializePrimitive(cylinder);
  17189. serializationObject.height = cylinder.height;
  17190. serializationObject.diameterTop = cylinder.diameterTop;
  17191. serializationObject.diameterBottom = cylinder.diameterBottom;
  17192. serializationObject.tessellation = cylinder.tessellation;
  17193. return serializationObject;
  17194. };
  17195. var serializeTorus = function (torus) {
  17196. var serializationObject = serializePrimitive(torus);
  17197. serializationObject.diameter = torus.diameter;
  17198. serializationObject.thickness = torus.thickness;
  17199. serializationObject.tessellation = torus.tessellation;
  17200. return serializationObject;
  17201. };
  17202. var serializeGround = function (ground) {
  17203. var serializationObject = serializePrimitive(ground);
  17204. serializationObject.width = ground.width;
  17205. serializationObject.height = ground.height;
  17206. serializationObject.subdivisions = ground.subdivisions;
  17207. return serializationObject;
  17208. };
  17209. var serializePlane = function (plane) {
  17210. var serializationObject = serializePrimitive(plane);
  17211. serializationObject.size = plane.size;
  17212. return serializationObject;
  17213. };
  17214. var serializeTorusKnot = function (torusKnot) {
  17215. var serializationObject = serializePrimitive(torusKnot);
  17216. serializationObject.radius = torusKnot.radius;
  17217. serializationObject.tube = torusKnot.tube;
  17218. serializationObject.radialSegments = torusKnot.radialSegments;
  17219. serializationObject.tubularSegments = torusKnot.tubularSegments;
  17220. serializationObject.p = torusKnot.p;
  17221. serializationObject.q = torusKnot.q;
  17222. return serializationObject;
  17223. };
  17224. var serializeMesh = function (mesh, serializationScene) {
  17225. var serializationObject = {};
  17226. serializationObject.name = mesh.name;
  17227. serializationObject.id = mesh.id;
  17228. if (BABYLON.Tags.HasTags(mesh)) {
  17229. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  17230. }
  17231. serializationObject.position = mesh.position.asArray();
  17232. if (mesh.rotationQuaternion) {
  17233. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  17234. }
  17235. else if (mesh.rotation) {
  17236. serializationObject.rotation = mesh.rotation.asArray();
  17237. }
  17238. serializationObject.scaling = mesh.scaling.asArray();
  17239. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  17240. serializationObject.isEnabled = mesh.isEnabled();
  17241. serializationObject.isVisible = mesh.isVisible;
  17242. serializationObject.infiniteDistance = mesh.infiniteDistance;
  17243. serializationObject.pickable = mesh.isPickable;
  17244. serializationObject.receiveShadows = mesh.receiveShadows;
  17245. serializationObject.billboardMode = mesh.billboardMode;
  17246. serializationObject.visibility = mesh.visibility;
  17247. serializationObject.checkCollisions = mesh.checkCollisions;
  17248. // Parent
  17249. if (mesh.parent) {
  17250. serializationObject.parentId = mesh.parent.id;
  17251. }
  17252. // Geometry
  17253. var geometry = mesh._geometry;
  17254. if (geometry) {
  17255. var geometryId = geometry.id;
  17256. serializationObject.geometryId = geometryId;
  17257. if (!mesh.getScene().getGeometryByID(geometryId)) {
  17258. // 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
  17259. serializeGeometry(geometry, serializationScene.geometries);
  17260. }
  17261. // SubMeshes
  17262. serializationObject.subMeshes = [];
  17263. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  17264. var subMesh = mesh.subMeshes[subIndex];
  17265. serializationObject.subMeshes.push({
  17266. materialIndex: subMesh.materialIndex,
  17267. verticesStart: subMesh.verticesStart,
  17268. verticesCount: subMesh.verticesCount,
  17269. indexStart: subMesh.indexStart,
  17270. indexCount: subMesh.indexCount
  17271. });
  17272. }
  17273. }
  17274. // Material
  17275. if (mesh.material) {
  17276. serializationObject.materialId = mesh.material.id;
  17277. }
  17278. else {
  17279. mesh.material = null;
  17280. }
  17281. // Skeleton
  17282. if (mesh.skeleton) {
  17283. serializationObject.skeletonId = mesh.skeleton.id;
  17284. }
  17285. // Physics
  17286. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  17287. serializationObject.physicsMass = mesh.getPhysicsMass();
  17288. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  17289. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  17290. switch (mesh.getPhysicsImpostor()) {
  17291. case BABYLON.PhysicsEngine.BoxImpostor:
  17292. serializationObject.physicsImpostor = 1;
  17293. break;
  17294. case BABYLON.PhysicsEngine.SphereImpostor:
  17295. serializationObject.physicsImpostor = 2;
  17296. break;
  17297. }
  17298. }
  17299. // Instances
  17300. serializationObject.instances = [];
  17301. for (var index = 0; index < mesh.instances.length; index++) {
  17302. var instance = mesh.instances[index];
  17303. var serializationInstance = {
  17304. name: instance.name,
  17305. position: instance.position,
  17306. rotation: instance.rotation,
  17307. rotationQuaternion: instance.rotationQuaternion,
  17308. scaling: instance.scaling
  17309. };
  17310. serializationObject.instances.push(serializationInstance);
  17311. // Animations
  17312. appendAnimations(instance, serializationInstance);
  17313. }
  17314. // Animations
  17315. appendAnimations(mesh, serializationObject);
  17316. // Layer mask
  17317. serializationObject.layerMask = mesh.layerMask;
  17318. return serializationObject;
  17319. };
  17320. var SceneSerializer = (function () {
  17321. function SceneSerializer() {
  17322. }
  17323. SceneSerializer.Serialize = function (scene) {
  17324. var serializationObject = {};
  17325. // Scene
  17326. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  17327. serializationObject.autoClear = scene.autoClear;
  17328. serializationObject.clearColor = scene.clearColor.asArray();
  17329. serializationObject.ambientColor = scene.ambientColor.asArray();
  17330. serializationObject.gravity = scene.gravity.asArray();
  17331. // Fog
  17332. if (scene.fogMode && scene.fogMode !== 0) {
  17333. serializationObject.fogMode = scene.fogMode;
  17334. serializationObject.fogColor = scene.fogColor.asArray();
  17335. serializationObject.fogStart = scene.fogStart;
  17336. serializationObject.fogEnd = scene.fogEnd;
  17337. serializationObject.fogDensity = scene.fogDensity;
  17338. }
  17339. // Lights
  17340. serializationObject.lights = [];
  17341. for (var index = 0; index < scene.lights.length; index++) {
  17342. var light = scene.lights[index];
  17343. serializationObject.lights.push(serializeLight(light));
  17344. }
  17345. // Cameras
  17346. serializationObject.cameras = [];
  17347. for (index = 0; index < scene.cameras.length; index++) {
  17348. var camera = scene.cameras[index];
  17349. if (camera instanceof BABYLON.FreeCamera) {
  17350. serializationObject.cameras.push(serializeCamera(camera));
  17351. }
  17352. }
  17353. if (scene.activeCamera) {
  17354. serializationObject.activeCameraID = scene.activeCamera.id;
  17355. }
  17356. // Materials
  17357. serializationObject.materials = [];
  17358. serializationObject.multiMaterials = [];
  17359. for (index = 0; index < scene.materials.length; index++) {
  17360. var material = scene.materials[index];
  17361. if (material instanceof BABYLON.StandardMaterial) {
  17362. serializationObject.materials.push(serializeMaterial(material));
  17363. }
  17364. else if (material instanceof BABYLON.MultiMaterial) {
  17365. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  17366. }
  17367. }
  17368. // Skeletons
  17369. serializationObject.skeletons = [];
  17370. for (index = 0; index < scene.skeletons.length; index++) {
  17371. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  17372. }
  17373. // Geometries
  17374. serializationObject.geometries = {};
  17375. serializationObject.geometries.boxes = [];
  17376. serializationObject.geometries.spheres = [];
  17377. serializationObject.geometries.cylinders = [];
  17378. serializationObject.geometries.toruses = [];
  17379. serializationObject.geometries.grounds = [];
  17380. serializationObject.geometries.planes = [];
  17381. serializationObject.geometries.torusKnots = [];
  17382. serializationObject.geometries.vertexData = [];
  17383. serializedGeometries = [];
  17384. var geometries = scene.getGeometries();
  17385. for (var index = 0; index < geometries.length; index++) {
  17386. var geometry = geometries[index];
  17387. if (geometry.isReady()) {
  17388. serializeGeometry(geometry, serializationObject.geometries);
  17389. }
  17390. }
  17391. // Meshes
  17392. serializationObject.meshes = [];
  17393. for (index = 0; index < scene.meshes.length; index++) {
  17394. var abstractMesh = scene.meshes[index];
  17395. if (abstractMesh instanceof BABYLON.Mesh) {
  17396. var mesh = abstractMesh;
  17397. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  17398. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  17399. }
  17400. }
  17401. }
  17402. // Particles Systems
  17403. serializationObject.particleSystems = [];
  17404. for (index = 0; index < scene.particleSystems.length; index++) {
  17405. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  17406. }
  17407. // Lens flares
  17408. serializationObject.lensFlareSystems = [];
  17409. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  17410. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  17411. }
  17412. // Shadows
  17413. serializationObject.shadowGenerators = [];
  17414. for (index = 0; index < scene.lights.length; index++) {
  17415. light = scene.lights[index];
  17416. if (light.getShadowGenerator()) {
  17417. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  17418. }
  17419. }
  17420. return serializationObject;
  17421. };
  17422. return SceneSerializer;
  17423. })();
  17424. BABYLON.SceneSerializer = SceneSerializer;
  17425. })(BABYLON || (BABYLON = {}));
  17426. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  17427. (function (BABYLON) {
  17428. var SceneLoader = (function () {
  17429. function SceneLoader() {
  17430. }
  17431. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  17432. get: function () {
  17433. return SceneLoader._ForceFullSceneLoadingForIncremental;
  17434. },
  17435. set: function (value) {
  17436. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  17442. get: function () {
  17443. return SceneLoader._ShowLoadingScreen;
  17444. },
  17445. set: function (value) {
  17446. SceneLoader._ShowLoadingScreen = value;
  17447. },
  17448. enumerable: true,
  17449. configurable: true
  17450. });
  17451. SceneLoader._getPluginForFilename = function (sceneFilename) {
  17452. var dotPosition = sceneFilename.lastIndexOf(".");
  17453. var queryStringPosition = sceneFilename.indexOf("?");
  17454. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  17455. for (var index = 0; index < this._registeredPlugins.length; index++) {
  17456. var plugin = this._registeredPlugins[index];
  17457. if (plugin.extensions.indexOf(extension) !== -1) {
  17458. return plugin;
  17459. }
  17460. }
  17461. return this._registeredPlugins[this._registeredPlugins.length - 1];
  17462. };
  17463. // Public functions
  17464. SceneLoader.RegisterPlugin = function (plugin) {
  17465. plugin.extensions = plugin.extensions.toLowerCase();
  17466. SceneLoader._registeredPlugins.push(plugin);
  17467. };
  17468. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17469. var manifestChecked = function (success) {
  17470. scene.database = database;
  17471. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  17472. var importMeshFromData = function (data) {
  17473. var meshes = [];
  17474. var particleSystems = [];
  17475. var skeletons = [];
  17476. try {
  17477. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  17478. if (onerror) {
  17479. onerror(scene, 'unable to load the scene');
  17480. }
  17481. return;
  17482. }
  17483. }
  17484. catch (e) {
  17485. if (onerror) {
  17486. onerror(scene, e);
  17487. }
  17488. return;
  17489. }
  17490. if (onsuccess) {
  17491. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  17492. onsuccess(meshes, particleSystems, skeletons);
  17493. }
  17494. };
  17495. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17496. // Direct load
  17497. importMeshFromData(sceneFilename.substr(5));
  17498. return;
  17499. }
  17500. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  17501. importMeshFromData(data);
  17502. }, progressCallBack, database);
  17503. };
  17504. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17505. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17506. };
  17507. /**
  17508. * Load a scene
  17509. * @param rootUrl a string that defines the root url for scene and resources
  17510. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17511. * @param engine is the instance of BABYLON.Engine to use to create the scene
  17512. */
  17513. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  17514. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  17515. };
  17516. /**
  17517. * Append a scene
  17518. * @param rootUrl a string that defines the root url for scene and resources
  17519. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  17520. * @param scene is the instance of BABYLON.Scene to append to
  17521. */
  17522. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  17523. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  17524. var database;
  17525. if (SceneLoader.ShowLoadingScreen) {
  17526. scene.getEngine().displayLoadingUI();
  17527. }
  17528. var loadSceneFromData = function (data) {
  17529. scene.database = database;
  17530. if (!plugin.load(scene, data, rootUrl)) {
  17531. if (onerror) {
  17532. onerror(scene);
  17533. }
  17534. scene.getEngine().hideLoadingUI();
  17535. return;
  17536. }
  17537. if (onsuccess) {
  17538. onsuccess(scene);
  17539. }
  17540. if (SceneLoader.ShowLoadingScreen) {
  17541. scene.executeWhenReady(function () {
  17542. scene.getEngine().hideLoadingUI();
  17543. });
  17544. }
  17545. };
  17546. var manifestChecked = function (success) {
  17547. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  17548. };
  17549. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  17550. // Direct load
  17551. loadSceneFromData(sceneFilename.substr(5));
  17552. return;
  17553. }
  17554. if (rootUrl.indexOf("file:") === -1) {
  17555. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  17556. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  17557. }
  17558. else {
  17559. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  17560. }
  17561. };
  17562. // Flags
  17563. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  17564. SceneLoader._ShowLoadingScreen = true;
  17565. // Members
  17566. SceneLoader._registeredPlugins = new Array();
  17567. return SceneLoader;
  17568. })();
  17569. BABYLON.SceneLoader = SceneLoader;
  17570. ;
  17571. })(BABYLON || (BABYLON = {}));
  17572. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  17573. (function (BABYLON) {
  17574. var Internals;
  17575. (function (Internals) {
  17576. var checkColors4 = function (colors, count) {
  17577. // Check if color3 was used
  17578. if (colors.length === count * 3) {
  17579. var colors4 = [];
  17580. for (var index = 0; index < colors.length; index += 3) {
  17581. var newIndex = (index / 3) * 4;
  17582. colors4[newIndex] = colors[index];
  17583. colors4[newIndex + 1] = colors[index + 1];
  17584. colors4[newIndex + 2] = colors[index + 2];
  17585. colors4[newIndex + 3] = 1.0;
  17586. }
  17587. return colors4;
  17588. }
  17589. return colors;
  17590. };
  17591. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  17592. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  17593. texture.name = parsedTexture.name;
  17594. texture.hasAlpha = parsedTexture.hasAlpha;
  17595. texture.level = parsedTexture.level;
  17596. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17597. return texture;
  17598. };
  17599. var loadTexture = function (rootUrl, parsedTexture, scene) {
  17600. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  17601. return null;
  17602. }
  17603. if (parsedTexture.isCube) {
  17604. return loadCubeTexture(rootUrl, parsedTexture, scene);
  17605. }
  17606. var texture;
  17607. if (parsedTexture.mirrorPlane) {
  17608. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17609. texture._waitingRenderList = parsedTexture.renderList;
  17610. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  17611. }
  17612. else if (parsedTexture.isRenderTarget) {
  17613. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  17614. texture._waitingRenderList = parsedTexture.renderList;
  17615. }
  17616. else {
  17617. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  17618. }
  17619. texture.name = parsedTexture.name;
  17620. texture.hasAlpha = parsedTexture.hasAlpha;
  17621. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  17622. texture.level = parsedTexture.level;
  17623. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  17624. texture.coordinatesMode = parsedTexture.coordinatesMode;
  17625. texture.uOffset = parsedTexture.uOffset;
  17626. texture.vOffset = parsedTexture.vOffset;
  17627. texture.uScale = parsedTexture.uScale;
  17628. texture.vScale = parsedTexture.vScale;
  17629. texture.uAng = parsedTexture.uAng;
  17630. texture.vAng = parsedTexture.vAng;
  17631. texture.wAng = parsedTexture.wAng;
  17632. texture.wrapU = parsedTexture.wrapU;
  17633. texture.wrapV = parsedTexture.wrapV;
  17634. // Animations
  17635. if (parsedTexture.animations) {
  17636. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  17637. var parsedAnimation = parsedTexture.animations[animationIndex];
  17638. texture.animations.push(parseAnimation(parsedAnimation));
  17639. }
  17640. }
  17641. return texture;
  17642. };
  17643. var parseSkeleton = function (parsedSkeleton, scene) {
  17644. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  17645. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  17646. var parsedBone = parsedSkeleton.bones[index];
  17647. var parentBone = null;
  17648. if (parsedBone.parentBoneIndex > -1) {
  17649. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  17650. }
  17651. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  17652. if (parsedBone.animation) {
  17653. bone.animations.push(parseAnimation(parsedBone.animation));
  17654. }
  17655. }
  17656. return skeleton;
  17657. };
  17658. var parseFresnelParameters = function (parsedFresnelParameters) {
  17659. var fresnelParameters = new BABYLON.FresnelParameters();
  17660. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  17661. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  17662. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  17663. fresnelParameters.bias = parsedFresnelParameters.bias;
  17664. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  17665. return fresnelParameters;
  17666. };
  17667. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  17668. var material;
  17669. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  17670. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  17671. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  17672. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  17673. material.specularPower = parsedMaterial.specularPower;
  17674. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  17675. material.alpha = parsedMaterial.alpha;
  17676. material.id = parsedMaterial.id;
  17677. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  17678. material.backFaceCulling = parsedMaterial.backFaceCulling;
  17679. material.wireframe = parsedMaterial.wireframe;
  17680. if (parsedMaterial.diffuseTexture) {
  17681. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  17682. }
  17683. if (parsedMaterial.diffuseFresnelParameters) {
  17684. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  17685. }
  17686. if (parsedMaterial.ambientTexture) {
  17687. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  17688. }
  17689. if (parsedMaterial.opacityTexture) {
  17690. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  17691. }
  17692. if (parsedMaterial.opacityFresnelParameters) {
  17693. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  17694. }
  17695. if (parsedMaterial.reflectionTexture) {
  17696. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  17697. }
  17698. if (parsedMaterial.reflectionFresnelParameters) {
  17699. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  17700. }
  17701. if (parsedMaterial.emissiveTexture) {
  17702. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  17703. }
  17704. if (parsedMaterial.emissiveFresnelParameters) {
  17705. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  17706. }
  17707. if (parsedMaterial.specularTexture) {
  17708. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  17709. }
  17710. if (parsedMaterial.bumpTexture) {
  17711. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  17712. }
  17713. return material;
  17714. };
  17715. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  17716. for (var index = 0; index < parsedData.materials.length; index++) {
  17717. var parsedMaterial = parsedData.materials[index];
  17718. if (parsedMaterial.id === id) {
  17719. return parseMaterial(parsedMaterial, scene, rootUrl);
  17720. }
  17721. }
  17722. return null;
  17723. };
  17724. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  17725. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  17726. multiMaterial.id = parsedMultiMaterial.id;
  17727. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  17728. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  17729. var subMatId = parsedMultiMaterial.materials[matIndex];
  17730. if (subMatId) {
  17731. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  17732. }
  17733. else {
  17734. multiMaterial.subMaterials.push(null);
  17735. }
  17736. }
  17737. return multiMaterial;
  17738. };
  17739. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  17740. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  17741. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  17742. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  17743. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  17744. var parsedFlare = parsedLensFlareSystem.flares[index];
  17745. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  17746. }
  17747. return lensFlareSystem;
  17748. };
  17749. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  17750. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  17751. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  17752. if (parsedParticleSystem.textureName) {
  17753. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  17754. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  17755. }
  17756. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  17757. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  17758. particleSystem.minSize = parsedParticleSystem.minSize;
  17759. particleSystem.maxSize = parsedParticleSystem.maxSize;
  17760. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  17761. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  17762. particleSystem.emitter = emitter;
  17763. particleSystem.emitRate = parsedParticleSystem.emitRate;
  17764. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  17765. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  17766. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  17767. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  17768. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  17769. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  17770. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  17771. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  17772. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  17773. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  17774. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  17775. particleSystem.blendMode = parsedParticleSystem.blendMode;
  17776. particleSystem.start();
  17777. return particleSystem;
  17778. };
  17779. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  17780. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  17781. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  17782. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  17783. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  17784. shadowGenerator.getShadowMap().renderList.push(mesh);
  17785. }
  17786. if (parsedShadowGenerator.usePoissonSampling) {
  17787. shadowGenerator.usePoissonSampling = true;
  17788. }
  17789. else {
  17790. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  17791. }
  17792. return shadowGenerator;
  17793. };
  17794. var parseAnimation = function (parsedAnimation) {
  17795. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  17796. var dataType = parsedAnimation.dataType;
  17797. var keys = [];
  17798. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  17799. var key = parsedAnimation.keys[index];
  17800. var data;
  17801. switch (dataType) {
  17802. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17803. data = key.values[0];
  17804. break;
  17805. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17806. data = BABYLON.Quaternion.FromArray(key.values);
  17807. break;
  17808. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17809. data = BABYLON.Matrix.FromArray(key.values);
  17810. break;
  17811. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17812. default:
  17813. data = BABYLON.Vector3.FromArray(key.values);
  17814. break;
  17815. }
  17816. keys.push({
  17817. frame: key.frame,
  17818. value: data
  17819. });
  17820. }
  17821. animation.setKeys(keys);
  17822. return animation;
  17823. };
  17824. var parseLight = function (parsedLight, scene) {
  17825. var light;
  17826. switch (parsedLight.type) {
  17827. case 0:
  17828. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  17829. break;
  17830. case 1:
  17831. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17832. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  17833. break;
  17834. case 2:
  17835. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  17836. break;
  17837. case 3:
  17838. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  17839. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  17840. break;
  17841. }
  17842. light.id = parsedLight.id;
  17843. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  17844. if (parsedLight.intensity !== undefined) {
  17845. light.intensity = parsedLight.intensity;
  17846. }
  17847. if (parsedLight.range) {
  17848. light.range = parsedLight.range;
  17849. }
  17850. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  17851. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  17852. if (parsedLight.excludedMeshesIds) {
  17853. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  17854. }
  17855. // Parent
  17856. if (parsedLight.parentId) {
  17857. light._waitingParentId = parsedLight.parentId;
  17858. }
  17859. if (parsedLight.includedOnlyMeshesIds) {
  17860. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  17861. }
  17862. // Actions
  17863. if (parsedLight.actions !== undefined) {
  17864. light._waitingActions = parsedLight.actions;
  17865. }
  17866. // Animations
  17867. if (parsedLight.animations) {
  17868. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  17869. var parsedAnimation = parsedLight.animations[animationIndex];
  17870. light.animations.push(parseAnimation(parsedAnimation));
  17871. }
  17872. }
  17873. if (parsedLight.autoAnimate) {
  17874. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  17875. }
  17876. };
  17877. var parseCamera = function (parsedCamera, scene) {
  17878. var camera;
  17879. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  17880. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  17881. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  17882. var alpha = parsedCamera.alpha;
  17883. var beta = parsedCamera.beta;
  17884. var radius = parsedCamera.radius;
  17885. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  17886. var eye_space = parsedCamera.eye_space;
  17887. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  17888. }
  17889. else {
  17890. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  17891. }
  17892. }
  17893. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  17894. eye_space = parsedCamera.eye_space;
  17895. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  17896. }
  17897. else if (parsedCamera.type === "DeviceOrientationCamera") {
  17898. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  17899. }
  17900. else if (parsedCamera.type === "FollowCamera") {
  17901. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  17902. camera.heightOffset = parsedCamera.heightOffset;
  17903. camera.radius = parsedCamera.radius;
  17904. camera.rotationOffset = parsedCamera.rotationOffset;
  17905. if (lockedTargetMesh)
  17906. camera.target = lockedTargetMesh;
  17907. }
  17908. else if (parsedCamera.type === "GamepadCamera") {
  17909. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  17910. }
  17911. else if (parsedCamera.type === "OculusCamera") {
  17912. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  17913. }
  17914. else if (parsedCamera.type === "OculusGamepadCamera") {
  17915. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  17916. }
  17917. else if (parsedCamera.type === "TouchCamera") {
  17918. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  17919. }
  17920. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  17921. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  17922. }
  17923. else if (parsedCamera.type === "WebVRCamera") {
  17924. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  17925. }
  17926. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  17927. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  17928. }
  17929. else {
  17930. // Free Camera is the default value
  17931. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  17932. }
  17933. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  17934. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  17935. camera.lockedTarget = lockedTargetMesh;
  17936. }
  17937. camera.id = parsedCamera.id;
  17938. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  17939. // Parent
  17940. if (parsedCamera.parentId) {
  17941. camera._waitingParentId = parsedCamera.parentId;
  17942. }
  17943. // Actions
  17944. if (parsedCamera.actions !== undefined) {
  17945. camera._waitingActions = parsedCamera.actions;
  17946. }
  17947. // Target
  17948. if (parsedCamera.target) {
  17949. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  17950. }
  17951. else {
  17952. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  17953. }
  17954. camera.fov = parsedCamera.fov;
  17955. camera.minZ = parsedCamera.minZ;
  17956. camera.maxZ = parsedCamera.maxZ;
  17957. camera.speed = parsedCamera.speed;
  17958. camera.inertia = parsedCamera.inertia;
  17959. camera.checkCollisions = parsedCamera.checkCollisions;
  17960. camera.applyGravity = parsedCamera.applyGravity;
  17961. if (parsedCamera.ellipsoid) {
  17962. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  17963. }
  17964. // Animations
  17965. if (parsedCamera.animations) {
  17966. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  17967. var parsedAnimation = parsedCamera.animations[animationIndex];
  17968. camera.animations.push(parseAnimation(parsedAnimation));
  17969. }
  17970. }
  17971. if (parsedCamera.autoAnimate) {
  17972. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  17973. }
  17974. // Layer Mask
  17975. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  17976. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  17977. }
  17978. else {
  17979. camera.layerMask = 0xFFFFFFFF;
  17980. }
  17981. return camera;
  17982. };
  17983. var parseGeometry = function (parsedGeometry, scene) {
  17984. var id = parsedGeometry.id;
  17985. return scene.getGeometryByID(id);
  17986. };
  17987. var parseBox = function (parsedBox, scene) {
  17988. if (parseGeometry(parsedBox, scene)) {
  17989. return null; // null since geometry could be something else than a box...
  17990. }
  17991. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  17992. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  17993. scene.pushGeometry(box, true);
  17994. return box;
  17995. };
  17996. var parseSphere = function (parsedSphere, scene) {
  17997. if (parseGeometry(parsedSphere, scene)) {
  17998. return null; // null since geometry could be something else than a sphere...
  17999. }
  18000. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18001. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18002. scene.pushGeometry(sphere, true);
  18003. return sphere;
  18004. };
  18005. var parseCylinder = function (parsedCylinder, scene) {
  18006. if (parseGeometry(parsedCylinder, scene)) {
  18007. return null; // null since geometry could be something else than a cylinder...
  18008. }
  18009. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18010. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18011. scene.pushGeometry(cylinder, true);
  18012. return cylinder;
  18013. };
  18014. var parseTorus = function (parsedTorus, scene) {
  18015. if (parseGeometry(parsedTorus, scene)) {
  18016. return null; // null since geometry could be something else than a torus...
  18017. }
  18018. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18019. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18020. scene.pushGeometry(torus, true);
  18021. return torus;
  18022. };
  18023. var parseGround = function (parsedGround, scene) {
  18024. if (parseGeometry(parsedGround, scene)) {
  18025. return null; // null since geometry could be something else than a ground...
  18026. }
  18027. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18028. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18029. scene.pushGeometry(ground, true);
  18030. return ground;
  18031. };
  18032. var parsePlane = function (parsedPlane, scene) {
  18033. if (parseGeometry(parsedPlane, scene)) {
  18034. return null; // null since geometry could be something else than a plane...
  18035. }
  18036. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18037. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18038. scene.pushGeometry(plane, true);
  18039. return plane;
  18040. };
  18041. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18042. if (parseGeometry(parsedTorusKnot, scene)) {
  18043. return null; // null since geometry could be something else than a torusKnot...
  18044. }
  18045. 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);
  18046. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  18047. scene.pushGeometry(torusKnot, true);
  18048. return torusKnot;
  18049. };
  18050. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  18051. if (parseGeometry(parsedVertexData, scene)) {
  18052. return null; // null since geometry could be a primitive
  18053. }
  18054. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  18055. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  18056. if (parsedVertexData.delayLoadingFile) {
  18057. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18058. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  18059. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  18060. geometry._delayInfo = [];
  18061. if (parsedVertexData.hasUVs) {
  18062. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18063. }
  18064. if (parsedVertexData.hasUVs2) {
  18065. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18066. }
  18067. if (parsedVertexData.hasColors) {
  18068. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18069. }
  18070. if (parsedVertexData.hasMatricesIndices) {
  18071. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18072. }
  18073. if (parsedVertexData.hasMatricesWeights) {
  18074. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18075. }
  18076. geometry._delayLoadingFunction = importVertexData;
  18077. }
  18078. else {
  18079. importVertexData(parsedVertexData, geometry);
  18080. }
  18081. scene.pushGeometry(geometry, true);
  18082. return geometry;
  18083. };
  18084. var parseMesh = function (parsedMesh, scene, rootUrl) {
  18085. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  18086. mesh.id = parsedMesh.id;
  18087. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  18088. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  18089. if (parsedMesh.rotationQuaternion) {
  18090. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  18091. }
  18092. else if (parsedMesh.rotation) {
  18093. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  18094. }
  18095. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  18096. if (parsedMesh.localMatrix) {
  18097. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  18098. }
  18099. else if (parsedMesh.pivotMatrix) {
  18100. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  18101. }
  18102. mesh.setEnabled(parsedMesh.isEnabled);
  18103. mesh.isVisible = parsedMesh.isVisible;
  18104. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  18105. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  18106. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  18107. if (parsedMesh.applyFog !== undefined) {
  18108. mesh.applyFog = parsedMesh.applyFog;
  18109. }
  18110. if (parsedMesh.pickable !== undefined) {
  18111. mesh.isPickable = parsedMesh.pickable;
  18112. }
  18113. if (parsedMesh.alphaIndex !== undefined) {
  18114. mesh.alphaIndex = parsedMesh.alphaIndex;
  18115. }
  18116. mesh.receiveShadows = parsedMesh.receiveShadows;
  18117. mesh.billboardMode = parsedMesh.billboardMode;
  18118. if (parsedMesh.visibility !== undefined) {
  18119. mesh.visibility = parsedMesh.visibility;
  18120. }
  18121. mesh.checkCollisions = parsedMesh.checkCollisions;
  18122. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  18123. // Parent
  18124. if (parsedMesh.parentId) {
  18125. mesh._waitingParentId = parsedMesh.parentId;
  18126. }
  18127. // Actions
  18128. if (parsedMesh.actions !== undefined) {
  18129. mesh._waitingActions = parsedMesh.actions;
  18130. }
  18131. // Geometry
  18132. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  18133. if (parsedMesh.delayLoadingFile) {
  18134. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  18135. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  18136. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  18137. if (parsedMesh._binaryInfo) {
  18138. mesh._binaryInfo = parsedMesh._binaryInfo;
  18139. }
  18140. mesh._delayInfo = [];
  18141. if (parsedMesh.hasUVs) {
  18142. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  18143. }
  18144. if (parsedMesh.hasUVs2) {
  18145. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  18146. }
  18147. if (parsedMesh.hasColors) {
  18148. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  18149. }
  18150. if (parsedMesh.hasMatricesIndices) {
  18151. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  18152. }
  18153. if (parsedMesh.hasMatricesWeights) {
  18154. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  18155. }
  18156. mesh._delayLoadingFunction = importGeometry;
  18157. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  18158. mesh._checkDelayState();
  18159. }
  18160. }
  18161. else {
  18162. importGeometry(parsedMesh, mesh);
  18163. }
  18164. // Material
  18165. if (parsedMesh.materialId) {
  18166. mesh.setMaterialByID(parsedMesh.materialId);
  18167. }
  18168. else {
  18169. mesh.material = null;
  18170. }
  18171. // Skeleton
  18172. if (parsedMesh.skeletonId > -1) {
  18173. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  18174. }
  18175. // Physics
  18176. if (parsedMesh.physicsImpostor) {
  18177. if (!scene.isPhysicsEnabled()) {
  18178. scene.enablePhysics();
  18179. }
  18180. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  18181. }
  18182. // Animations
  18183. if (parsedMesh.animations) {
  18184. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18185. var parsedAnimation = parsedMesh.animations[animationIndex];
  18186. mesh.animations.push(parseAnimation(parsedAnimation));
  18187. }
  18188. }
  18189. if (parsedMesh.autoAnimate) {
  18190. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  18191. }
  18192. // Layer Mask
  18193. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  18194. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  18195. }
  18196. else {
  18197. mesh.layerMask = 0xFFFFFFFF;
  18198. }
  18199. // Instances
  18200. if (parsedMesh.instances) {
  18201. for (var index = 0; index < parsedMesh.instances.length; index++) {
  18202. var parsedInstance = parsedMesh.instances[index];
  18203. var instance = mesh.createInstance(parsedInstance.name);
  18204. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  18205. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  18206. if (parsedInstance.rotationQuaternion) {
  18207. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  18208. }
  18209. else if (parsedInstance.rotation) {
  18210. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  18211. }
  18212. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  18213. instance.checkCollisions = mesh.checkCollisions;
  18214. if (parsedMesh.animations) {
  18215. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  18216. parsedAnimation = parsedMesh.animations[animationIndex];
  18217. instance.animations.push(parseAnimation(parsedAnimation));
  18218. }
  18219. }
  18220. }
  18221. }
  18222. return mesh;
  18223. };
  18224. var parseActions = function (parsedActions, object, scene) {
  18225. object.actionManager = new BABYLON.ActionManager(scene);
  18226. // instanciate a new object
  18227. var instanciate = function (name, params) {
  18228. var newInstance = Object.create(BABYLON[name].prototype);
  18229. newInstance.constructor.apply(newInstance, params);
  18230. return newInstance;
  18231. };
  18232. var parseParameter = function (name, value, target, propertyPath) {
  18233. var split = value.split(",");
  18234. if (split.length == 1) {
  18235. var num = parseFloat(split[0]);
  18236. if (isNaN(num))
  18237. return split[0];
  18238. else
  18239. return num;
  18240. }
  18241. var effectiveTarget = propertyPath.split(".");
  18242. for (var i = 0; i < effectiveTarget.length; i++) {
  18243. target = target[effectiveTarget[i]];
  18244. }
  18245. if (split.length == 3) {
  18246. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2])];
  18247. if (target instanceof BABYLON.Vector3)
  18248. return BABYLON.Vector3.FromArray(values);
  18249. else
  18250. return BABYLON.Color3.FromArray(values);
  18251. }
  18252. if (split.length == 4) {
  18253. var values = [parseFloat(split[0]), parseFloat(split[1]), parseFloat(split[2]), parseFloat(split[3])];
  18254. if (target instanceof BABYLON.Vector4)
  18255. return BABYLON.Vector4.FromArray(values);
  18256. else
  18257. return BABYLON.Color4.FromArray(values);
  18258. }
  18259. };
  18260. // traverse graph per trigger
  18261. var traverse = function (parsedAction, trigger, condition, action, actionManager) {
  18262. var parameters = new Array();
  18263. var target = null;
  18264. var propertyPath = null;
  18265. // Parameters
  18266. if (parsedAction.type == 2)
  18267. parameters.push(actionManager);
  18268. else
  18269. parameters.push(trigger);
  18270. for (var i = 0; i < parsedAction.properties.length; i++) {
  18271. var value = parsedAction.properties[i].value;
  18272. if (parsedAction.properties[i].name === "target") {
  18273. value = target = scene.getNodeByName(value);
  18274. }
  18275. else if (parsedAction.properties[i].name != "propertyPath") {
  18276. if (value === "false" || value === "true")
  18277. value = value === "true";
  18278. else if (parsedAction.type === 2 && parsedAction.properties[i].name === "operator")
  18279. value = BABYLON.ValueCondition[value];
  18280. else
  18281. value = parseParameter(parsedAction.properties[i].name, value, target, propertyPath);
  18282. }
  18283. else {
  18284. propertyPath = value;
  18285. }
  18286. parameters.push(value);
  18287. }
  18288. parameters.push(condition);
  18289. // If interpolate value action
  18290. if (parsedAction.name === "InterpolateValueAction") {
  18291. var param = parameters[parameters.length - 2];
  18292. parameters[parameters.length - 1] = param;
  18293. parameters[parameters.length - 2] = condition;
  18294. }
  18295. // Action or condition
  18296. var newAction = instanciate(parsedAction.name, parameters);
  18297. if (newAction instanceof BABYLON.Condition) {
  18298. condition = newAction;
  18299. newAction = action;
  18300. }
  18301. else {
  18302. condition = null;
  18303. if (action)
  18304. action.then(newAction);
  18305. else
  18306. actionManager.registerAction(newAction);
  18307. }
  18308. for (var i = 0; i < parsedAction.children.length; i++)
  18309. traverse(parsedAction.children[i], trigger, condition, newAction, actionManager);
  18310. };
  18311. for (var i = 0; i < parsedActions.children.length; i++) {
  18312. var triggerParams;
  18313. var trigger = parsedActions.children[i];
  18314. if (trigger.properties.length > 0) {
  18315. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  18316. }
  18317. else
  18318. triggerParams = BABYLON.ActionManager[trigger.name];
  18319. for (var j = 0; j < trigger.children.length; j++)
  18320. traverse(trigger.children[j], triggerParams, null, null, object.actionManager);
  18321. }
  18322. };
  18323. var isDescendantOf = function (mesh, names, hierarchyIds) {
  18324. names = (names instanceof Array) ? names : [names];
  18325. for (var i in names) {
  18326. if (mesh.name === names[i]) {
  18327. hierarchyIds.push(mesh.id);
  18328. return true;
  18329. }
  18330. }
  18331. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  18332. hierarchyIds.push(mesh.id);
  18333. return true;
  18334. }
  18335. return false;
  18336. };
  18337. var importVertexData = function (parsedVertexData, geometry) {
  18338. var vertexData = new BABYLON.VertexData();
  18339. // positions
  18340. var positions = parsedVertexData.positions;
  18341. if (positions) {
  18342. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  18343. }
  18344. // normals
  18345. var normals = parsedVertexData.normals;
  18346. if (normals) {
  18347. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  18348. }
  18349. // uvs
  18350. var uvs = parsedVertexData.uvs;
  18351. if (uvs) {
  18352. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  18353. }
  18354. // uv2s
  18355. var uv2s = parsedVertexData.uv2s;
  18356. if (uv2s) {
  18357. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  18358. }
  18359. // colors
  18360. var colors = parsedVertexData.colors;
  18361. if (colors) {
  18362. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  18363. }
  18364. // matricesIndices
  18365. var matricesIndices = parsedVertexData.matricesIndices;
  18366. if (matricesIndices) {
  18367. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  18368. }
  18369. // matricesWeights
  18370. var matricesWeights = parsedVertexData.matricesWeights;
  18371. if (matricesWeights) {
  18372. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  18373. }
  18374. // indices
  18375. var indices = parsedVertexData.indices;
  18376. if (indices) {
  18377. vertexData.indices = indices;
  18378. }
  18379. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  18380. };
  18381. var importGeometry = function (parsedGeometry, mesh) {
  18382. var scene = mesh.getScene();
  18383. // Geometry
  18384. var geometryId = parsedGeometry.geometryId;
  18385. if (geometryId) {
  18386. var geometry = scene.getGeometryByID(geometryId);
  18387. if (geometry) {
  18388. geometry.applyToMesh(mesh);
  18389. }
  18390. }
  18391. else if (parsedGeometry instanceof ArrayBuffer) {
  18392. var binaryInfo = mesh._binaryInfo;
  18393. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  18394. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  18395. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  18396. }
  18397. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  18398. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  18399. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  18400. }
  18401. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  18402. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  18403. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  18404. }
  18405. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  18406. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  18407. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  18408. }
  18409. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  18410. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  18411. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  18412. }
  18413. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  18414. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  18415. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  18416. }
  18417. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  18418. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  18419. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  18420. }
  18421. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  18422. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  18423. mesh.setIndices(indicesData);
  18424. }
  18425. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  18426. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  18427. mesh.subMeshes = [];
  18428. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  18429. var materialIndex = subMeshesData[(i * 5) + 0];
  18430. var verticesStart = subMeshesData[(i * 5) + 1];
  18431. var verticesCount = subMeshesData[(i * 5) + 2];
  18432. var indexStart = subMeshesData[(i * 5) + 3];
  18433. var indexCount = subMeshesData[(i * 5) + 4];
  18434. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  18435. }
  18436. }
  18437. }
  18438. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  18439. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  18440. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  18441. if (parsedGeometry.uvs) {
  18442. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  18443. }
  18444. if (parsedGeometry.uvs2) {
  18445. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  18446. }
  18447. if (parsedGeometry.colors) {
  18448. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  18449. }
  18450. if (parsedGeometry.matricesIndices) {
  18451. if (!parsedGeometry.matricesIndices._isExpanded) {
  18452. var floatIndices = [];
  18453. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  18454. var matricesIndex = parsedGeometry.matricesIndices[i];
  18455. floatIndices.push(matricesIndex & 0x000000FF);
  18456. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  18457. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  18458. floatIndices.push(matricesIndex >> 24);
  18459. }
  18460. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  18461. }
  18462. else {
  18463. delete parsedGeometry.matricesIndices._isExpanded;
  18464. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  18465. }
  18466. }
  18467. if (parsedGeometry.matricesWeights) {
  18468. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  18469. }
  18470. mesh.setIndices(parsedGeometry.indices);
  18471. // SubMeshes
  18472. if (parsedGeometry.subMeshes) {
  18473. mesh.subMeshes = [];
  18474. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  18475. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  18476. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  18477. }
  18478. }
  18479. }
  18480. // Flat shading
  18481. if (mesh._shouldGenerateFlatShading) {
  18482. mesh.convertToFlatShadedMesh();
  18483. delete mesh._shouldGenerateFlatShading;
  18484. }
  18485. // Update
  18486. mesh.computeWorldMatrix(true);
  18487. // Octree
  18488. if (scene._selectionOctree) {
  18489. scene._selectionOctree.addMesh(mesh);
  18490. }
  18491. };
  18492. BABYLON.SceneLoader.RegisterPlugin({
  18493. extensions: ".babylon",
  18494. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  18495. var parsedData = JSON.parse(data);
  18496. var loadedSkeletonsIds = [];
  18497. var loadedMaterialsIds = [];
  18498. var hierarchyIds = [];
  18499. for (var index = 0; index < parsedData.meshes.length; index++) {
  18500. var parsedMesh = parsedData.meshes[index];
  18501. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  18502. if (meshesNames instanceof Array) {
  18503. // Remove found mesh name from list.
  18504. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  18505. }
  18506. // Material ?
  18507. if (parsedMesh.materialId) {
  18508. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  18509. if (!materialFound) {
  18510. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  18511. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  18512. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  18513. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18514. var subMatId = parsedMultiMaterial.materials[matIndex];
  18515. loadedMaterialsIds.push(subMatId);
  18516. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  18517. }
  18518. loadedMaterialsIds.push(parsedMultiMaterial.id);
  18519. parseMultiMaterial(parsedMultiMaterial, scene);
  18520. materialFound = true;
  18521. break;
  18522. }
  18523. }
  18524. }
  18525. if (!materialFound) {
  18526. loadedMaterialsIds.push(parsedMesh.materialId);
  18527. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  18528. }
  18529. }
  18530. // Skeleton ?
  18531. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  18532. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  18533. if (!skeletonAlreadyLoaded) {
  18534. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  18535. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  18536. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  18537. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  18538. loadedSkeletonsIds.push(parsedSkeleton.id);
  18539. }
  18540. }
  18541. }
  18542. }
  18543. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  18544. meshes.push(mesh);
  18545. }
  18546. }
  18547. for (index = 0; index < scene.meshes.length; index++) {
  18548. var currentMesh = scene.meshes[index];
  18549. if (currentMesh._waitingParentId) {
  18550. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  18551. currentMesh._waitingParentId = undefined;
  18552. }
  18553. }
  18554. // Particles
  18555. if (parsedData.particleSystems) {
  18556. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18557. var parsedParticleSystem = parsedData.particleSystems[index];
  18558. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  18559. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  18560. }
  18561. }
  18562. }
  18563. return true;
  18564. },
  18565. load: function (scene, data, rootUrl) {
  18566. var parsedData = JSON.parse(data);
  18567. // Scene
  18568. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  18569. scene.autoClear = parsedData.autoClear;
  18570. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  18571. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  18572. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  18573. // Fog
  18574. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  18575. scene.fogMode = parsedData.fogMode;
  18576. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  18577. scene.fogStart = parsedData.fogStart;
  18578. scene.fogEnd = parsedData.fogEnd;
  18579. scene.fogDensity = parsedData.fogDensity;
  18580. }
  18581. for (var index = 0; index < parsedData.lights.length; index++) {
  18582. var parsedLight = parsedData.lights[index];
  18583. parseLight(parsedLight, scene);
  18584. }
  18585. // Materials
  18586. if (parsedData.materials) {
  18587. for (index = 0; index < parsedData.materials.length; index++) {
  18588. var parsedMaterial = parsedData.materials[index];
  18589. parseMaterial(parsedMaterial, scene, rootUrl);
  18590. }
  18591. }
  18592. if (parsedData.multiMaterials) {
  18593. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  18594. var parsedMultiMaterial = parsedData.multiMaterials[index];
  18595. parseMultiMaterial(parsedMultiMaterial, scene);
  18596. }
  18597. }
  18598. // Skeletons
  18599. if (parsedData.skeletons) {
  18600. for (index = 0; index < parsedData.skeletons.length; index++) {
  18601. var parsedSkeleton = parsedData.skeletons[index];
  18602. parseSkeleton(parsedSkeleton, scene);
  18603. }
  18604. }
  18605. // Geometries
  18606. var geometries = parsedData.geometries;
  18607. if (geometries) {
  18608. // Boxes
  18609. var boxes = geometries.boxes;
  18610. if (boxes) {
  18611. for (index = 0; index < boxes.length; index++) {
  18612. var parsedBox = boxes[index];
  18613. parseBox(parsedBox, scene);
  18614. }
  18615. }
  18616. // Spheres
  18617. var spheres = geometries.spheres;
  18618. if (spheres) {
  18619. for (index = 0; index < spheres.length; index++) {
  18620. var parsedSphere = spheres[index];
  18621. parseSphere(parsedSphere, scene);
  18622. }
  18623. }
  18624. // Cylinders
  18625. var cylinders = geometries.cylinders;
  18626. if (cylinders) {
  18627. for (index = 0; index < cylinders.length; index++) {
  18628. var parsedCylinder = cylinders[index];
  18629. parseCylinder(parsedCylinder, scene);
  18630. }
  18631. }
  18632. // Toruses
  18633. var toruses = geometries.toruses;
  18634. if (toruses) {
  18635. for (index = 0; index < toruses.length; index++) {
  18636. var parsedTorus = toruses[index];
  18637. parseTorus(parsedTorus, scene);
  18638. }
  18639. }
  18640. // Grounds
  18641. var grounds = geometries.grounds;
  18642. if (grounds) {
  18643. for (index = 0; index < grounds.length; index++) {
  18644. var parsedGround = grounds[index];
  18645. parseGround(parsedGround, scene);
  18646. }
  18647. }
  18648. // Planes
  18649. var planes = geometries.planes;
  18650. if (planes) {
  18651. for (index = 0; index < planes.length; index++) {
  18652. var parsedPlane = planes[index];
  18653. parsePlane(parsedPlane, scene);
  18654. }
  18655. }
  18656. // TorusKnots
  18657. var torusKnots = geometries.torusKnots;
  18658. if (torusKnots) {
  18659. for (index = 0; index < torusKnots.length; index++) {
  18660. var parsedTorusKnot = torusKnots[index];
  18661. parseTorusKnot(parsedTorusKnot, scene);
  18662. }
  18663. }
  18664. // VertexData
  18665. var vertexData = geometries.vertexData;
  18666. if (vertexData) {
  18667. for (index = 0; index < vertexData.length; index++) {
  18668. var parsedVertexData = vertexData[index];
  18669. parseVertexData(parsedVertexData, scene, rootUrl);
  18670. }
  18671. }
  18672. }
  18673. for (index = 0; index < parsedData.meshes.length; index++) {
  18674. var parsedMesh = parsedData.meshes[index];
  18675. parseMesh(parsedMesh, scene, rootUrl);
  18676. }
  18677. for (index = 0; index < parsedData.cameras.length; index++) {
  18678. var parsedCamera = parsedData.cameras[index];
  18679. parseCamera(parsedCamera, scene);
  18680. }
  18681. if (parsedData.activeCameraID) {
  18682. scene.setActiveCameraByID(parsedData.activeCameraID);
  18683. }
  18684. for (index = 0; index < scene.cameras.length; index++) {
  18685. var camera = scene.cameras[index];
  18686. if (camera._waitingParentId) {
  18687. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  18688. camera._waitingParentId = undefined;
  18689. }
  18690. }
  18691. for (index = 0; index < scene.lights.length; index++) {
  18692. var light = scene.lights[index];
  18693. if (light._waitingParentId) {
  18694. light.parent = scene.getLastEntryByID(light._waitingParentId);
  18695. light._waitingParentId = undefined;
  18696. }
  18697. }
  18698. for (index = 0; index < scene.meshes.length; index++) {
  18699. var mesh = scene.meshes[index];
  18700. if (mesh._waitingParentId) {
  18701. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  18702. mesh._waitingParentId = undefined;
  18703. }
  18704. if (mesh._waitingActions) {
  18705. parseActions(mesh._waitingActions, mesh, scene);
  18706. mesh._waitingActions = undefined;
  18707. }
  18708. }
  18709. // Particles Systems
  18710. if (parsedData.particleSystems) {
  18711. for (index = 0; index < parsedData.particleSystems.length; index++) {
  18712. var parsedParticleSystem = parsedData.particleSystems[index];
  18713. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  18714. }
  18715. }
  18716. // Lens flares
  18717. if (parsedData.lensFlareSystems) {
  18718. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  18719. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  18720. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  18721. }
  18722. }
  18723. // Shadows
  18724. if (parsedData.shadowGenerators) {
  18725. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  18726. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  18727. parseShadowGenerator(parsedShadowGenerator, scene);
  18728. }
  18729. }
  18730. // Actions (scene)
  18731. if (parsedData.actions) {
  18732. parseActions(parsedData.actions, scene, scene);
  18733. }
  18734. // Finish
  18735. return true;
  18736. }
  18737. });
  18738. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  18739. })(BABYLON || (BABYLON = {}));
  18740. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  18741. (function (BABYLON) {
  18742. // Unique ID when we import meshes from Babylon to CSG
  18743. var currentCSGMeshId = 0;
  18744. // # class Vertex
  18745. // Represents a vertex of a polygon. Use your own vertex class instead of this
  18746. // one to provide additional features like texture coordinates and vertex
  18747. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  18748. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  18749. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  18750. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  18751. // is not used anywhere else.
  18752. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  18753. var Vertex = (function () {
  18754. function Vertex(pos, normal, uv) {
  18755. this.pos = pos;
  18756. this.normal = normal;
  18757. this.uv = uv;
  18758. }
  18759. Vertex.prototype.clone = function () {
  18760. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  18761. };
  18762. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  18763. // orientation of a polygon is flipped.
  18764. Vertex.prototype.flip = function () {
  18765. this.normal = this.normal.scale(-1);
  18766. };
  18767. // Create a new vertex between this vertex and `other` by linearly
  18768. // interpolating all properties using a parameter of `t`. Subclasses should
  18769. // override this to interpolate additional properties.
  18770. Vertex.prototype.interpolate = function (other, t) {
  18771. 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));
  18772. };
  18773. return Vertex;
  18774. })();
  18775. // # class Plane
  18776. // Represents a plane in 3D space.
  18777. var Plane = (function () {
  18778. function Plane(normal, w) {
  18779. this.normal = normal;
  18780. this.w = w;
  18781. }
  18782. Plane.FromPoints = function (a, b, c) {
  18783. var v0 = c.subtract(a);
  18784. var v1 = b.subtract(a);
  18785. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  18786. return null;
  18787. }
  18788. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  18789. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  18790. };
  18791. Plane.prototype.clone = function () {
  18792. return new Plane(this.normal.clone(), this.w);
  18793. };
  18794. Plane.prototype.flip = function () {
  18795. this.normal.scaleInPlace(-1);
  18796. this.w = -this.w;
  18797. };
  18798. // Split `polygon` by this plane if needed, then put the polygon or polygon
  18799. // fragments in the appropriate lists. Coplanar polygons go into either
  18800. // `coplanarFront` or `coplanarBack` depending on their orientation with
  18801. // respect to this plane. Polygons in front or in back of this plane go into
  18802. // either `front` or `back`.
  18803. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  18804. var COPLANAR = 0;
  18805. var FRONT = 1;
  18806. var BACK = 2;
  18807. var SPANNING = 3;
  18808. // Classify each point as well as the entire polygon into one of the above
  18809. // four classes.
  18810. var polygonType = 0;
  18811. var types = [];
  18812. for (var i = 0; i < polygon.vertices.length; i++) {
  18813. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  18814. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  18815. polygonType |= type;
  18816. types.push(type);
  18817. }
  18818. switch (polygonType) {
  18819. case COPLANAR:
  18820. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  18821. break;
  18822. case FRONT:
  18823. front.push(polygon);
  18824. break;
  18825. case BACK:
  18826. back.push(polygon);
  18827. break;
  18828. case SPANNING:
  18829. var f = [], b = [];
  18830. for (i = 0; i < polygon.vertices.length; i++) {
  18831. var j = (i + 1) % polygon.vertices.length;
  18832. var ti = types[i], tj = types[j];
  18833. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  18834. if (ti != BACK)
  18835. f.push(vi);
  18836. if (ti != FRONT)
  18837. b.push(ti != BACK ? vi.clone() : vi);
  18838. if ((ti | tj) == SPANNING) {
  18839. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  18840. var v = vi.interpolate(vj, t);
  18841. f.push(v);
  18842. b.push(v.clone());
  18843. }
  18844. }
  18845. if (f.length >= 3) {
  18846. var poly = new Polygon(f, polygon.shared);
  18847. if (poly.plane)
  18848. front.push(poly);
  18849. }
  18850. if (b.length >= 3) {
  18851. poly = new Polygon(b, polygon.shared);
  18852. if (poly.plane)
  18853. back.push(poly);
  18854. }
  18855. break;
  18856. }
  18857. };
  18858. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  18859. // point is on the plane.
  18860. Plane.EPSILON = 1e-5;
  18861. return Plane;
  18862. })();
  18863. // # class Polygon
  18864. // Represents a convex polygon. The vertices used to initialize a polygon must
  18865. // be coplanar and form a convex loop.
  18866. //
  18867. // Each convex polygon has a `shared` property, which is shared between all
  18868. // polygons that are clones of each other or were split from the same polygon.
  18869. // This can be used to define per-polygon properties (such as surface color).
  18870. var Polygon = (function () {
  18871. function Polygon(vertices, shared) {
  18872. this.vertices = vertices;
  18873. this.shared = shared;
  18874. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  18875. }
  18876. Polygon.prototype.clone = function () {
  18877. var vertices = this.vertices.map(function (v) { return v.clone(); });
  18878. return new Polygon(vertices, this.shared);
  18879. };
  18880. Polygon.prototype.flip = function () {
  18881. this.vertices.reverse().map(function (v) {
  18882. v.flip();
  18883. });
  18884. this.plane.flip();
  18885. };
  18886. return Polygon;
  18887. })();
  18888. // # class Node
  18889. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  18890. // by picking a polygon to split along. That polygon (and all other coplanar
  18891. // polygons) are added directly to that node and the other polygons are added to
  18892. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  18893. // no distinction between internal and leaf nodes.
  18894. var Node = (function () {
  18895. function Node(polygons) {
  18896. this.plane = null;
  18897. this.front = null;
  18898. this.back = null;
  18899. this.polygons = [];
  18900. if (polygons) {
  18901. this.build(polygons);
  18902. }
  18903. }
  18904. Node.prototype.clone = function () {
  18905. var node = new Node();
  18906. node.plane = this.plane && this.plane.clone();
  18907. node.front = this.front && this.front.clone();
  18908. node.back = this.back && this.back.clone();
  18909. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  18910. return node;
  18911. };
  18912. // Convert solid space to empty space and empty space to solid space.
  18913. Node.prototype.invert = function () {
  18914. for (var i = 0; i < this.polygons.length; i++) {
  18915. this.polygons[i].flip();
  18916. }
  18917. if (this.plane) {
  18918. this.plane.flip();
  18919. }
  18920. if (this.front) {
  18921. this.front.invert();
  18922. }
  18923. if (this.back) {
  18924. this.back.invert();
  18925. }
  18926. var temp = this.front;
  18927. this.front = this.back;
  18928. this.back = temp;
  18929. };
  18930. // Recursively remove all polygons in `polygons` that are inside this BSP
  18931. // tree.
  18932. Node.prototype.clipPolygons = function (polygons) {
  18933. if (!this.plane)
  18934. return polygons.slice();
  18935. var front = [], back = [];
  18936. for (var i = 0; i < polygons.length; i++) {
  18937. this.plane.splitPolygon(polygons[i], front, back, front, back);
  18938. }
  18939. if (this.front) {
  18940. front = this.front.clipPolygons(front);
  18941. }
  18942. if (this.back) {
  18943. back = this.back.clipPolygons(back);
  18944. }
  18945. else {
  18946. back = [];
  18947. }
  18948. return front.concat(back);
  18949. };
  18950. // Remove all polygons in this BSP tree that are inside the other BSP tree
  18951. // `bsp`.
  18952. Node.prototype.clipTo = function (bsp) {
  18953. this.polygons = bsp.clipPolygons(this.polygons);
  18954. if (this.front)
  18955. this.front.clipTo(bsp);
  18956. if (this.back)
  18957. this.back.clipTo(bsp);
  18958. };
  18959. // Return a list of all polygons in this BSP tree.
  18960. Node.prototype.allPolygons = function () {
  18961. var polygons = this.polygons.slice();
  18962. if (this.front)
  18963. polygons = polygons.concat(this.front.allPolygons());
  18964. if (this.back)
  18965. polygons = polygons.concat(this.back.allPolygons());
  18966. return polygons;
  18967. };
  18968. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  18969. // new polygons are filtered down to the bottom of the tree and become new
  18970. // nodes there. Each set of polygons is partitioned using the first polygon
  18971. // (no heuristic is used to pick a good split).
  18972. Node.prototype.build = function (polygons) {
  18973. if (!polygons.length)
  18974. return;
  18975. if (!this.plane)
  18976. this.plane = polygons[0].plane.clone();
  18977. var front = [], back = [];
  18978. for (var i = 0; i < polygons.length; i++) {
  18979. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  18980. }
  18981. if (front.length) {
  18982. if (!this.front)
  18983. this.front = new Node();
  18984. this.front.build(front);
  18985. }
  18986. if (back.length) {
  18987. if (!this.back)
  18988. this.back = new Node();
  18989. this.back.build(back);
  18990. }
  18991. };
  18992. return Node;
  18993. })();
  18994. var CSG = (function () {
  18995. function CSG() {
  18996. this.polygons = new Array();
  18997. }
  18998. // Convert BABYLON.Mesh to BABYLON.CSG
  18999. CSG.FromMesh = function (mesh) {
  19000. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  19001. if (mesh instanceof BABYLON.Mesh) {
  19002. mesh.computeWorldMatrix(true);
  19003. var matrix = mesh.getWorldMatrix();
  19004. var meshPosition = mesh.position.clone();
  19005. var meshRotation = mesh.rotation.clone();
  19006. var meshScaling = mesh.scaling.clone();
  19007. }
  19008. else {
  19009. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  19010. }
  19011. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  19012. var subMeshes = mesh.subMeshes;
  19013. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  19014. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  19015. vertices = [];
  19016. for (var j = 0; j < 3; j++) {
  19017. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  19018. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  19019. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  19020. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  19021. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  19022. vertex = new Vertex(position, normal, uv);
  19023. vertices.push(vertex);
  19024. }
  19025. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  19026. // To handle the case of degenerated triangle
  19027. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  19028. if (polygon.plane)
  19029. polygons.push(polygon);
  19030. }
  19031. }
  19032. var csg = CSG.FromPolygons(polygons);
  19033. csg.matrix = matrix;
  19034. csg.position = meshPosition;
  19035. csg.rotation = meshRotation;
  19036. csg.scaling = meshScaling;
  19037. currentCSGMeshId++;
  19038. return csg;
  19039. };
  19040. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  19041. CSG.FromPolygons = function (polygons) {
  19042. var csg = new BABYLON.CSG();
  19043. csg.polygons = polygons;
  19044. return csg;
  19045. };
  19046. CSG.prototype.clone = function () {
  19047. var csg = new BABYLON.CSG();
  19048. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  19049. csg.copyTransformAttributes(this);
  19050. return csg;
  19051. };
  19052. CSG.prototype.toPolygons = function () {
  19053. return this.polygons;
  19054. };
  19055. CSG.prototype.union = function (csg) {
  19056. var a = new Node(this.clone().polygons);
  19057. var b = new Node(csg.clone().polygons);
  19058. a.clipTo(b);
  19059. b.clipTo(a);
  19060. b.invert();
  19061. b.clipTo(a);
  19062. b.invert();
  19063. a.build(b.allPolygons());
  19064. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19065. };
  19066. CSG.prototype.unionInPlace = function (csg) {
  19067. var a = new Node(this.polygons);
  19068. var b = new Node(csg.polygons);
  19069. a.clipTo(b);
  19070. b.clipTo(a);
  19071. b.invert();
  19072. b.clipTo(a);
  19073. b.invert();
  19074. a.build(b.allPolygons());
  19075. this.polygons = a.allPolygons();
  19076. };
  19077. CSG.prototype.subtract = function (csg) {
  19078. var a = new Node(this.clone().polygons);
  19079. var b = new Node(csg.clone().polygons);
  19080. a.invert();
  19081. a.clipTo(b);
  19082. b.clipTo(a);
  19083. b.invert();
  19084. b.clipTo(a);
  19085. b.invert();
  19086. a.build(b.allPolygons());
  19087. a.invert();
  19088. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19089. };
  19090. CSG.prototype.subtractInPlace = function (csg) {
  19091. var a = new Node(this.polygons);
  19092. var b = new Node(csg.polygons);
  19093. a.invert();
  19094. a.clipTo(b);
  19095. b.clipTo(a);
  19096. b.invert();
  19097. b.clipTo(a);
  19098. b.invert();
  19099. a.build(b.allPolygons());
  19100. a.invert();
  19101. this.polygons = a.allPolygons();
  19102. };
  19103. CSG.prototype.intersect = function (csg) {
  19104. var a = new Node(this.clone().polygons);
  19105. var b = new Node(csg.clone().polygons);
  19106. a.invert();
  19107. b.clipTo(a);
  19108. b.invert();
  19109. a.clipTo(b);
  19110. b.clipTo(a);
  19111. a.build(b.allPolygons());
  19112. a.invert();
  19113. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  19114. };
  19115. CSG.prototype.intersectInPlace = function (csg) {
  19116. var a = new Node(this.polygons);
  19117. var b = new Node(csg.polygons);
  19118. a.invert();
  19119. b.clipTo(a);
  19120. b.invert();
  19121. a.clipTo(b);
  19122. b.clipTo(a);
  19123. a.build(b.allPolygons());
  19124. a.invert();
  19125. this.polygons = a.allPolygons();
  19126. };
  19127. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  19128. // not modified.
  19129. CSG.prototype.inverse = function () {
  19130. var csg = this.clone();
  19131. csg.inverseInPlace();
  19132. return csg;
  19133. };
  19134. CSG.prototype.inverseInPlace = function () {
  19135. this.polygons.map(function (p) {
  19136. p.flip();
  19137. });
  19138. };
  19139. // This is used to keep meshes transformations so they can be restored
  19140. // when we build back a Babylon Mesh
  19141. // NB : All CSG operations are performed in world coordinates
  19142. CSG.prototype.copyTransformAttributes = function (csg) {
  19143. this.matrix = csg.matrix;
  19144. this.position = csg.position;
  19145. this.rotation = csg.rotation;
  19146. this.scaling = csg.scaling;
  19147. return this;
  19148. };
  19149. // Build Raw mesh from CSG
  19150. // Coordinates here are in world space
  19151. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  19152. var matrix = this.matrix.clone();
  19153. matrix.invert();
  19154. 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;
  19155. if (keepSubMeshes) {
  19156. // Sort Polygons, since subMeshes are indices range
  19157. polygons.sort(function (a, b) {
  19158. if (a.shared.meshId === b.shared.meshId) {
  19159. return a.shared.subMeshId - b.shared.subMeshId;
  19160. }
  19161. else {
  19162. return a.shared.meshId - b.shared.meshId;
  19163. }
  19164. });
  19165. }
  19166. for (var i = 0, il = polygons.length; i < il; i++) {
  19167. polygon = polygons[i];
  19168. // Building SubMeshes
  19169. if (!subMesh_dict[polygon.shared.meshId]) {
  19170. subMesh_dict[polygon.shared.meshId] = {};
  19171. }
  19172. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  19173. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  19174. indexStart: +Infinity,
  19175. indexEnd: -Infinity,
  19176. materialIndex: polygon.shared.materialIndex
  19177. };
  19178. }
  19179. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  19180. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  19181. polygonIndices[0] = 0;
  19182. polygonIndices[1] = j - 1;
  19183. polygonIndices[2] = j;
  19184. for (var k = 0; k < 3; k++) {
  19185. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  19186. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  19187. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  19188. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  19189. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  19190. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  19191. // Check if 2 points can be merged
  19192. 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)) {
  19193. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  19194. uvs.push(uv.x, uv.y);
  19195. normals.push(normal.x, normal.y, normal.z);
  19196. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  19197. }
  19198. indices.push(vertex_idx);
  19199. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  19200. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  19201. currentIndex++;
  19202. }
  19203. }
  19204. }
  19205. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  19206. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  19207. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  19208. mesh.setIndices(indices);
  19209. if (keepSubMeshes) {
  19210. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  19211. var materialIndexOffset = 0, materialMaxIndex;
  19212. mesh.subMeshes.length = 0;
  19213. for (var m in subMesh_dict) {
  19214. materialMaxIndex = -1;
  19215. for (var sm in subMesh_dict[m]) {
  19216. subMesh_obj = subMesh_dict[m][sm];
  19217. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  19218. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  19219. }
  19220. materialIndexOffset += ++materialMaxIndex;
  19221. }
  19222. }
  19223. return mesh;
  19224. };
  19225. // Build Mesh from CSG taking material and transforms into account
  19226. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  19227. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  19228. mesh.material = material;
  19229. mesh.position.copyFrom(this.position);
  19230. mesh.rotation.copyFrom(this.rotation);
  19231. mesh.scaling.copyFrom(this.scaling);
  19232. mesh.computeWorldMatrix(true);
  19233. return mesh;
  19234. };
  19235. return CSG;
  19236. })();
  19237. BABYLON.CSG = CSG;
  19238. })(BABYLON || (BABYLON = {}));
  19239. //# sourceMappingURL=babylon.csg.js.map
  19240. var BABYLON;
  19241. (function (BABYLON) {
  19242. var OculusDistortionCorrectionPostProcess = (function (_super) {
  19243. __extends(OculusDistortionCorrectionPostProcess, _super);
  19244. //ANY
  19245. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  19246. var _this = this;
  19247. _super.call(this, name, "oculusDistortionCorrection", [
  19248. 'LensCenter',
  19249. 'Scale',
  19250. 'ScaleIn',
  19251. 'HmdWarpParam'
  19252. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  19253. this._isRightEye = isRightEye;
  19254. this._distortionFactors = cameraSettings.DistortionK;
  19255. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  19256. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  19257. this.onSizeChanged = function () {
  19258. _this.aspectRatio = _this.width * .5 / _this.height;
  19259. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  19260. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  19261. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  19262. };
  19263. this.onApply = function (effect) {
  19264. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  19265. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  19266. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  19267. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  19268. };
  19269. }
  19270. return OculusDistortionCorrectionPostProcess;
  19271. })(BABYLON.PostProcess);
  19272. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  19273. })(BABYLON || (BABYLON = {}));
  19274. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  19275. // 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
  19276. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  19277. var BABYLON;
  19278. (function (BABYLON) {
  19279. (function (JoystickAxis) {
  19280. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  19281. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  19282. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  19283. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  19284. var JoystickAxis = BABYLON.JoystickAxis;
  19285. var VirtualJoystick = (function () {
  19286. function VirtualJoystick(leftJoystick) {
  19287. var _this = this;
  19288. if (leftJoystick) {
  19289. this._leftJoystick = true;
  19290. }
  19291. else {
  19292. this._leftJoystick = false;
  19293. }
  19294. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  19295. VirtualJoystick._globalJoystickIndex++;
  19296. // By default left & right arrow keys are moving the X
  19297. // and up & down keys are moving the Y
  19298. this._axisTargetedByLeftAndRight = 0 /* X */;
  19299. this._axisTargetedByUpAndDown = 1 /* Y */;
  19300. this.reverseLeftRight = false;
  19301. this.reverseUpDown = false;
  19302. // collections of pointers
  19303. this._touches = new BABYLON.VirtualJoystick.Collection();
  19304. this.deltaPosition = BABYLON.Vector3.Zero();
  19305. this._joystickSensibility = 25;
  19306. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19307. this._rotationSpeed = 25;
  19308. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  19309. this._rotateOnAxisRelativeToMesh = false;
  19310. // injecting a canvas element on top of the canvas 3D game
  19311. if (!VirtualJoystick.vjCanvas) {
  19312. window.addEventListener("resize", function () {
  19313. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19314. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19315. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  19316. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  19317. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  19318. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  19319. }, false);
  19320. VirtualJoystick.vjCanvas = document.createElement("canvas");
  19321. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  19322. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  19323. VirtualJoystick.vjCanvas.width = window.innerWidth;
  19324. VirtualJoystick.vjCanvas.height = window.innerHeight;
  19325. VirtualJoystick.vjCanvas.style.width = "100%";
  19326. VirtualJoystick.vjCanvas.style.height = "100%";
  19327. VirtualJoystick.vjCanvas.style.position = "absolute";
  19328. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  19329. VirtualJoystick.vjCanvas.style.top = "0px";
  19330. VirtualJoystick.vjCanvas.style.left = "0px";
  19331. VirtualJoystick.vjCanvas.style.zIndex = "5";
  19332. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  19333. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  19334. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  19335. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19336. document.body.appendChild(VirtualJoystick.vjCanvas);
  19337. }
  19338. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  19339. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  19340. this.pressed = false;
  19341. // default joystick color
  19342. this._joystickColor = "cyan";
  19343. this._joystickPointerID = -1;
  19344. // current joystick position
  19345. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  19346. // origin joystick position
  19347. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  19348. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  19349. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  19350. _this._onPointerDown(evt);
  19351. }, false);
  19352. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  19353. _this._onPointerMove(evt);
  19354. }, false);
  19355. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  19356. _this._onPointerUp(evt);
  19357. }, false);
  19358. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  19359. _this._onPointerUp(evt);
  19360. }, false);
  19361. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  19362. evt.preventDefault(); // Disables system menu
  19363. }, false);
  19364. requestAnimationFrame(function () {
  19365. _this._drawVirtualJoystick();
  19366. });
  19367. }
  19368. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  19369. this._joystickSensibility = newJoystickSensibility;
  19370. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  19371. };
  19372. VirtualJoystick.prototype._onPointerDown = function (e) {
  19373. var positionOnScreenCondition;
  19374. e.preventDefault();
  19375. if (this._leftJoystick === true) {
  19376. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  19377. }
  19378. else {
  19379. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  19380. }
  19381. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  19382. // First contact will be dedicated to the virtual joystick
  19383. this._joystickPointerID = e.pointerId;
  19384. this._joystickPointerStartPos.x = e.clientX;
  19385. this._joystickPointerStartPos.y = e.clientY;
  19386. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  19387. this._deltaJoystickVector.x = 0;
  19388. this._deltaJoystickVector.y = 0;
  19389. this.pressed = true;
  19390. this._touches.add(e.pointerId.toString(), e);
  19391. }
  19392. else {
  19393. // You can only trigger the action buttons with a joystick declared
  19394. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  19395. this._action();
  19396. this._touches.add(e.pointerId.toString(), e);
  19397. }
  19398. }
  19399. };
  19400. VirtualJoystick.prototype._onPointerMove = function (e) {
  19401. // If the current pointer is the one associated to the joystick (first touch contact)
  19402. if (this._joystickPointerID == e.pointerId) {
  19403. this._joystickPointerPos.x = e.clientX;
  19404. this._joystickPointerPos.y = e.clientY;
  19405. this._deltaJoystickVector = this._joystickPointerPos.clone();
  19406. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  19407. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  19408. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  19409. switch (this._axisTargetedByLeftAndRight) {
  19410. case 0 /* X */:
  19411. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  19412. break;
  19413. case 1 /* Y */:
  19414. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  19415. break;
  19416. case 2 /* Z */:
  19417. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  19418. break;
  19419. }
  19420. var directionUpDown = this.reverseUpDown ? 1 : -1;
  19421. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  19422. switch (this._axisTargetedByUpAndDown) {
  19423. case 0 /* X */:
  19424. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  19425. break;
  19426. case 1 /* Y */:
  19427. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  19428. break;
  19429. case 2 /* Z */:
  19430. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  19431. break;
  19432. }
  19433. }
  19434. else {
  19435. if (this._touches.item(e.pointerId.toString())) {
  19436. this._touches.item(e.pointerId.toString()).x = e.clientX;
  19437. this._touches.item(e.pointerId.toString()).y = e.clientY;
  19438. }
  19439. }
  19440. };
  19441. VirtualJoystick.prototype._onPointerUp = function (e) {
  19442. this._clearCanvas();
  19443. if (this._joystickPointerID == e.pointerId) {
  19444. this._joystickPointerID = -1;
  19445. this.pressed = false;
  19446. }
  19447. this._deltaJoystickVector.x = 0;
  19448. this._deltaJoystickVector.y = 0;
  19449. this._touches.remove(e.pointerId.toString());
  19450. };
  19451. /**
  19452. * Change the color of the virtual joystick
  19453. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  19454. */
  19455. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  19456. this._joystickColor = newColor;
  19457. };
  19458. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  19459. this._action = action;
  19460. };
  19461. // Define which axis you'd like to control for left & right
  19462. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  19463. switch (axis) {
  19464. case 0 /* X */:
  19465. case 1 /* Y */:
  19466. case 2 /* Z */:
  19467. this._axisTargetedByLeftAndRight = axis;
  19468. break;
  19469. default:
  19470. this._axisTargetedByLeftAndRight = 0 /* X */;
  19471. break;
  19472. }
  19473. };
  19474. // Define which axis you'd like to control for up & down
  19475. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  19476. switch (axis) {
  19477. case 0 /* X */:
  19478. case 1 /* Y */:
  19479. case 2 /* Z */:
  19480. this._axisTargetedByUpAndDown = axis;
  19481. break;
  19482. default:
  19483. this._axisTargetedByUpAndDown = 1 /* Y */;
  19484. break;
  19485. }
  19486. };
  19487. VirtualJoystick.prototype._clearCanvas = function () {
  19488. if (this._leftJoystick) {
  19489. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  19490. }
  19491. else {
  19492. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  19493. }
  19494. };
  19495. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  19496. var _this = this;
  19497. if (this.pressed) {
  19498. this._clearCanvas();
  19499. this._touches.forEach(function (touch) {
  19500. if (touch.pointerId === _this._joystickPointerID) {
  19501. VirtualJoystick.vjCanvasContext.beginPath();
  19502. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19503. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19504. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  19505. VirtualJoystick.vjCanvasContext.stroke();
  19506. VirtualJoystick.vjCanvasContext.beginPath();
  19507. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19508. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  19509. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  19510. VirtualJoystick.vjCanvasContext.stroke();
  19511. VirtualJoystick.vjCanvasContext.beginPath();
  19512. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  19513. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  19514. VirtualJoystick.vjCanvasContext.stroke();
  19515. }
  19516. else {
  19517. VirtualJoystick.vjCanvasContext.beginPath();
  19518. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  19519. VirtualJoystick.vjCanvasContext.beginPath();
  19520. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  19521. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  19522. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  19523. VirtualJoystick.vjCanvasContext.stroke();
  19524. }
  19525. ;
  19526. });
  19527. }
  19528. requestAnimationFrame(function () {
  19529. _this._drawVirtualJoystick();
  19530. });
  19531. };
  19532. VirtualJoystick.prototype.releaseCanvas = function () {
  19533. if (VirtualJoystick.vjCanvas) {
  19534. document.body.removeChild(VirtualJoystick.vjCanvas);
  19535. VirtualJoystick.vjCanvas = null;
  19536. }
  19537. };
  19538. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  19539. VirtualJoystick._globalJoystickIndex = 0;
  19540. return VirtualJoystick;
  19541. })();
  19542. BABYLON.VirtualJoystick = VirtualJoystick;
  19543. })(BABYLON || (BABYLON = {}));
  19544. var BABYLON;
  19545. (function (BABYLON) {
  19546. var VirtualJoystick;
  19547. (function (VirtualJoystick) {
  19548. var Collection = (function () {
  19549. function Collection() {
  19550. this._count = 0;
  19551. this._collection = new Array();
  19552. }
  19553. Collection.prototype.Count = function () {
  19554. return this._count;
  19555. };
  19556. Collection.prototype.add = function (key, item) {
  19557. if (this._collection[key] != undefined) {
  19558. return undefined;
  19559. }
  19560. this._collection[key] = item;
  19561. return ++this._count;
  19562. };
  19563. Collection.prototype.remove = function (key) {
  19564. if (this._collection[key] == undefined) {
  19565. return undefined;
  19566. }
  19567. delete this._collection[key];
  19568. return --this._count;
  19569. };
  19570. Collection.prototype.item = function (key) {
  19571. return this._collection[key];
  19572. };
  19573. Collection.prototype.forEach = function (block) {
  19574. var key;
  19575. for (key in this._collection) {
  19576. if (this._collection.hasOwnProperty(key)) {
  19577. block(this._collection[key]);
  19578. }
  19579. }
  19580. };
  19581. return Collection;
  19582. })();
  19583. VirtualJoystick.Collection = Collection;
  19584. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  19585. })(BABYLON || (BABYLON = {}));
  19586. //# sourceMappingURL=babylon.virtualJoystick.js.map
  19587. var BABYLON;
  19588. (function (BABYLON) {
  19589. var OculusRiftDevKit2013_Metric = {
  19590. HResolution: 1280,
  19591. VResolution: 800,
  19592. HScreenSize: 0.149759993,
  19593. VScreenSize: 0.0935999975,
  19594. VScreenCenter: 0.0467999987,
  19595. EyeToScreenDistance: 0.0410000011,
  19596. LensSeparationDistance: 0.0635000020,
  19597. InterpupillaryDistance: 0.0640000030,
  19598. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19599. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19600. PostProcessScaleFactor: 1.714605507808412,
  19601. LensCenterOffset: 0.151976421
  19602. };
  19603. var _OculusInnerCamera = (function (_super) {
  19604. __extends(_OculusInnerCamera, _super);
  19605. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  19606. _super.call(this, name, position, scene);
  19607. this._workMatrix = new BABYLON.Matrix();
  19608. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19609. // Constants
  19610. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19611. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19612. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19613. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19614. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19615. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19616. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19617. // Postprocess
  19618. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19619. }
  19620. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  19621. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19622. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19623. return this._projectionMatrix;
  19624. };
  19625. _OculusInnerCamera.prototype._getViewMatrix = function () {
  19626. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19627. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19628. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19629. // Computing target and final matrix
  19630. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19631. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19632. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19633. return this._viewMatrix;
  19634. };
  19635. return _OculusInnerCamera;
  19636. })(BABYLON.FreeCamera);
  19637. var OculusCamera = (function (_super) {
  19638. __extends(OculusCamera, _super);
  19639. function OculusCamera(name, position, scene) {
  19640. _super.call(this, name, position, scene);
  19641. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  19642. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  19643. this.subCameras.push(this._leftCamera);
  19644. this.subCameras.push(this._rightCamera);
  19645. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19646. }
  19647. OculusCamera.prototype._update = function () {
  19648. this._leftCamera.position.copyFrom(this.position);
  19649. this._rightCamera.position.copyFrom(this.position);
  19650. this._updateCamera(this._leftCamera);
  19651. this._updateCamera(this._rightCamera);
  19652. _super.prototype._update.call(this);
  19653. };
  19654. OculusCamera.prototype._updateCamera = function (camera) {
  19655. camera.minZ = this.minZ;
  19656. camera.maxZ = this.maxZ;
  19657. camera.rotation.x = this.rotation.x;
  19658. camera.rotation.y = this.rotation.y;
  19659. camera.rotation.z = this.rotation.z;
  19660. };
  19661. // Oculus events
  19662. OculusCamera.prototype._onOrientationEvent = function (evt) {
  19663. var yaw = evt.alpha / 180 * Math.PI;
  19664. var pitch = evt.beta / 180 * Math.PI;
  19665. var roll = evt.gamma / 180 * Math.PI;
  19666. if (!this._offsetOrientation) {
  19667. this._offsetOrientation = {
  19668. yaw: yaw,
  19669. pitch: pitch,
  19670. roll: roll
  19671. };
  19672. return;
  19673. }
  19674. else {
  19675. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19676. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19677. this.rotation.z += this._offsetOrientation.roll - roll;
  19678. this._offsetOrientation.yaw = yaw;
  19679. this._offsetOrientation.pitch = pitch;
  19680. this._offsetOrientation.roll = roll;
  19681. }
  19682. };
  19683. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  19684. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19685. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19686. };
  19687. OculusCamera.prototype.detachControl = function (element) {
  19688. _super.prototype.detachControl.call(this, element);
  19689. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19690. };
  19691. return OculusCamera;
  19692. })(BABYLON.FreeCamera);
  19693. BABYLON.OculusCamera = OculusCamera;
  19694. })(BABYLON || (BABYLON = {}));
  19695. //# sourceMappingURL=babylon.oculusCamera.js.map
  19696. var BABYLON;
  19697. (function (BABYLON) {
  19698. var OculusRiftDevKit2013_Metric = {
  19699. HResolution: 1280,
  19700. VResolution: 800,
  19701. HScreenSize: 0.149759993,
  19702. VScreenSize: 0.0935999975,
  19703. VScreenCenter: 0.0467999987,
  19704. EyeToScreenDistance: 0.0410000011,
  19705. LensSeparationDistance: 0.0635000020,
  19706. InterpupillaryDistance: 0.0640000030,
  19707. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  19708. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  19709. PostProcessScaleFactor: 1.714605507808412,
  19710. LensCenterOffset: 0.151976421
  19711. };
  19712. var _OculusInnerGamepadCamera = (function (_super) {
  19713. __extends(_OculusInnerGamepadCamera, _super);
  19714. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  19715. _super.call(this, name, position, scene);
  19716. this._workMatrix = new BABYLON.Matrix();
  19717. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  19718. // Constants
  19719. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  19720. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  19721. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  19722. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  19723. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  19724. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  19725. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  19726. // Postprocess
  19727. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  19728. }
  19729. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  19730. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  19731. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  19732. return this._projectionMatrix;
  19733. };
  19734. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  19735. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  19736. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  19737. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  19738. // Computing target and final matrix
  19739. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  19740. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  19741. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  19742. return this._viewMatrix;
  19743. };
  19744. return _OculusInnerGamepadCamera;
  19745. })(BABYLON.FreeCamera);
  19746. var OculusGamepadCamera = (function (_super) {
  19747. __extends(OculusGamepadCamera, _super);
  19748. function OculusGamepadCamera(name, position, scene) {
  19749. var _this = this;
  19750. _super.call(this, name, position, scene);
  19751. this.angularSensibility = 200;
  19752. this.moveSensibility = 75;
  19753. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  19754. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  19755. this.subCameras.push(this._leftCamera);
  19756. this.subCameras.push(this._rightCamera);
  19757. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  19758. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  19759. _this._onNewGameConnected(gamepad);
  19760. });
  19761. }
  19762. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  19763. // Only the first gamepad can control the camera
  19764. if (gamepad.index === 0) {
  19765. this._gamepad = gamepad;
  19766. }
  19767. };
  19768. OculusGamepadCamera.prototype._update = function () {
  19769. this._leftCamera.position.copyFrom(this.position);
  19770. this._rightCamera.position.copyFrom(this.position);
  19771. this._updateCamera(this._leftCamera);
  19772. this._updateCamera(this._rightCamera);
  19773. _super.prototype._update.call(this);
  19774. };
  19775. OculusGamepadCamera.prototype._checkInputs = function () {
  19776. if (!this._gamepad) {
  19777. return;
  19778. }
  19779. var LSValues = this._gamepad.leftStick;
  19780. var normalizedLX = LSValues.x / this.moveSensibility;
  19781. var normalizedLY = LSValues.y / this.moveSensibility;
  19782. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  19783. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  19784. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19785. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  19786. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19787. };
  19788. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  19789. camera.minZ = this.minZ;
  19790. camera.maxZ = this.maxZ;
  19791. camera.rotation.x = this.rotation.x;
  19792. camera.rotation.y = this.rotation.y;
  19793. camera.rotation.z = this.rotation.z;
  19794. };
  19795. // Oculus events
  19796. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  19797. var yaw = evt.alpha / 180 * Math.PI;
  19798. var pitch = evt.beta / 180 * Math.PI;
  19799. var roll = evt.gamma / 180 * Math.PI;
  19800. if (!this._offsetOrientation) {
  19801. this._offsetOrientation = {
  19802. yaw: yaw,
  19803. pitch: pitch,
  19804. roll: roll
  19805. };
  19806. return;
  19807. }
  19808. else {
  19809. this.rotation.y += yaw - this._offsetOrientation.yaw;
  19810. this.rotation.x += pitch - this._offsetOrientation.pitch;
  19811. this.rotation.z += this._offsetOrientation.roll - roll;
  19812. this._offsetOrientation.yaw = yaw;
  19813. this._offsetOrientation.pitch = pitch;
  19814. this._offsetOrientation.roll = roll;
  19815. }
  19816. };
  19817. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  19818. _super.prototype.attachControl.call(this, element, noPreventDefault);
  19819. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  19820. };
  19821. OculusGamepadCamera.prototype.detachControl = function (element) {
  19822. _super.prototype.detachControl.call(this, element);
  19823. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  19824. };
  19825. OculusGamepadCamera.prototype.dispose = function () {
  19826. this._gamepads.dispose();
  19827. _super.prototype.dispose.call(this);
  19828. };
  19829. return OculusGamepadCamera;
  19830. })(BABYLON.FreeCamera);
  19831. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  19832. })(BABYLON || (BABYLON = {}));
  19833. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  19834. var BABYLON;
  19835. (function (BABYLON) {
  19836. // We're mainly based on the logic defined into the FreeCamera code
  19837. var VirtualJoysticksCamera = (function (_super) {
  19838. __extends(VirtualJoysticksCamera, _super);
  19839. function VirtualJoysticksCamera(name, position, scene) {
  19840. _super.call(this, name, position, scene);
  19841. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  19842. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  19843. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  19844. this._leftjoystick.setJoystickSensibility(0.15);
  19845. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  19846. this._rightjoystick.setAxisForUpDown(0 /* X */);
  19847. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  19848. this._rightjoystick.reverseUpDown = true;
  19849. this._rightjoystick.setJoystickSensibility(0.05);
  19850. this._rightjoystick.setJoystickColor("yellow");
  19851. }
  19852. VirtualJoysticksCamera.prototype._checkInputs = function () {
  19853. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  19854. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  19855. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  19856. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  19857. if (!this._leftjoystick.pressed) {
  19858. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  19859. }
  19860. if (!this._rightjoystick.pressed) {
  19861. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  19862. }
  19863. };
  19864. VirtualJoysticksCamera.prototype.dispose = function () {
  19865. this._leftjoystick.releaseCanvas();
  19866. _super.prototype.dispose.call(this);
  19867. };
  19868. return VirtualJoysticksCamera;
  19869. })(BABYLON.FreeCamera);
  19870. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  19871. })(BABYLON || (BABYLON = {}));
  19872. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  19873. var BABYLON;
  19874. (function (BABYLON) {
  19875. var ShaderMaterial = (function (_super) {
  19876. __extends(ShaderMaterial, _super);
  19877. function ShaderMaterial(name, scene, shaderPath, options) {
  19878. _super.call(this, name, scene);
  19879. this._textures = new Array();
  19880. this._floats = new Array();
  19881. this._floatsArrays = {};
  19882. this._colors3 = new Array();
  19883. this._colors4 = new Array();
  19884. this._vectors2 = new Array();
  19885. this._vectors3 = new Array();
  19886. this._matrices = new Array();
  19887. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  19888. this._shaderPath = shaderPath;
  19889. options.needAlphaBlending = options.needAlphaBlending || false;
  19890. options.needAlphaTesting = options.needAlphaTesting || false;
  19891. options.attributes = options.attributes || ["position", "normal", "uv"];
  19892. options.uniforms = options.uniforms || ["worldViewProjection"];
  19893. options.samplers = options.samplers || [];
  19894. this._options = options;
  19895. }
  19896. ShaderMaterial.prototype.needAlphaBlending = function () {
  19897. return this._options.needAlphaBlending;
  19898. };
  19899. ShaderMaterial.prototype.needAlphaTesting = function () {
  19900. return this._options.needAlphaTesting;
  19901. };
  19902. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  19903. if (this._options.uniforms.indexOf(uniformName) === -1) {
  19904. this._options.uniforms.push(uniformName);
  19905. }
  19906. };
  19907. ShaderMaterial.prototype.setTexture = function (name, texture) {
  19908. if (this._options.samplers.indexOf(name) === -1) {
  19909. this._options.samplers.push(name);
  19910. }
  19911. this._textures[name] = texture;
  19912. return this;
  19913. };
  19914. ShaderMaterial.prototype.setFloat = function (name, value) {
  19915. this._checkUniform(name);
  19916. this._floats[name] = value;
  19917. return this;
  19918. };
  19919. ShaderMaterial.prototype.setFloats = function (name, value) {
  19920. this._checkUniform(name);
  19921. this._floatsArrays[name] = value;
  19922. return this;
  19923. };
  19924. ShaderMaterial.prototype.setColor3 = function (name, value) {
  19925. this._checkUniform(name);
  19926. this._colors3[name] = value;
  19927. return this;
  19928. };
  19929. ShaderMaterial.prototype.setColor4 = function (name, value) {
  19930. this._checkUniform(name);
  19931. this._colors4[name] = value;
  19932. return this;
  19933. };
  19934. ShaderMaterial.prototype.setVector2 = function (name, value) {
  19935. this._checkUniform(name);
  19936. this._vectors2[name] = value;
  19937. return this;
  19938. };
  19939. ShaderMaterial.prototype.setVector3 = function (name, value) {
  19940. this._checkUniform(name);
  19941. this._vectors3[name] = value;
  19942. return this;
  19943. };
  19944. ShaderMaterial.prototype.setMatrix = function (name, value) {
  19945. this._checkUniform(name);
  19946. this._matrices[name] = value;
  19947. return this;
  19948. };
  19949. ShaderMaterial.prototype.isReady = function () {
  19950. var scene = this.getScene();
  19951. var engine = scene.getEngine();
  19952. if (!this.checkReadyOnEveryCall) {
  19953. if (this._renderId === scene.getRenderId()) {
  19954. return true;
  19955. }
  19956. }
  19957. var previousEffect = this._effect;
  19958. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  19959. if (!this._effect.isReady()) {
  19960. return false;
  19961. }
  19962. if (previousEffect !== this._effect) {
  19963. scene.resetCachedMaterial();
  19964. }
  19965. this._renderId = scene.getRenderId();
  19966. return true;
  19967. };
  19968. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  19969. var scene = this.getScene();
  19970. if (this._options.uniforms.indexOf("world") !== -1) {
  19971. this._effect.setMatrix("world", world);
  19972. }
  19973. if (this._options.uniforms.indexOf("worldView") !== -1) {
  19974. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  19975. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  19976. }
  19977. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  19978. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  19979. }
  19980. };
  19981. ShaderMaterial.prototype.bind = function (world) {
  19982. // Std values
  19983. this.bindOnlyWorldMatrix(world);
  19984. if (this.getScene().getCachedMaterial() !== this) {
  19985. if (this._options.uniforms.indexOf("view") !== -1) {
  19986. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  19987. }
  19988. if (this._options.uniforms.indexOf("projection") !== -1) {
  19989. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  19990. }
  19991. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  19992. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  19993. }
  19994. for (var name in this._textures) {
  19995. this._effect.setTexture(name, this._textures[name]);
  19996. }
  19997. for (name in this._floats) {
  19998. this._effect.setFloat(name, this._floats[name]);
  19999. }
  20000. for (name in this._floatsArrays) {
  20001. this._effect.setArray(name, this._floatsArrays[name]);
  20002. }
  20003. for (name in this._colors3) {
  20004. this._effect.setColor3(name, this._colors3[name]);
  20005. }
  20006. for (name in this._colors4) {
  20007. var color = this._colors4[name];
  20008. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  20009. }
  20010. for (name in this._vectors2) {
  20011. this._effect.setVector2(name, this._vectors2[name]);
  20012. }
  20013. for (name in this._vectors3) {
  20014. this._effect.setVector3(name, this._vectors3[name]);
  20015. }
  20016. for (name in this._matrices) {
  20017. this._effect.setMatrix(name, this._matrices[name]);
  20018. }
  20019. }
  20020. _super.prototype.bind.call(this, world, null);
  20021. };
  20022. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  20023. for (var name in this._textures) {
  20024. this._textures[name].dispose();
  20025. }
  20026. this._textures = [];
  20027. _super.prototype.dispose.call(this, forceDisposeEffect);
  20028. };
  20029. return ShaderMaterial;
  20030. })(BABYLON.Material);
  20031. BABYLON.ShaderMaterial = ShaderMaterial;
  20032. })(BABYLON || (BABYLON = {}));
  20033. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  20034. (function (BABYLON) {
  20035. var VertexData = (function () {
  20036. function VertexData() {
  20037. }
  20038. VertexData.prototype.set = function (data, kind) {
  20039. switch (kind) {
  20040. case BABYLON.VertexBuffer.PositionKind:
  20041. this.positions = data;
  20042. break;
  20043. case BABYLON.VertexBuffer.NormalKind:
  20044. this.normals = data;
  20045. break;
  20046. case BABYLON.VertexBuffer.UVKind:
  20047. this.uvs = data;
  20048. break;
  20049. case BABYLON.VertexBuffer.UV2Kind:
  20050. this.uv2s = data;
  20051. break;
  20052. case BABYLON.VertexBuffer.ColorKind:
  20053. this.colors = data;
  20054. break;
  20055. case BABYLON.VertexBuffer.MatricesIndicesKind:
  20056. this.matricesIndices = data;
  20057. break;
  20058. case BABYLON.VertexBuffer.MatricesWeightsKind:
  20059. this.matricesWeights = data;
  20060. break;
  20061. }
  20062. };
  20063. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  20064. this._applyTo(mesh, updatable);
  20065. };
  20066. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  20067. this._applyTo(geometry, updatable);
  20068. };
  20069. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  20070. this._update(mesh);
  20071. };
  20072. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  20073. this._update(geometry);
  20074. };
  20075. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  20076. if (this.positions) {
  20077. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  20078. }
  20079. if (this.normals) {
  20080. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  20081. }
  20082. if (this.uvs) {
  20083. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  20084. }
  20085. if (this.uv2s) {
  20086. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  20087. }
  20088. if (this.colors) {
  20089. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  20090. }
  20091. if (this.matricesIndices) {
  20092. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  20093. }
  20094. if (this.matricesWeights) {
  20095. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  20096. }
  20097. if (this.indices) {
  20098. meshOrGeometry.setIndices(this.indices);
  20099. }
  20100. };
  20101. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  20102. if (this.positions) {
  20103. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  20104. }
  20105. if (this.normals) {
  20106. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  20107. }
  20108. if (this.uvs) {
  20109. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  20110. }
  20111. if (this.uv2s) {
  20112. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  20113. }
  20114. if (this.colors) {
  20115. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  20116. }
  20117. if (this.matricesIndices) {
  20118. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  20119. }
  20120. if (this.matricesWeights) {
  20121. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  20122. }
  20123. if (this.indices) {
  20124. meshOrGeometry.setIndices(this.indices);
  20125. }
  20126. };
  20127. VertexData.prototype.transform = function (matrix) {
  20128. var transformed = BABYLON.Vector3.Zero();
  20129. if (this.positions) {
  20130. var position = BABYLON.Vector3.Zero();
  20131. for (var index = 0; index < this.positions.length; index += 3) {
  20132. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  20133. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  20134. this.positions[index] = transformed.x;
  20135. this.positions[index + 1] = transformed.y;
  20136. this.positions[index + 2] = transformed.z;
  20137. }
  20138. }
  20139. if (this.normals) {
  20140. var normal = BABYLON.Vector3.Zero();
  20141. for (index = 0; index < this.normals.length; index += 3) {
  20142. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  20143. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  20144. this.normals[index] = transformed.x;
  20145. this.normals[index + 1] = transformed.y;
  20146. this.normals[index + 2] = transformed.z;
  20147. }
  20148. }
  20149. };
  20150. VertexData.prototype.merge = function (other) {
  20151. if (other.indices) {
  20152. if (!this.indices) {
  20153. this.indices = [];
  20154. }
  20155. var offset = this.positions ? this.positions.length / 3 : 0;
  20156. for (var index = 0; index < other.indices.length; index++) {
  20157. this.indices.push(other.indices[index] + offset);
  20158. }
  20159. }
  20160. if (other.positions) {
  20161. if (!this.positions) {
  20162. this.positions = [];
  20163. }
  20164. for (index = 0; index < other.positions.length; index++) {
  20165. this.positions.push(other.positions[index]);
  20166. }
  20167. }
  20168. if (other.normals) {
  20169. if (!this.normals) {
  20170. this.normals = [];
  20171. }
  20172. for (index = 0; index < other.normals.length; index++) {
  20173. this.normals.push(other.normals[index]);
  20174. }
  20175. }
  20176. if (other.uvs) {
  20177. if (!this.uvs) {
  20178. this.uvs = [];
  20179. }
  20180. for (index = 0; index < other.uvs.length; index++) {
  20181. this.uvs.push(other.uvs[index]);
  20182. }
  20183. }
  20184. if (other.uv2s) {
  20185. if (!this.uv2s) {
  20186. this.uv2s = [];
  20187. }
  20188. for (index = 0; index < other.uv2s.length; index++) {
  20189. this.uv2s.push(other.uv2s[index]);
  20190. }
  20191. }
  20192. if (other.matricesIndices) {
  20193. if (!this.matricesIndices) {
  20194. this.matricesIndices = [];
  20195. }
  20196. for (index = 0; index < other.matricesIndices.length; index++) {
  20197. this.matricesIndices.push(other.matricesIndices[index]);
  20198. }
  20199. }
  20200. if (other.matricesWeights) {
  20201. if (!this.matricesWeights) {
  20202. this.matricesWeights = [];
  20203. }
  20204. for (index = 0; index < other.matricesWeights.length; index++) {
  20205. this.matricesWeights.push(other.matricesWeights[index]);
  20206. }
  20207. }
  20208. if (other.colors) {
  20209. if (!this.colors) {
  20210. this.colors = [];
  20211. }
  20212. for (index = 0; index < other.colors.length; index++) {
  20213. this.colors.push(other.colors[index]);
  20214. }
  20215. }
  20216. };
  20217. // Statics
  20218. VertexData.ExtractFromMesh = function (mesh) {
  20219. return VertexData._ExtractFrom(mesh);
  20220. };
  20221. VertexData.ExtractFromGeometry = function (geometry) {
  20222. return VertexData._ExtractFrom(geometry);
  20223. };
  20224. VertexData._ExtractFrom = function (meshOrGeometry) {
  20225. var result = new BABYLON.VertexData();
  20226. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20227. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20228. }
  20229. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20230. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20231. }
  20232. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20233. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20234. }
  20235. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  20236. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  20237. }
  20238. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  20239. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  20240. }
  20241. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  20242. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  20243. }
  20244. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  20245. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  20246. }
  20247. result.indices = meshOrGeometry.getIndices();
  20248. return result;
  20249. };
  20250. VertexData.CreateBox = function (size) {
  20251. var normalsSource = [
  20252. new BABYLON.Vector3(0, 0, 1),
  20253. new BABYLON.Vector3(0, 0, -1),
  20254. new BABYLON.Vector3(1, 0, 0),
  20255. new BABYLON.Vector3(-1, 0, 0),
  20256. new BABYLON.Vector3(0, 1, 0),
  20257. new BABYLON.Vector3(0, -1, 0)
  20258. ];
  20259. var indices = [];
  20260. var positions = [];
  20261. var normals = [];
  20262. var uvs = [];
  20263. size = size || 1;
  20264. for (var index = 0; index < normalsSource.length; index++) {
  20265. var normal = normalsSource[index];
  20266. // Get two vectors perpendicular to the face normal and to each other.
  20267. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  20268. var side2 = BABYLON.Vector3.Cross(normal, side1);
  20269. // Six indices (two triangles) per face.
  20270. var verticesLength = positions.length / 3;
  20271. indices.push(verticesLength);
  20272. indices.push(verticesLength + 1);
  20273. indices.push(verticesLength + 2);
  20274. indices.push(verticesLength);
  20275. indices.push(verticesLength + 2);
  20276. indices.push(verticesLength + 3);
  20277. // Four vertices per face.
  20278. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  20279. positions.push(vertex.x, vertex.y, vertex.z);
  20280. normals.push(normal.x, normal.y, normal.z);
  20281. uvs.push(1.0, 1.0);
  20282. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  20283. positions.push(vertex.x, vertex.y, vertex.z);
  20284. normals.push(normal.x, normal.y, normal.z);
  20285. uvs.push(0.0, 1.0);
  20286. vertex = normal.add(side1).add(side2).scale(size / 2);
  20287. positions.push(vertex.x, vertex.y, vertex.z);
  20288. normals.push(normal.x, normal.y, normal.z);
  20289. uvs.push(0.0, 0.0);
  20290. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  20291. positions.push(vertex.x, vertex.y, vertex.z);
  20292. normals.push(normal.x, normal.y, normal.z);
  20293. uvs.push(1.0, 0.0);
  20294. }
  20295. // Result
  20296. var vertexData = new BABYLON.VertexData();
  20297. vertexData.indices = indices;
  20298. vertexData.positions = positions;
  20299. vertexData.normals = normals;
  20300. vertexData.uvs = uvs;
  20301. return vertexData;
  20302. };
  20303. VertexData.CreateSphere = function (segments, diameter) {
  20304. segments = segments || 32;
  20305. diameter = diameter || 1;
  20306. var radius = diameter / 2;
  20307. var totalZRotationSteps = 2 + segments;
  20308. var totalYRotationSteps = 2 * totalZRotationSteps;
  20309. var indices = [];
  20310. var positions = [];
  20311. var normals = [];
  20312. var uvs = [];
  20313. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  20314. var normalizedZ = zRotationStep / totalZRotationSteps;
  20315. var angleZ = (normalizedZ * Math.PI);
  20316. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  20317. var normalizedY = yRotationStep / totalYRotationSteps;
  20318. var angleY = normalizedY * Math.PI * 2;
  20319. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  20320. var rotationY = BABYLON.Matrix.RotationY(angleY);
  20321. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  20322. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  20323. var vertex = complete.scale(radius);
  20324. var normal = BABYLON.Vector3.Normalize(vertex);
  20325. positions.push(vertex.x, vertex.y, vertex.z);
  20326. normals.push(normal.x, normal.y, normal.z);
  20327. uvs.push(normalizedZ, normalizedY);
  20328. }
  20329. if (zRotationStep > 0) {
  20330. var verticesCount = positions.length / 3;
  20331. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  20332. indices.push((firstIndex));
  20333. indices.push((firstIndex + 1));
  20334. indices.push(firstIndex + totalYRotationSteps + 1);
  20335. indices.push((firstIndex + totalYRotationSteps + 1));
  20336. indices.push((firstIndex + 1));
  20337. indices.push((firstIndex + totalYRotationSteps + 2));
  20338. }
  20339. }
  20340. }
  20341. // Result
  20342. var vertexData = new BABYLON.VertexData();
  20343. vertexData.indices = indices;
  20344. vertexData.positions = positions;
  20345. vertexData.normals = normals;
  20346. vertexData.uvs = uvs;
  20347. return vertexData;
  20348. };
  20349. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions) {
  20350. if (subdivisions === void 0) { subdivisions = 1; }
  20351. var radiusTop = diameterTop / 2;
  20352. var radiusBottom = diameterBottom / 2;
  20353. var indices = [];
  20354. var positions = [];
  20355. var normals = [];
  20356. var uvs = [];
  20357. height = height || 1;
  20358. diameterTop = diameterTop || 0.5;
  20359. diameterBottom = diameterBottom || 1;
  20360. tessellation = tessellation || 16;
  20361. subdivisions = subdivisions || 1;
  20362. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  20363. var getCircleVector = function (i) {
  20364. var angle = (i * 2.0 * Math.PI / tessellation);
  20365. var dx = Math.cos(angle);
  20366. var dz = Math.sin(angle);
  20367. return new BABYLON.Vector3(dx, 0, dz);
  20368. };
  20369. var createCylinderCap = function (isTop) {
  20370. var radius = isTop ? radiusTop : radiusBottom;
  20371. if (radius == 0) {
  20372. return;
  20373. }
  20374. var vbase = positions.length / 3;
  20375. var offset = new BABYLON.Vector3(0, height / 2, 0);
  20376. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  20377. if (!isTop) {
  20378. offset.scaleInPlace(-1);
  20379. textureScale.x = -textureScale.x;
  20380. }
  20381. for (i = 0; i < tessellation; i++) {
  20382. var circleVector = getCircleVector(i);
  20383. var position = circleVector.scale(radius).add(offset);
  20384. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  20385. positions.push(position.x, position.y, position.z);
  20386. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20387. }
  20388. for (var i = 0; i < tessellation - 2; i++) {
  20389. if (!isTop) {
  20390. indices.push(vbase);
  20391. indices.push(vbase + (i + 2) % tessellation);
  20392. indices.push(vbase + (i + 1) % tessellation);
  20393. }
  20394. else {
  20395. indices.push(vbase);
  20396. indices.push(vbase + (i + 1) % tessellation);
  20397. indices.push(vbase + (i + 2) % tessellation);
  20398. }
  20399. }
  20400. };
  20401. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  20402. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  20403. var stride = tessellation + 1;
  20404. for (var i = 0; i <= tessellation; i++) {
  20405. var circleVector = getCircleVector(i);
  20406. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  20407. var position, radius = radiusBottom;
  20408. for (var s = 0; s <= subdivisions; s++) {
  20409. // Update variables
  20410. position = circleVector.scale(radius);
  20411. position.addInPlace(base.add(offset.scale(s)));
  20412. textureCoordinate.y += 1 / subdivisions;
  20413. radius += (radiusTop - radiusBottom) / subdivisions;
  20414. // Push in arrays
  20415. positions.push(position.x, position.y, position.z);
  20416. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20417. }
  20418. }
  20419. subdivisions += 1;
  20420. for (var s = 0; s < subdivisions - 1; s++) {
  20421. for (var i = 0; i <= tessellation; i++) {
  20422. indices.push(i * subdivisions + s);
  20423. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20424. indices.push(i * subdivisions + (s + 1));
  20425. indices.push(i * subdivisions + (s + 1));
  20426. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  20427. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  20428. }
  20429. }
  20430. // Create flat triangle fan caps to seal the top and bottom.
  20431. createCylinderCap(true);
  20432. createCylinderCap(false);
  20433. // Normals
  20434. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20435. // Result
  20436. var vertexData = new BABYLON.VertexData();
  20437. vertexData.indices = indices;
  20438. vertexData.positions = positions;
  20439. vertexData.normals = normals;
  20440. vertexData.uvs = uvs;
  20441. return vertexData;
  20442. };
  20443. VertexData.CreateTorus = function (diameter, thickness, tessellation) {
  20444. var indices = [];
  20445. var positions = [];
  20446. var normals = [];
  20447. var uvs = [];
  20448. diameter = diameter || 1;
  20449. thickness = thickness || 0.5;
  20450. tessellation = tessellation || 16;
  20451. var stride = tessellation + 1;
  20452. for (var i = 0; i <= tessellation; i++) {
  20453. var u = i / tessellation;
  20454. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  20455. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  20456. for (var j = 0; j <= tessellation; j++) {
  20457. var v = 1 - j / tessellation;
  20458. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  20459. var dx = Math.cos(innerAngle);
  20460. var dy = Math.sin(innerAngle);
  20461. // Create a vertex.
  20462. var normal = new BABYLON.Vector3(dx, dy, 0);
  20463. var position = normal.scale(thickness / 2);
  20464. var textureCoordinate = new BABYLON.Vector2(u, v);
  20465. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  20466. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  20467. positions.push(position.x, position.y, position.z);
  20468. normals.push(normal.x, normal.y, normal.z);
  20469. uvs.push(textureCoordinate.x, textureCoordinate.y);
  20470. // And create indices for two triangles.
  20471. var nextI = (i + 1) % stride;
  20472. var nextJ = (j + 1) % stride;
  20473. indices.push(i * stride + j);
  20474. indices.push(i * stride + nextJ);
  20475. indices.push(nextI * stride + j);
  20476. indices.push(i * stride + nextJ);
  20477. indices.push(nextI * stride + nextJ);
  20478. indices.push(nextI * stride + j);
  20479. }
  20480. }
  20481. // Result
  20482. var vertexData = new BABYLON.VertexData();
  20483. vertexData.indices = indices;
  20484. vertexData.positions = positions;
  20485. vertexData.normals = normals;
  20486. vertexData.uvs = uvs;
  20487. return vertexData;
  20488. };
  20489. VertexData.CreateLines = function (points) {
  20490. var indices = [];
  20491. var positions = [];
  20492. for (var index = 0; index < points.length; index++) {
  20493. positions.push(points[index].x, points[index].y, points[index].z);
  20494. if (index > 0) {
  20495. indices.push(index - 1);
  20496. indices.push(index);
  20497. }
  20498. }
  20499. // Result
  20500. var vertexData = new BABYLON.VertexData();
  20501. vertexData.indices = indices;
  20502. vertexData.positions = positions;
  20503. return vertexData;
  20504. };
  20505. VertexData.CreateGround = function (width, height, subdivisions) {
  20506. var indices = [];
  20507. var positions = [];
  20508. var normals = [];
  20509. var uvs = [];
  20510. var row, col;
  20511. width = width || 1;
  20512. height = height || 1;
  20513. subdivisions = subdivisions || 1;
  20514. for (row = 0; row <= subdivisions; row++) {
  20515. for (col = 0; col <= subdivisions; col++) {
  20516. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20517. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20518. positions.push(position.x, position.y, position.z);
  20519. normals.push(normal.x, normal.y, normal.z);
  20520. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20521. }
  20522. }
  20523. for (row = 0; row < subdivisions; row++) {
  20524. for (col = 0; col < subdivisions; col++) {
  20525. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20526. indices.push(col + 1 + row * (subdivisions + 1));
  20527. indices.push(col + row * (subdivisions + 1));
  20528. indices.push(col + (row + 1) * (subdivisions + 1));
  20529. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20530. indices.push(col + row * (subdivisions + 1));
  20531. }
  20532. }
  20533. // Result
  20534. var vertexData = new BABYLON.VertexData();
  20535. vertexData.indices = indices;
  20536. vertexData.positions = positions;
  20537. vertexData.normals = normals;
  20538. vertexData.uvs = uvs;
  20539. return vertexData;
  20540. };
  20541. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  20542. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  20543. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  20544. var indices = [];
  20545. var positions = [];
  20546. var normals = [];
  20547. var uvs = [];
  20548. var row, col, tileRow, tileCol;
  20549. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  20550. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  20551. precision.w = (precision.w < 1) ? 1 : precision.w;
  20552. precision.h = (precision.h < 1) ? 1 : precision.h;
  20553. var tileSize = {
  20554. 'w': (xmax - xmin) / subdivisions.w,
  20555. 'h': (zmax - zmin) / subdivisions.h
  20556. };
  20557. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  20558. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  20559. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  20560. }
  20561. }
  20562. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  20563. // Indices
  20564. var base = positions.length / 3;
  20565. var rowLength = precision.w + 1;
  20566. for (row = 0; row < precision.h; row++) {
  20567. for (col = 0; col < precision.w; col++) {
  20568. var square = [
  20569. base + col + row * rowLength,
  20570. base + (col + 1) + row * rowLength,
  20571. base + (col + 1) + (row + 1) * rowLength,
  20572. base + col + (row + 1) * rowLength
  20573. ];
  20574. indices.push(square[1]);
  20575. indices.push(square[2]);
  20576. indices.push(square[3]);
  20577. indices.push(square[0]);
  20578. indices.push(square[1]);
  20579. indices.push(square[3]);
  20580. }
  20581. }
  20582. // Position, normals and uvs
  20583. var position = BABYLON.Vector3.Zero();
  20584. var normal = new BABYLON.Vector3(0, 1.0, 0);
  20585. for (row = 0; row <= precision.h; row++) {
  20586. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  20587. for (col = 0; col <= precision.w; col++) {
  20588. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  20589. position.y = 0;
  20590. positions.push(position.x, position.y, position.z);
  20591. normals.push(normal.x, normal.y, normal.z);
  20592. uvs.push(col / precision.w, row / precision.h);
  20593. }
  20594. }
  20595. }
  20596. // Result
  20597. var vertexData = new BABYLON.VertexData();
  20598. vertexData.indices = indices;
  20599. vertexData.positions = positions;
  20600. vertexData.normals = normals;
  20601. vertexData.uvs = uvs;
  20602. return vertexData;
  20603. };
  20604. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  20605. var indices = [];
  20606. var positions = [];
  20607. var normals = [];
  20608. var uvs = [];
  20609. var row, col;
  20610. for (row = 0; row <= subdivisions; row++) {
  20611. for (col = 0; col <= subdivisions; col++) {
  20612. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  20613. // Compute height
  20614. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  20615. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  20616. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  20617. var r = buffer[pos] / 255.0;
  20618. var g = buffer[pos + 1] / 255.0;
  20619. var b = buffer[pos + 2] / 255.0;
  20620. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20621. position.y = minHeight + (maxHeight - minHeight) * gradient;
  20622. // Add vertex
  20623. positions.push(position.x, position.y, position.z);
  20624. normals.push(0, 0, 0);
  20625. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  20626. }
  20627. }
  20628. for (row = 0; row < subdivisions; row++) {
  20629. for (col = 0; col < subdivisions; col++) {
  20630. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20631. indices.push(col + 1 + row * (subdivisions + 1));
  20632. indices.push(col + row * (subdivisions + 1));
  20633. indices.push(col + (row + 1) * (subdivisions + 1));
  20634. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  20635. indices.push(col + row * (subdivisions + 1));
  20636. }
  20637. }
  20638. // Normals
  20639. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20640. // Result
  20641. var vertexData = new BABYLON.VertexData();
  20642. vertexData.indices = indices;
  20643. vertexData.positions = positions;
  20644. vertexData.normals = normals;
  20645. vertexData.uvs = uvs;
  20646. return vertexData;
  20647. };
  20648. VertexData.CreatePlane = function (size) {
  20649. var indices = [];
  20650. var positions = [];
  20651. var normals = [];
  20652. var uvs = [];
  20653. size = size || 1;
  20654. // Vertices
  20655. var halfSize = size / 2.0;
  20656. positions.push(-halfSize, -halfSize, 0);
  20657. normals.push(0, 0, -1.0);
  20658. uvs.push(0.0, 0.0);
  20659. positions.push(halfSize, -halfSize, 0);
  20660. normals.push(0, 0, -1.0);
  20661. uvs.push(1.0, 0.0);
  20662. positions.push(halfSize, halfSize, 0);
  20663. normals.push(0, 0, -1.0);
  20664. uvs.push(1.0, 1.0);
  20665. positions.push(-halfSize, halfSize, 0);
  20666. normals.push(0, 0, -1.0);
  20667. uvs.push(0.0, 1.0);
  20668. // Indices
  20669. indices.push(0);
  20670. indices.push(1);
  20671. indices.push(2);
  20672. indices.push(0);
  20673. indices.push(2);
  20674. indices.push(3);
  20675. // Result
  20676. var vertexData = new BABYLON.VertexData();
  20677. vertexData.indices = indices;
  20678. vertexData.positions = positions;
  20679. vertexData.normals = normals;
  20680. vertexData.uvs = uvs;
  20681. return vertexData;
  20682. };
  20683. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  20684. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q) {
  20685. var indices = [];
  20686. var positions = [];
  20687. var normals = [];
  20688. var uvs = [];
  20689. radius = radius || 2;
  20690. tube = tube || 0.5;
  20691. radialSegments = radialSegments || 32;
  20692. tubularSegments = tubularSegments || 32;
  20693. p = p || 2;
  20694. q = q || 3;
  20695. // Helper
  20696. var getPos = function (angle) {
  20697. var cu = Math.cos(angle);
  20698. var su = Math.sin(angle);
  20699. var quOverP = q / p * angle;
  20700. var cs = Math.cos(quOverP);
  20701. var tx = radius * (2 + cs) * 0.5 * cu;
  20702. var ty = radius * (2 + cs) * su * 0.5;
  20703. var tz = radius * Math.sin(quOverP) * 0.5;
  20704. return new BABYLON.Vector3(tx, ty, tz);
  20705. };
  20706. for (var i = 0; i <= radialSegments; i++) {
  20707. var modI = i % radialSegments;
  20708. var u = modI / radialSegments * 2 * p * Math.PI;
  20709. var p1 = getPos(u);
  20710. var p2 = getPos(u + 0.01);
  20711. var tang = p2.subtract(p1);
  20712. var n = p2.add(p1);
  20713. var bitan = BABYLON.Vector3.Cross(tang, n);
  20714. n = BABYLON.Vector3.Cross(bitan, tang);
  20715. bitan.normalize();
  20716. n.normalize();
  20717. for (var j = 0; j < tubularSegments; j++) {
  20718. var modJ = j % tubularSegments;
  20719. var v = modJ / tubularSegments * 2 * Math.PI;
  20720. var cx = -tube * Math.cos(v);
  20721. var cy = tube * Math.sin(v);
  20722. positions.push(p1.x + cx * n.x + cy * bitan.x);
  20723. positions.push(p1.y + cx * n.y + cy * bitan.y);
  20724. positions.push(p1.z + cx * n.z + cy * bitan.z);
  20725. uvs.push(i / radialSegments);
  20726. uvs.push(j / tubularSegments);
  20727. }
  20728. }
  20729. for (i = 0; i < radialSegments; i++) {
  20730. for (j = 0; j < tubularSegments; j++) {
  20731. var jNext = (j + 1) % tubularSegments;
  20732. var a = i * tubularSegments + j;
  20733. var b = (i + 1) * tubularSegments + j;
  20734. var c = (i + 1) * tubularSegments + jNext;
  20735. var d = i * tubularSegments + jNext;
  20736. indices.push(d);
  20737. indices.push(b);
  20738. indices.push(a);
  20739. indices.push(d);
  20740. indices.push(c);
  20741. indices.push(b);
  20742. }
  20743. }
  20744. // Normals
  20745. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20746. // Result
  20747. var vertexData = new BABYLON.VertexData();
  20748. vertexData.indices = indices;
  20749. vertexData.positions = positions;
  20750. vertexData.normals = normals;
  20751. vertexData.uvs = uvs;
  20752. return vertexData;
  20753. };
  20754. // Tools
  20755. VertexData.ComputeNormals = function (positions, indices, normals) {
  20756. var positionVectors = [];
  20757. var facesOfVertices = [];
  20758. var index;
  20759. for (index = 0; index < positions.length; index += 3) {
  20760. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  20761. positionVectors.push(vector3);
  20762. facesOfVertices.push([]);
  20763. }
  20764. // Compute normals
  20765. var facesNormals = [];
  20766. for (index = 0; index < indices.length / 3; index++) {
  20767. var i1 = indices[index * 3];
  20768. var i2 = indices[index * 3 + 1];
  20769. var i3 = indices[index * 3 + 2];
  20770. var p1 = positionVectors[i1];
  20771. var p2 = positionVectors[i2];
  20772. var p3 = positionVectors[i3];
  20773. var p1p2 = p1.subtract(p2);
  20774. var p3p2 = p3.subtract(p2);
  20775. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20776. facesOfVertices[i1].push(index);
  20777. facesOfVertices[i2].push(index);
  20778. facesOfVertices[i3].push(index);
  20779. }
  20780. for (index = 0; index < positionVectors.length; index++) {
  20781. var faces = facesOfVertices[index];
  20782. var normal = BABYLON.Vector3.Zero();
  20783. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  20784. normal.addInPlace(facesNormals[faces[faceIndex]]);
  20785. }
  20786. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  20787. normals[index * 3] = normal.x;
  20788. normals[index * 3 + 1] = normal.y;
  20789. normals[index * 3 + 2] = normal.z;
  20790. }
  20791. };
  20792. return VertexData;
  20793. })();
  20794. BABYLON.VertexData = VertexData;
  20795. })(BABYLON || (BABYLON = {}));
  20796. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  20797. var BABYLON;
  20798. (function (BABYLON) {
  20799. var buildCamera = function (that, name) {
  20800. that._leftCamera.isIntermediate = true;
  20801. that.subCameras.push(that._leftCamera);
  20802. that.subCameras.push(that._rightCamera);
  20803. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  20804. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  20805. that._anaglyphPostProcess.onApply = function (effect) {
  20806. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  20807. };
  20808. that._update();
  20809. };
  20810. var AnaglyphArcRotateCamera = (function (_super) {
  20811. __extends(AnaglyphArcRotateCamera, _super);
  20812. // ANY
  20813. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  20814. _super.call(this, name, alpha, beta, radius, target, scene);
  20815. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20816. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  20817. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  20818. buildCamera(this, name);
  20819. }
  20820. AnaglyphArcRotateCamera.prototype._update = function () {
  20821. this._updateCamera(this._leftCamera);
  20822. this._updateCamera(this._rightCamera);
  20823. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  20824. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  20825. _super.prototype._update.call(this);
  20826. };
  20827. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  20828. camera.beta = this.beta;
  20829. camera.radius = this.radius;
  20830. camera.minZ = this.minZ;
  20831. camera.maxZ = this.maxZ;
  20832. camera.fov = this.fov;
  20833. camera.target = this.target;
  20834. };
  20835. return AnaglyphArcRotateCamera;
  20836. })(BABYLON.ArcRotateCamera);
  20837. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  20838. var AnaglyphFreeCamera = (function (_super) {
  20839. __extends(AnaglyphFreeCamera, _super);
  20840. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  20841. _super.call(this, name, position, scene);
  20842. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  20843. this._transformMatrix = new BABYLON.Matrix();
  20844. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  20845. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  20846. buildCamera(this, name);
  20847. }
  20848. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  20849. var target = this.getTarget();
  20850. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  20851. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  20852. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  20853. };
  20854. AnaglyphFreeCamera.prototype._update = function () {
  20855. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  20856. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  20857. this._updateCamera(this._leftCamera);
  20858. this._updateCamera(this._rightCamera);
  20859. _super.prototype._update.call(this);
  20860. };
  20861. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  20862. camera.minZ = this.minZ;
  20863. camera.maxZ = this.maxZ;
  20864. camera.fov = this.fov;
  20865. camera.viewport = this.viewport;
  20866. camera.setTarget(this.getTarget());
  20867. };
  20868. return AnaglyphFreeCamera;
  20869. })(BABYLON.FreeCamera);
  20870. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  20871. })(BABYLON || (BABYLON = {}));
  20872. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  20873. var BABYLON;
  20874. (function (BABYLON) {
  20875. var AnaglyphPostProcess = (function (_super) {
  20876. __extends(AnaglyphPostProcess, _super);
  20877. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  20878. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  20879. }
  20880. return AnaglyphPostProcess;
  20881. })(BABYLON.PostProcess);
  20882. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  20883. })(BABYLON || (BABYLON = {}));
  20884. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  20885. (function (BABYLON) {
  20886. var Tags = (function () {
  20887. function Tags() {
  20888. }
  20889. Tags.EnableFor = function (obj) {
  20890. obj._tags = obj._tags || {};
  20891. obj.hasTags = function () {
  20892. return Tags.HasTags(obj);
  20893. };
  20894. obj.addTags = function (tagsString) {
  20895. return Tags.AddTagsTo(obj, tagsString);
  20896. };
  20897. obj.removeTags = function (tagsString) {
  20898. return Tags.RemoveTagsFrom(obj, tagsString);
  20899. };
  20900. obj.matchesTagsQuery = function (tagsQuery) {
  20901. return Tags.MatchesQuery(obj, tagsQuery);
  20902. };
  20903. };
  20904. Tags.DisableFor = function (obj) {
  20905. delete obj._tags;
  20906. delete obj.hasTags;
  20907. delete obj.addTags;
  20908. delete obj.removeTags;
  20909. delete obj.matchesTagsQuery;
  20910. };
  20911. Tags.HasTags = function (obj) {
  20912. if (!obj._tags) {
  20913. return false;
  20914. }
  20915. return !BABYLON.Tools.IsEmpty(obj._tags);
  20916. };
  20917. Tags.GetTags = function (obj) {
  20918. if (!obj._tags) {
  20919. return null;
  20920. }
  20921. return obj._tags;
  20922. };
  20923. // the tags 'true' and 'false' are reserved and cannot be used as tags
  20924. // a tag cannot start with '||', '&&', and '!'
  20925. // it cannot contain whitespaces
  20926. Tags.AddTagsTo = function (obj, tagsString) {
  20927. if (!tagsString) {
  20928. return;
  20929. }
  20930. var tags = tagsString.split(" ");
  20931. for (var t in tags) {
  20932. Tags._AddTagTo(obj, tags[t]);
  20933. }
  20934. };
  20935. Tags._AddTagTo = function (obj, tag) {
  20936. tag = tag.trim();
  20937. if (tag === "" || tag === "true" || tag === "false") {
  20938. return;
  20939. }
  20940. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  20941. return;
  20942. }
  20943. Tags.EnableFor(obj);
  20944. obj._tags[tag] = true;
  20945. };
  20946. Tags.RemoveTagsFrom = function (obj, tagsString) {
  20947. if (!Tags.HasTags(obj)) {
  20948. return;
  20949. }
  20950. var tags = tagsString.split(" ");
  20951. for (var t in tags) {
  20952. Tags._RemoveTagFrom(obj, tags[t]);
  20953. }
  20954. };
  20955. Tags._RemoveTagFrom = function (obj, tag) {
  20956. delete obj._tags[tag];
  20957. };
  20958. Tags.MatchesQuery = function (obj, tagsQuery) {
  20959. if (tagsQuery === undefined) {
  20960. return true;
  20961. }
  20962. if (tagsQuery === "") {
  20963. return Tags.HasTags(obj);
  20964. }
  20965. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  20966. };
  20967. return Tags;
  20968. })();
  20969. BABYLON.Tags = Tags;
  20970. })(BABYLON || (BABYLON = {}));
  20971. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  20972. (function (BABYLON) {
  20973. var Internals;
  20974. (function (Internals) {
  20975. var AndOrNotEvaluator = (function () {
  20976. function AndOrNotEvaluator() {
  20977. }
  20978. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  20979. if (!query.match(/\([^\(\)]*\)/g)) {
  20980. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  20981. }
  20982. else {
  20983. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  20984. // remove parenthesis
  20985. r = r.slice(1, r.length - 1);
  20986. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  20987. });
  20988. }
  20989. if (query === "true") {
  20990. return true;
  20991. }
  20992. if (query === "false") {
  20993. return false;
  20994. }
  20995. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  20996. };
  20997. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  20998. evaluateCallback = evaluateCallback || (function (r) {
  20999. return r === "true" ? true : false;
  21000. });
  21001. var result;
  21002. var or = parenthesisContent.split("||");
  21003. for (var i in or) {
  21004. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  21005. var and = ori.split("&&");
  21006. if (and.length > 1) {
  21007. for (var j = 0; j < and.length; ++j) {
  21008. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  21009. if (andj !== "true" && andj !== "false") {
  21010. if (andj[0] === "!") {
  21011. result = !evaluateCallback(andj.substring(1));
  21012. }
  21013. else {
  21014. result = evaluateCallback(andj);
  21015. }
  21016. }
  21017. else {
  21018. result = andj === "true" ? true : false;
  21019. }
  21020. if (!result) {
  21021. ori = "false";
  21022. break;
  21023. }
  21024. }
  21025. }
  21026. if (result || ori === "true") {
  21027. result = true;
  21028. break;
  21029. }
  21030. // result equals false (or undefined)
  21031. if (ori !== "true" && ori !== "false") {
  21032. if (ori[0] === "!") {
  21033. result = !evaluateCallback(ori.substring(1));
  21034. }
  21035. else {
  21036. result = evaluateCallback(ori);
  21037. }
  21038. }
  21039. else {
  21040. result = ori === "true" ? true : false;
  21041. }
  21042. }
  21043. // the whole parenthesis scope is replaced by 'true' or 'false'
  21044. return result ? "true" : "false";
  21045. };
  21046. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  21047. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  21048. // remove whitespaces
  21049. r = r.replace(/[\s]/g, function () { return ""; });
  21050. return r.length % 2 ? "!" : "";
  21051. });
  21052. booleanString = booleanString.trim();
  21053. if (booleanString === "!true") {
  21054. booleanString = "false";
  21055. }
  21056. else if (booleanString === "!false") {
  21057. booleanString = "true";
  21058. }
  21059. return booleanString;
  21060. };
  21061. return AndOrNotEvaluator;
  21062. })();
  21063. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  21064. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21065. })(BABYLON || (BABYLON = {}));
  21066. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  21067. (function (BABYLON) {
  21068. var PostProcessRenderPass = (function () {
  21069. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  21070. this._enabled = true;
  21071. this._refCount = 0;
  21072. this._name = name;
  21073. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  21074. this.setRenderList(renderList);
  21075. this._renderTexture.onBeforeRender = beforeRender;
  21076. this._renderTexture.onAfterRender = afterRender;
  21077. this._scene = scene;
  21078. this._renderList = renderList;
  21079. }
  21080. // private
  21081. PostProcessRenderPass.prototype._incRefCount = function () {
  21082. if (this._refCount === 0) {
  21083. this._scene.customRenderTargets.push(this._renderTexture);
  21084. }
  21085. return ++this._refCount;
  21086. };
  21087. PostProcessRenderPass.prototype._decRefCount = function () {
  21088. this._refCount--;
  21089. if (this._refCount <= 0) {
  21090. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  21091. }
  21092. return this._refCount;
  21093. };
  21094. PostProcessRenderPass.prototype._update = function () {
  21095. this.setRenderList(this._renderList);
  21096. };
  21097. // public
  21098. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  21099. this._renderTexture.renderList = renderList;
  21100. };
  21101. PostProcessRenderPass.prototype.getRenderTexture = function () {
  21102. return this._renderTexture;
  21103. };
  21104. return PostProcessRenderPass;
  21105. })();
  21106. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  21107. })(BABYLON || (BABYLON = {}));
  21108. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  21109. (function (BABYLON) {
  21110. var PostProcessRenderEffect = (function () {
  21111. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  21112. this._engine = engine;
  21113. this._name = name;
  21114. this._singleInstance = singleInstance || true;
  21115. this._getPostProcess = getPostProcess;
  21116. this._cameras = [];
  21117. this._indicesForCamera = [];
  21118. this._postProcesses = {};
  21119. this._renderPasses = {};
  21120. this._renderEffectAsPasses = {};
  21121. }
  21122. PostProcessRenderEffect.prototype._update = function () {
  21123. for (var renderPassName in this._renderPasses) {
  21124. this._renderPasses[renderPassName]._update();
  21125. }
  21126. };
  21127. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  21128. this._renderPasses[renderPass._name] = renderPass;
  21129. this._linkParameters();
  21130. };
  21131. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  21132. delete this._renderPasses[renderPass._name];
  21133. this._linkParameters();
  21134. };
  21135. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  21136. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  21137. this._linkParameters();
  21138. };
  21139. PostProcessRenderEffect.prototype.getPass = function (passName) {
  21140. for (var renderPassName in this._renderPasses) {
  21141. if (renderPassName === passName) {
  21142. return this._renderPasses[passName];
  21143. }
  21144. }
  21145. };
  21146. PostProcessRenderEffect.prototype.emptyPasses = function () {
  21147. this._renderPasses = {};
  21148. this._linkParameters();
  21149. };
  21150. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  21151. var cameraKey;
  21152. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21153. for (var i = 0; i < _cam.length; i++) {
  21154. var camera = _cam[i];
  21155. var cameraName = camera.name;
  21156. if (this._singleInstance) {
  21157. cameraKey = 0;
  21158. }
  21159. else {
  21160. cameraKey = cameraName;
  21161. }
  21162. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  21163. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  21164. if (!this._indicesForCamera[cameraName]) {
  21165. this._indicesForCamera[cameraName] = [];
  21166. }
  21167. this._indicesForCamera[cameraName].push(index);
  21168. if (this._cameras.indexOf(camera) === -1) {
  21169. this._cameras[cameraName] = camera;
  21170. }
  21171. for (var passName in this._renderPasses) {
  21172. this._renderPasses[passName]._incRefCount();
  21173. }
  21174. }
  21175. this._linkParameters();
  21176. };
  21177. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  21178. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21179. for (var i = 0; i < _cam.length; i++) {
  21180. var camera = _cam[i];
  21181. var cameraName = camera.name;
  21182. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21183. var index = this._cameras.indexOf(cameraName);
  21184. this._indicesForCamera.splice(index, 1);
  21185. this._cameras.splice(index, 1);
  21186. for (var passName in this._renderPasses) {
  21187. this._renderPasses[passName]._decRefCount();
  21188. }
  21189. }
  21190. };
  21191. PostProcessRenderEffect.prototype._enable = function (cameras) {
  21192. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21193. for (var i = 0; i < _cam.length; i++) {
  21194. var camera = _cam[i];
  21195. var cameraName = camera.name;
  21196. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  21197. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  21198. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  21199. }
  21200. }
  21201. for (var passName in this._renderPasses) {
  21202. this._renderPasses[passName]._incRefCount();
  21203. }
  21204. }
  21205. };
  21206. PostProcessRenderEffect.prototype._disable = function (cameras) {
  21207. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21208. for (var i = 0; i < _cam.length; i++) {
  21209. var camera = _cam[i];
  21210. var cameraName = camera.Name;
  21211. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  21212. for (var passName in this._renderPasses) {
  21213. this._renderPasses[passName]._decRefCount();
  21214. }
  21215. }
  21216. };
  21217. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  21218. if (this._singleInstance) {
  21219. return this._postProcesses[0];
  21220. }
  21221. else {
  21222. return this._postProcesses[camera.name];
  21223. }
  21224. };
  21225. PostProcessRenderEffect.prototype._linkParameters = function () {
  21226. var _this = this;
  21227. for (var index in this._postProcesses) {
  21228. if (this.applyParameters) {
  21229. this.applyParameters(this._postProcesses[index]);
  21230. }
  21231. this._postProcesses[index].onBeforeRender = function (effect) {
  21232. _this._linkTextures(effect);
  21233. };
  21234. }
  21235. };
  21236. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  21237. for (var renderPassName in this._renderPasses) {
  21238. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  21239. }
  21240. for (var renderEffectName in this._renderEffectAsPasses) {
  21241. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  21242. }
  21243. };
  21244. return PostProcessRenderEffect;
  21245. })();
  21246. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  21247. })(BABYLON || (BABYLON = {}));
  21248. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  21249. (function (BABYLON) {
  21250. var PostProcessRenderPipeline = (function () {
  21251. function PostProcessRenderPipeline(engine, name) {
  21252. this._engine = engine;
  21253. this._name = name;
  21254. this._renderEffects = {};
  21255. this._renderEffectsForIsolatedPass = {};
  21256. this._cameras = [];
  21257. }
  21258. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  21259. this._renderEffects[renderEffect._name] = renderEffect;
  21260. };
  21261. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  21262. var renderEffects = this._renderEffects[renderEffectName];
  21263. if (!renderEffects) {
  21264. return;
  21265. }
  21266. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21267. };
  21268. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  21269. var renderEffects = this._renderEffects[renderEffectName];
  21270. if (!renderEffects) {
  21271. return;
  21272. }
  21273. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  21274. };
  21275. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  21276. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21277. var indicesToDelete = [];
  21278. for (var i = 0; i < _cam.length; i++) {
  21279. var camera = _cam[i];
  21280. var cameraName = camera.name;
  21281. if (this._cameras.indexOf(camera) === -1) {
  21282. this._cameras[cameraName] = camera;
  21283. }
  21284. else if (unique) {
  21285. indicesToDelete.push(i);
  21286. }
  21287. }
  21288. for (var i = 0; i < indicesToDelete.length; i++) {
  21289. cameras.splice(indicesToDelete[i], 1);
  21290. }
  21291. for (var renderEffectName in this._renderEffects) {
  21292. this._renderEffects[renderEffectName]._attachCameras(_cam);
  21293. }
  21294. };
  21295. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  21296. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21297. for (var renderEffectName in this._renderEffects) {
  21298. this._renderEffects[renderEffectName]._detachCameras(_cam);
  21299. }
  21300. for (var i = 0; i < _cam.length; i++) {
  21301. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  21302. }
  21303. };
  21304. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  21305. var _this = this;
  21306. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21307. var pass = null;
  21308. for (var renderEffectName in this._renderEffects) {
  21309. pass = this._renderEffects[renderEffectName].getPass(passName);
  21310. if (pass != null) {
  21311. break;
  21312. }
  21313. }
  21314. if (pass === null) {
  21315. return;
  21316. }
  21317. for (var renderEffectName in this._renderEffects) {
  21318. this._renderEffects[renderEffectName]._disable(_cam);
  21319. }
  21320. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  21321. for (var i = 0; i < _cam.length; i++) {
  21322. var camera = _cam[i];
  21323. var cameraName = camera.name;
  21324. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21325. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21326. });
  21327. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  21328. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  21329. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  21330. }
  21331. };
  21332. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  21333. var _this = this;
  21334. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  21335. for (var i = 0; i < _cam.length; i++) {
  21336. var camera = _cam[i];
  21337. var cameraName = camera.name;
  21338. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  21339. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  21340. });
  21341. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  21342. }
  21343. for (var renderEffectName in this._renderEffects) {
  21344. this._renderEffects[renderEffectName]._enable(_cam);
  21345. }
  21346. };
  21347. PostProcessRenderPipeline.prototype._update = function () {
  21348. for (var renderEffectName in this._renderEffects) {
  21349. this._renderEffects[renderEffectName]._update();
  21350. }
  21351. for (var i = 0; i < this._cameras.length; i++) {
  21352. var cameraName = this._cameras[i].name;
  21353. if (this._renderEffectsForIsolatedPass[cameraName]) {
  21354. this._renderEffectsForIsolatedPass[cameraName]._update();
  21355. }
  21356. }
  21357. };
  21358. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  21359. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  21360. return PostProcessRenderPipeline;
  21361. })();
  21362. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  21363. })(BABYLON || (BABYLON = {}));
  21364. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  21365. (function (BABYLON) {
  21366. var PostProcessRenderPipelineManager = (function () {
  21367. function PostProcessRenderPipelineManager() {
  21368. this._renderPipelines = {};
  21369. }
  21370. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  21371. this._renderPipelines[renderPipeline._name] = renderPipeline;
  21372. };
  21373. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  21374. var renderPipeline = this._renderPipelines[renderPipelineName];
  21375. if (!renderPipeline) {
  21376. return;
  21377. }
  21378. renderPipeline._attachCameras(cameras, unique);
  21379. };
  21380. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  21381. var renderPipeline = this._renderPipelines[renderPipelineName];
  21382. if (!renderPipeline) {
  21383. return;
  21384. }
  21385. renderPipeline._detachCameras(cameras);
  21386. };
  21387. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21388. var renderPipeline = this._renderPipelines[renderPipelineName];
  21389. if (!renderPipeline) {
  21390. return;
  21391. }
  21392. renderPipeline._enableEffect(renderEffectName, cameras);
  21393. };
  21394. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  21395. var renderPipeline = this._renderPipelines[renderPipelineName];
  21396. if (!renderPipeline) {
  21397. return;
  21398. }
  21399. renderPipeline._disableEffect(renderEffectName, cameras);
  21400. };
  21401. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  21402. var renderPipeline = this._renderPipelines[renderPipelineName];
  21403. if (!renderPipeline) {
  21404. return;
  21405. }
  21406. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  21407. };
  21408. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  21409. var renderPipeline = this._renderPipelines[renderPipelineName];
  21410. if (!renderPipeline) {
  21411. return;
  21412. }
  21413. renderPipeline._disableDisplayOnlyPass(cameras);
  21414. };
  21415. PostProcessRenderPipelineManager.prototype.update = function () {
  21416. for (var renderPipelineName in this._renderPipelines) {
  21417. this._renderPipelines[renderPipelineName]._update();
  21418. }
  21419. };
  21420. return PostProcessRenderPipelineManager;
  21421. })();
  21422. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  21423. })(BABYLON || (BABYLON = {}));
  21424. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  21425. var BABYLON;
  21426. (function (BABYLON) {
  21427. var DisplayPassPostProcess = (function (_super) {
  21428. __extends(DisplayPassPostProcess, _super);
  21429. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  21430. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  21431. }
  21432. return DisplayPassPostProcess;
  21433. })(BABYLON.PostProcess);
  21434. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  21435. })(BABYLON || (BABYLON = {}));
  21436. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  21437. (function (BABYLON) {
  21438. var BoundingBoxRenderer = (function () {
  21439. function BoundingBoxRenderer(scene) {
  21440. this.frontColor = new BABYLON.Color3(1, 1, 1);
  21441. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  21442. this.showBackLines = true;
  21443. this.renderList = new BABYLON.SmartArray(32);
  21444. this._scene = scene;
  21445. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  21446. attributes: ["position"],
  21447. uniforms: ["worldViewProjection", "color"]
  21448. });
  21449. var engine = this._scene.getEngine();
  21450. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  21451. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  21452. 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]);
  21453. }
  21454. BoundingBoxRenderer.prototype.reset = function () {
  21455. this.renderList.reset();
  21456. };
  21457. BoundingBoxRenderer.prototype.render = function () {
  21458. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  21459. return;
  21460. }
  21461. var engine = this._scene.getEngine();
  21462. engine.setDepthWrite(false);
  21463. this._colorShader._preBind();
  21464. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  21465. var boundingBox = this.renderList.data[boundingBoxIndex];
  21466. var min = boundingBox.minimum;
  21467. var max = boundingBox.maximum;
  21468. var diff = max.subtract(min);
  21469. var median = min.add(diff.scale(0.5));
  21470. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  21471. // VBOs
  21472. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  21473. if (this.showBackLines) {
  21474. // Back
  21475. engine.setDepthFunctionToGreaterOrEqual();
  21476. this._scene.resetCachedMaterial();
  21477. this._colorShader.setColor4("color", this.backColor.toColor4());
  21478. this._colorShader.bind(worldMatrix);
  21479. // Draw order
  21480. engine.draw(false, 0, 24);
  21481. }
  21482. // Front
  21483. engine.setDepthFunctionToLess();
  21484. this._scene.resetCachedMaterial();
  21485. this._colorShader.setColor4("color", this.frontColor.toColor4());
  21486. this._colorShader.bind(worldMatrix);
  21487. // Draw order
  21488. engine.draw(false, 0, 24);
  21489. }
  21490. this._colorShader.unbind();
  21491. engine.setDepthFunctionToLessOrEqual();
  21492. engine.setDepthWrite(true);
  21493. };
  21494. BoundingBoxRenderer.prototype.dispose = function () {
  21495. this._colorShader.dispose();
  21496. this._vb.dispose();
  21497. this._scene.getEngine()._releaseBuffer(this._ib);
  21498. };
  21499. return BoundingBoxRenderer;
  21500. })();
  21501. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  21502. })(BABYLON || (BABYLON = {}));
  21503. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  21504. (function (BABYLON) {
  21505. var Internals;
  21506. (function (Internals) {
  21507. /*
  21508. * Based on jsTGALoader - Javascript loader for TGA file
  21509. * By Vincent Thibault
  21510. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  21511. */
  21512. var TGATools = (function () {
  21513. function TGATools() {
  21514. }
  21515. TGATools.GetTGAHeader = function (data) {
  21516. var offset = 0;
  21517. var header = {
  21518. id_length: data[offset++],
  21519. colormap_type: data[offset++],
  21520. image_type: data[offset++],
  21521. colormap_index: data[offset++] | data[offset++] << 8,
  21522. colormap_length: data[offset++] | data[offset++] << 8,
  21523. colormap_size: data[offset++],
  21524. origin: [
  21525. data[offset++] | data[offset++] << 8,
  21526. data[offset++] | data[offset++] << 8
  21527. ],
  21528. width: data[offset++] | data[offset++] << 8,
  21529. height: data[offset++] | data[offset++] << 8,
  21530. pixel_size: data[offset++],
  21531. flags: data[offset++]
  21532. };
  21533. return header;
  21534. };
  21535. TGATools.UploadContent = function (gl, data) {
  21536. // Not enough data to contain header ?
  21537. if (data.length < 19) {
  21538. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  21539. return;
  21540. }
  21541. // Read Header
  21542. var offset = 18;
  21543. var header = TGATools.GetTGAHeader(data);
  21544. // Assume it's a valid Targa file.
  21545. if (header.id_length + offset > data.length) {
  21546. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  21547. return;
  21548. }
  21549. // Skip not needed data
  21550. offset += header.id_length;
  21551. var use_rle = false;
  21552. var use_pal = false;
  21553. var use_rgb = false;
  21554. var use_grey = false;
  21555. switch (header.image_type) {
  21556. case TGATools._TYPE_RLE_INDEXED:
  21557. use_rle = true;
  21558. case TGATools._TYPE_INDEXED:
  21559. use_pal = true;
  21560. break;
  21561. case TGATools._TYPE_RLE_RGB:
  21562. use_rle = true;
  21563. case TGATools._TYPE_RGB:
  21564. use_rgb = true;
  21565. break;
  21566. case TGATools._TYPE_RLE_GREY:
  21567. use_rle = true;
  21568. case TGATools._TYPE_GREY:
  21569. use_grey = true;
  21570. break;
  21571. }
  21572. var pixel_data;
  21573. var numAlphaBits = header.flags & 0xf;
  21574. var pixel_size = header.pixel_size >> 3;
  21575. var pixel_total = header.width * header.height * pixel_size;
  21576. // Read palettes
  21577. var palettes;
  21578. if (use_pal) {
  21579. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  21580. }
  21581. // Read LRE
  21582. if (use_rle) {
  21583. pixel_data = new Uint8Array(pixel_total);
  21584. var c, count, i;
  21585. var localOffset = 0;
  21586. var pixels = new Uint8Array(pixel_size);
  21587. while (offset < pixel_total && localOffset < pixel_total) {
  21588. c = data[offset++];
  21589. count = (c & 0x7f) + 1;
  21590. // RLE pixels
  21591. if (c & 0x80) {
  21592. for (i = 0; i < pixel_size; ++i) {
  21593. pixels[i] = data[offset++];
  21594. }
  21595. for (i = 0; i < count; ++i) {
  21596. pixel_data.set(pixels, localOffset + i * pixel_size);
  21597. }
  21598. localOffset += pixel_size * count;
  21599. }
  21600. else {
  21601. count *= pixel_size;
  21602. for (i = 0; i < count; ++i) {
  21603. pixel_data[localOffset + i] = data[offset++];
  21604. }
  21605. localOffset += count;
  21606. }
  21607. }
  21608. }
  21609. else {
  21610. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  21611. }
  21612. // Load to texture
  21613. var x_start, y_start, x_step, y_step, y_end, x_end;
  21614. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  21615. default:
  21616. case TGATools._ORIGIN_UL:
  21617. x_start = 0;
  21618. x_step = 1;
  21619. x_end = header.width;
  21620. y_start = 0;
  21621. y_step = 1;
  21622. y_end = header.height;
  21623. break;
  21624. case TGATools._ORIGIN_BL:
  21625. x_start = 0;
  21626. x_step = 1;
  21627. x_end = header.width;
  21628. y_start = header.height - 1;
  21629. y_step = -1;
  21630. y_end = -1;
  21631. break;
  21632. case TGATools._ORIGIN_UR:
  21633. x_start = header.width - 1;
  21634. x_step = -1;
  21635. x_end = -1;
  21636. y_start = 0;
  21637. y_step = 1;
  21638. y_end = header.height;
  21639. break;
  21640. case TGATools._ORIGIN_BR:
  21641. x_start = header.width - 1;
  21642. x_step = -1;
  21643. x_end = -1;
  21644. y_start = header.height - 1;
  21645. y_step = -1;
  21646. y_end = -1;
  21647. break;
  21648. }
  21649. // Load the specify method
  21650. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  21651. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  21652. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  21653. };
  21654. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21655. var image = pixel_data, colormap = palettes;
  21656. var width = header.width, height = header.height;
  21657. var color, i = 0, x, y;
  21658. var imageData = new Uint8Array(width * height * 4);
  21659. for (y = y_start; y !== y_end; y += y_step) {
  21660. for (x = x_start; x !== x_end; x += x_step, i++) {
  21661. color = image[i];
  21662. imageData[(x + width * y) * 4 + 3] = 255;
  21663. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  21664. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  21665. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  21666. }
  21667. }
  21668. return imageData;
  21669. };
  21670. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21671. var image = pixel_data;
  21672. var width = header.width, height = header.height;
  21673. var color, i = 0, x, y;
  21674. var imageData = new Uint8Array(width * height * 4);
  21675. for (y = y_start; y !== y_end; y += y_step) {
  21676. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21677. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  21678. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  21679. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  21680. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  21681. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  21682. }
  21683. }
  21684. return imageData;
  21685. };
  21686. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21687. var image = pixel_data;
  21688. var width = header.width, height = header.height;
  21689. var i = 0, x, y;
  21690. var imageData = new Uint8Array(width * height * 4);
  21691. for (y = y_start; y !== y_end; y += y_step) {
  21692. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  21693. imageData[(x + width * y) * 4 + 3] = 255;
  21694. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21695. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21696. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21697. }
  21698. }
  21699. return imageData;
  21700. };
  21701. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21702. var image = pixel_data;
  21703. var width = header.width, height = header.height;
  21704. var i = 0, x, y;
  21705. var imageData = new Uint8Array(width * height * 4);
  21706. for (y = y_start; y !== y_end; y += y_step) {
  21707. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  21708. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21709. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  21710. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  21711. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  21712. }
  21713. }
  21714. return imageData;
  21715. };
  21716. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21717. var image = pixel_data;
  21718. var width = header.width, height = header.height;
  21719. var color, i = 0, x, y;
  21720. var imageData = new Uint8Array(width * height * 4);
  21721. for (y = y_start; y !== y_end; y += y_step) {
  21722. for (x = x_start; x !== x_end; x += x_step, i++) {
  21723. color = image[i];
  21724. imageData[(x + width * y) * 4 + 0] = color;
  21725. imageData[(x + width * y) * 4 + 1] = color;
  21726. imageData[(x + width * y) * 4 + 2] = color;
  21727. imageData[(x + width * y) * 4 + 3] = 255;
  21728. }
  21729. }
  21730. return imageData;
  21731. };
  21732. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  21733. var image = pixel_data;
  21734. var width = header.width, height = header.height;
  21735. var i = 0, x, y;
  21736. var imageData = new Uint8Array(width * height * 4);
  21737. for (y = y_start; y !== y_end; y += y_step) {
  21738. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  21739. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  21740. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  21741. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  21742. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  21743. }
  21744. }
  21745. return imageData;
  21746. };
  21747. TGATools._TYPE_NO_DATA = 0;
  21748. TGATools._TYPE_INDEXED = 1;
  21749. TGATools._TYPE_RGB = 2;
  21750. TGATools._TYPE_GREY = 3;
  21751. TGATools._TYPE_RLE_INDEXED = 9;
  21752. TGATools._TYPE_RLE_RGB = 10;
  21753. TGATools._TYPE_RLE_GREY = 11;
  21754. TGATools._ORIGIN_MASK = 0x30;
  21755. TGATools._ORIGIN_SHIFT = 0x04;
  21756. TGATools._ORIGIN_BL = 0x00;
  21757. TGATools._ORIGIN_BR = 0x01;
  21758. TGATools._ORIGIN_UL = 0x02;
  21759. TGATools._ORIGIN_UR = 0x03;
  21760. return TGATools;
  21761. })();
  21762. Internals.TGATools = TGATools;
  21763. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21764. })(BABYLON || (BABYLON = {}));
  21765. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  21766. (function (BABYLON) {
  21767. var Internals;
  21768. (function (Internals) {
  21769. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  21770. // All values and structures referenced from:
  21771. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  21772. var DDS_MAGIC = 0x20534444;
  21773. 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;
  21774. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  21775. 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;
  21776. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  21777. function FourCCToInt32(value) {
  21778. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  21779. }
  21780. function Int32ToFourCC(value) {
  21781. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  21782. }
  21783. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  21784. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  21785. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  21786. var headerLengthInt = 31; // The header length in 32 bit ints
  21787. // Offsets into the header array
  21788. var off_magic = 0;
  21789. var off_size = 1;
  21790. var off_flags = 2;
  21791. var off_height = 3;
  21792. var off_width = 4;
  21793. var off_mipmapCount = 7;
  21794. var off_pfFlags = 20;
  21795. var off_pfFourCC = 21;
  21796. var off_RGBbpp = 22;
  21797. var off_RMask = 23;
  21798. var off_GMask = 24;
  21799. var off_BMask = 25;
  21800. var off_AMask = 26;
  21801. var off_caps1 = 27;
  21802. var off_caps2 = 28;
  21803. ;
  21804. var DDSTools = (function () {
  21805. function DDSTools() {
  21806. }
  21807. DDSTools.GetDDSInfo = function (arrayBuffer) {
  21808. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  21809. var mipmapCount = 1;
  21810. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  21811. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21812. }
  21813. return {
  21814. width: header[off_width],
  21815. height: header[off_height],
  21816. mipmapCount: mipmapCount,
  21817. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  21818. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  21819. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  21820. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  21821. };
  21822. };
  21823. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21824. var byteArray = new Uint8Array(dataLength);
  21825. var srcData = new Uint8Array(arrayBuffer);
  21826. var index = 0;
  21827. for (var y = height - 1; y >= 0; y--) {
  21828. for (var x = 0; x < width; x++) {
  21829. var srcPos = dataOffset + (x + y * width) * 4;
  21830. byteArray[index + 2] = srcData[srcPos];
  21831. byteArray[index + 1] = srcData[srcPos + 1];
  21832. byteArray[index] = srcData[srcPos + 2];
  21833. byteArray[index + 3] = srcData[srcPos + 3];
  21834. index += 4;
  21835. }
  21836. }
  21837. return byteArray;
  21838. };
  21839. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21840. var byteArray = new Uint8Array(dataLength);
  21841. var srcData = new Uint8Array(arrayBuffer);
  21842. var index = 0;
  21843. for (var y = height - 1; y >= 0; y--) {
  21844. for (var x = 0; x < width; x++) {
  21845. var srcPos = dataOffset + (x + y * width) * 3;
  21846. byteArray[index + 2] = srcData[srcPos];
  21847. byteArray[index + 1] = srcData[srcPos + 1];
  21848. byteArray[index] = srcData[srcPos + 2];
  21849. index += 3;
  21850. }
  21851. }
  21852. return byteArray;
  21853. };
  21854. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  21855. var byteArray = new Uint8Array(dataLength);
  21856. var srcData = new Uint8Array(arrayBuffer);
  21857. var index = 0;
  21858. for (var y = height - 1; y >= 0; y--) {
  21859. for (var x = 0; x < width; x++) {
  21860. var srcPos = dataOffset + (x + y * width);
  21861. byteArray[index] = srcData[srcPos];
  21862. index++;
  21863. }
  21864. }
  21865. return byteArray;
  21866. };
  21867. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  21868. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  21869. if (header[off_magic] != DDS_MAGIC) {
  21870. BABYLON.Tools.Error("Invalid magic number in DDS header");
  21871. return;
  21872. }
  21873. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  21874. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  21875. return;
  21876. }
  21877. if (info.isFourCC) {
  21878. fourCC = header[off_pfFourCC];
  21879. switch (fourCC) {
  21880. case FOURCC_DXT1:
  21881. blockBytes = 8;
  21882. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  21883. break;
  21884. case FOURCC_DXT3:
  21885. blockBytes = 16;
  21886. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  21887. break;
  21888. case FOURCC_DXT5:
  21889. blockBytes = 16;
  21890. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  21891. break;
  21892. default:
  21893. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  21894. return;
  21895. }
  21896. }
  21897. mipmapCount = 1;
  21898. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  21899. mipmapCount = Math.max(1, header[off_mipmapCount]);
  21900. }
  21901. var bpp = header[off_RGBbpp];
  21902. for (var face = 0; face < faces; face++) {
  21903. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  21904. width = header[off_width];
  21905. height = header[off_height];
  21906. dataOffset = header[off_size] + 4;
  21907. for (i = 0; i < mipmapCount; ++i) {
  21908. if (info.isRGB) {
  21909. if (bpp == 24) {
  21910. dataLength = width * height * 3;
  21911. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21912. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  21913. }
  21914. else {
  21915. dataLength = width * height * 4;
  21916. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21917. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  21918. }
  21919. }
  21920. else if (info.isLuminance) {
  21921. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  21922. var unpaddedRowSize = width;
  21923. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  21924. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  21925. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  21926. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  21927. }
  21928. else {
  21929. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  21930. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  21931. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  21932. }
  21933. dataOffset += dataLength;
  21934. width *= 0.5;
  21935. height *= 0.5;
  21936. width = Math.max(1.0, width);
  21937. height = Math.max(1.0, height);
  21938. }
  21939. }
  21940. };
  21941. return DDSTools;
  21942. })();
  21943. Internals.DDSTools = DDSTools;
  21944. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  21945. })(BABYLON || (BABYLON = {}));
  21946. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  21947. (function (BABYLON) {
  21948. var SmartArray = (function () {
  21949. function SmartArray(capacity) {
  21950. this.length = 0;
  21951. this._duplicateId = 0;
  21952. this.data = new Array(capacity);
  21953. this._id = SmartArray._GlobalId++;
  21954. }
  21955. SmartArray.prototype.push = function (value) {
  21956. this.data[this.length++] = value;
  21957. if (this.length > this.data.length) {
  21958. this.data.length *= 2;
  21959. }
  21960. if (!value.__smartArrayFlags) {
  21961. value.__smartArrayFlags = {};
  21962. }
  21963. value.__smartArrayFlags[this._id] = this._duplicateId;
  21964. };
  21965. SmartArray.prototype.pushNoDuplicate = function (value) {
  21966. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  21967. return;
  21968. }
  21969. this.push(value);
  21970. };
  21971. SmartArray.prototype.sort = function (compareFn) {
  21972. this.data.sort(compareFn);
  21973. };
  21974. SmartArray.prototype.reset = function () {
  21975. this.length = 0;
  21976. this._duplicateId++;
  21977. };
  21978. SmartArray.prototype.concat = function (array) {
  21979. if (array.length === 0) {
  21980. return;
  21981. }
  21982. if (this.length + array.length > this.data.length) {
  21983. this.data.length = (this.length + array.length) * 2;
  21984. }
  21985. for (var index = 0; index < array.length; index++) {
  21986. this.data[this.length++] = (array.data || array)[index];
  21987. }
  21988. };
  21989. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  21990. if (array.length === 0) {
  21991. return;
  21992. }
  21993. if (this.length + array.length > this.data.length) {
  21994. this.data.length = (this.length + array.length) * 2;
  21995. }
  21996. for (var index = 0; index < array.length; index++) {
  21997. var item = (array.data || array)[index];
  21998. this.pushNoDuplicate(item);
  21999. }
  22000. };
  22001. SmartArray.prototype.indexOf = function (value) {
  22002. var position = this.data.indexOf(value);
  22003. if (position >= this.length) {
  22004. return -1;
  22005. }
  22006. return position;
  22007. };
  22008. // Statics
  22009. SmartArray._GlobalId = 0;
  22010. return SmartArray;
  22011. })();
  22012. BABYLON.SmartArray = SmartArray;
  22013. })(BABYLON || (BABYLON = {}));
  22014. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  22015. (function (BABYLON) {
  22016. var CannonJSPlugin = (function () {
  22017. function CannonJSPlugin() {
  22018. this._registeredMeshes = [];
  22019. this._physicsMaterials = [];
  22020. this.updateBodyPosition = function (mesh) {
  22021. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22022. var registeredMesh = this._registeredMeshes[index];
  22023. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  22024. var body = registeredMesh.body;
  22025. var center = mesh.getBoundingInfo().boundingBox.center;
  22026. body.position.set(center.x, center.z, center.y);
  22027. body.quaternion.x = mesh.rotationQuaternion.x;
  22028. body.quaternion.z = mesh.rotationQuaternion.y;
  22029. body.quaternion.y = mesh.rotationQuaternion.z;
  22030. body.quaternion.w = -mesh.rotationQuaternion.w;
  22031. return;
  22032. }
  22033. }
  22034. };
  22035. }
  22036. CannonJSPlugin.prototype.initialize = function (iterations) {
  22037. if (iterations === void 0) { iterations = 10; }
  22038. this._world = new CANNON.World();
  22039. this._world.broadphase = new CANNON.NaiveBroadphase();
  22040. this._world.solver.iterations = iterations;
  22041. };
  22042. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  22043. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  22044. };
  22045. CannonJSPlugin.prototype.runOneStep = function (delta) {
  22046. this._world.step(delta);
  22047. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22048. var registeredMesh = this._registeredMeshes[index];
  22049. if (registeredMesh.isChild) {
  22050. continue;
  22051. }
  22052. // Body position
  22053. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  22054. var deltaPos = registeredMesh.delta;
  22055. if (deltaPos) {
  22056. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  22057. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  22058. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  22059. }
  22060. else {
  22061. registeredMesh.mesh.position.x = bodyX;
  22062. registeredMesh.mesh.position.y = bodyZ;
  22063. registeredMesh.mesh.position.z = bodyY;
  22064. }
  22065. if (!registeredMesh.mesh.rotationQuaternion) {
  22066. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22067. }
  22068. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  22069. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  22070. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  22071. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  22072. }
  22073. };
  22074. CannonJSPlugin.prototype.setGravity = function (gravity) {
  22075. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  22076. };
  22077. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  22078. this.unregisterMesh(mesh);
  22079. mesh.computeWorldMatrix(true);
  22080. switch (impostor) {
  22081. case BABYLON.PhysicsEngine.SphereImpostor:
  22082. var bbox = mesh.getBoundingInfo().boundingBox;
  22083. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  22084. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  22085. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  22086. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  22087. case BABYLON.PhysicsEngine.BoxImpostor:
  22088. bbox = mesh.getBoundingInfo().boundingBox;
  22089. var min = bbox.minimumWorld;
  22090. var max = bbox.maximumWorld;
  22091. var box = max.subtract(min).scale(0.5);
  22092. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  22093. case BABYLON.PhysicsEngine.PlaneImpostor:
  22094. return this._createPlane(mesh, options);
  22095. case BABYLON.PhysicsEngine.MeshImpostor:
  22096. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22097. var rawFaces = mesh.getIndices();
  22098. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  22099. }
  22100. return null;
  22101. };
  22102. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  22103. var shape = new CANNON.Sphere(radius);
  22104. if (!options) {
  22105. return shape;
  22106. }
  22107. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22108. };
  22109. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  22110. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  22111. if (!options) {
  22112. return shape;
  22113. }
  22114. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22115. };
  22116. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  22117. var shape = new CANNON.Plane();
  22118. if (!options) {
  22119. return shape;
  22120. }
  22121. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22122. };
  22123. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  22124. var verts = [], faces = [];
  22125. mesh.computeWorldMatrix(true);
  22126. for (var i = 0; i < rawVerts.length; i += 3) {
  22127. var transformed = BABYLON.Vector3.Zero();
  22128. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  22129. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  22130. }
  22131. for (var j = 0; j < rawFaces.length; j += 3) {
  22132. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  22133. }
  22134. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  22135. if (!options) {
  22136. return shape;
  22137. }
  22138. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  22139. };
  22140. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  22141. var index;
  22142. var mat;
  22143. for (index = 0; index < this._physicsMaterials.length; index++) {
  22144. mat = this._physicsMaterials[index];
  22145. if (mat.friction === friction && mat.restitution === restitution) {
  22146. return mat;
  22147. }
  22148. }
  22149. var currentMat = new CANNON.Material();
  22150. currentMat.friction = friction;
  22151. currentMat.restitution = restitution;
  22152. this._physicsMaterials.push(currentMat);
  22153. for (index = 0; index < this._physicsMaterials.length; index++) {
  22154. mat = this._physicsMaterials[index];
  22155. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  22156. contactMaterial.contactEquationStiffness = 1e10;
  22157. contactMaterial.contactEquationRegularizationTime = 10;
  22158. this._world.addContactMaterial(contactMaterial);
  22159. }
  22160. return currentMat;
  22161. };
  22162. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  22163. var initialRotation = null;
  22164. if (mesh.rotationQuaternion) {
  22165. initialRotation = mesh.rotationQuaternion.clone();
  22166. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  22167. }
  22168. // The delta between the mesh position and the mesh bounding box center
  22169. var bbox = mesh.getBoundingInfo().boundingBox;
  22170. var deltaPosition = mesh.position.subtract(bbox.center);
  22171. var material = this._addMaterial(friction, restitution);
  22172. var body = new CANNON.RigidBody(mass, shape, material);
  22173. if (initialRotation) {
  22174. body.quaternion.x = initialRotation.x;
  22175. body.quaternion.z = initialRotation.y;
  22176. body.quaternion.y = initialRotation.z;
  22177. body.quaternion.w = -initialRotation.w;
  22178. }
  22179. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  22180. this._world.add(body);
  22181. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  22182. return body;
  22183. };
  22184. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  22185. var compoundShape = new CANNON.Compound();
  22186. for (var index = 0; index < parts.length; index++) {
  22187. var mesh = parts[index].mesh;
  22188. var shape = this.registerMesh(mesh, parts[index].impostor);
  22189. if (index == 0) {
  22190. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  22191. }
  22192. else {
  22193. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  22194. }
  22195. }
  22196. var initialMesh = parts[0].mesh;
  22197. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  22198. body.parts = parts;
  22199. return body;
  22200. };
  22201. CannonJSPlugin.prototype._unbindBody = function (body) {
  22202. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22203. var registeredMesh = this._registeredMeshes[index];
  22204. if (registeredMesh.body === body) {
  22205. registeredMesh.body = null;
  22206. registeredMesh.delta = 0;
  22207. }
  22208. }
  22209. };
  22210. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  22211. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22212. var registeredMesh = this._registeredMeshes[index];
  22213. if (registeredMesh.mesh === mesh) {
  22214. // Remove body
  22215. if (registeredMesh.body) {
  22216. this._world.remove(registeredMesh.body);
  22217. this._unbindBody(registeredMesh.body);
  22218. }
  22219. this._registeredMeshes.splice(index, 1);
  22220. return;
  22221. }
  22222. }
  22223. };
  22224. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  22225. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  22226. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  22227. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22228. var registeredMesh = this._registeredMeshes[index];
  22229. if (registeredMesh.mesh === mesh) {
  22230. registeredMesh.body.applyImpulse(impulse, worldPoint);
  22231. return;
  22232. }
  22233. }
  22234. };
  22235. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  22236. var body1 = null, body2 = null;
  22237. for (var index = 0; index < this._registeredMeshes.length; index++) {
  22238. var registeredMesh = this._registeredMeshes[index];
  22239. if (registeredMesh.mesh === mesh1) {
  22240. body1 = registeredMesh.body;
  22241. }
  22242. else if (registeredMesh.mesh === mesh2) {
  22243. body2 = registeredMesh.body;
  22244. }
  22245. }
  22246. if (!body1 || !body2) {
  22247. return false;
  22248. }
  22249. 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));
  22250. this._world.addConstraint(constraint);
  22251. return true;
  22252. };
  22253. CannonJSPlugin.prototype.dispose = function () {
  22254. while (this._registeredMeshes.length) {
  22255. this.unregisterMesh(this._registeredMeshes[0].mesh);
  22256. }
  22257. };
  22258. CannonJSPlugin.prototype.isSupported = function () {
  22259. return window.CANNON !== undefined;
  22260. };
  22261. return CannonJSPlugin;
  22262. })();
  22263. BABYLON.CannonJSPlugin = CannonJSPlugin;
  22264. })(BABYLON || (BABYLON = {}));
  22265. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  22266. var BABYLON;
  22267. (function (BABYLON) {
  22268. var Condition = (function () {
  22269. function Condition(actionManager) {
  22270. this._actionManager = actionManager;
  22271. }
  22272. Condition.prototype.isValid = function () {
  22273. return true;
  22274. };
  22275. Condition.prototype._getProperty = function (propertyPath) {
  22276. return this._actionManager._getProperty(propertyPath);
  22277. };
  22278. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  22279. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22280. };
  22281. return Condition;
  22282. })();
  22283. BABYLON.Condition = Condition;
  22284. var ValueCondition = (function (_super) {
  22285. __extends(ValueCondition, _super);
  22286. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  22287. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  22288. _super.call(this, actionManager);
  22289. this.propertyPath = propertyPath;
  22290. this.value = value;
  22291. this.operator = operator;
  22292. this._target = this._getEffectiveTarget(target, this.propertyPath);
  22293. this._property = this._getProperty(this.propertyPath);
  22294. }
  22295. Object.defineProperty(ValueCondition, "IsEqual", {
  22296. get: function () {
  22297. return ValueCondition._IsEqual;
  22298. },
  22299. enumerable: true,
  22300. configurable: true
  22301. });
  22302. Object.defineProperty(ValueCondition, "IsDifferent", {
  22303. get: function () {
  22304. return ValueCondition._IsDifferent;
  22305. },
  22306. enumerable: true,
  22307. configurable: true
  22308. });
  22309. Object.defineProperty(ValueCondition, "IsGreater", {
  22310. get: function () {
  22311. return ValueCondition._IsGreater;
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(ValueCondition, "IsLesser", {
  22317. get: function () {
  22318. return ValueCondition._IsLesser;
  22319. },
  22320. enumerable: true,
  22321. configurable: true
  22322. });
  22323. // Methods
  22324. ValueCondition.prototype.isValid = function () {
  22325. switch (this.operator) {
  22326. case ValueCondition.IsGreater:
  22327. return this._target[this._property] > this.value;
  22328. case ValueCondition.IsLesser:
  22329. return this._target[this._property] < this.value;
  22330. case ValueCondition.IsEqual:
  22331. case ValueCondition.IsDifferent:
  22332. var check;
  22333. if (this.value.equals) {
  22334. check = this.value.equals(this._target[this._property]);
  22335. }
  22336. else {
  22337. check = this.value === this._target[this._property];
  22338. }
  22339. return this.operator === ValueCondition.IsEqual ? check : !check;
  22340. }
  22341. return false;
  22342. };
  22343. // Statics
  22344. ValueCondition._IsEqual = 0;
  22345. ValueCondition._IsDifferent = 1;
  22346. ValueCondition._IsGreater = 2;
  22347. ValueCondition._IsLesser = 3;
  22348. return ValueCondition;
  22349. })(Condition);
  22350. BABYLON.ValueCondition = ValueCondition;
  22351. var PredicateCondition = (function (_super) {
  22352. __extends(PredicateCondition, _super);
  22353. function PredicateCondition(actionManager, predicate) {
  22354. _super.call(this, actionManager);
  22355. this.predicate = predicate;
  22356. }
  22357. PredicateCondition.prototype.isValid = function () {
  22358. return this.predicate();
  22359. };
  22360. return PredicateCondition;
  22361. })(Condition);
  22362. BABYLON.PredicateCondition = PredicateCondition;
  22363. var StateCondition = (function (_super) {
  22364. __extends(StateCondition, _super);
  22365. function StateCondition(actionManager, target, value) {
  22366. _super.call(this, actionManager);
  22367. this.value = value;
  22368. this._target = target;
  22369. }
  22370. // Methods
  22371. StateCondition.prototype.isValid = function () {
  22372. return this._target.state === this.value;
  22373. };
  22374. return StateCondition;
  22375. })(Condition);
  22376. BABYLON.StateCondition = StateCondition;
  22377. })(BABYLON || (BABYLON = {}));
  22378. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  22379. (function (BABYLON) {
  22380. var Action = (function () {
  22381. function Action(triggerOptions, condition) {
  22382. this.triggerOptions = triggerOptions;
  22383. if (triggerOptions.parameter) {
  22384. this.trigger = triggerOptions.trigger;
  22385. this._triggerParameter = triggerOptions.parameter;
  22386. }
  22387. else {
  22388. this.trigger = triggerOptions;
  22389. }
  22390. this._nextActiveAction = this;
  22391. this._condition = condition;
  22392. }
  22393. // Methods
  22394. Action.prototype._prepare = function () {
  22395. };
  22396. Action.prototype.getTriggerParameter = function () {
  22397. return this._triggerParameter;
  22398. };
  22399. Action.prototype._executeCurrent = function (evt) {
  22400. if (this._condition) {
  22401. var currentRenderId = this._actionManager.getScene().getRenderId();
  22402. // We cache the current evaluation for the current frame
  22403. if (this._condition._evaluationId === currentRenderId) {
  22404. if (!this._condition._currentResult) {
  22405. return;
  22406. }
  22407. }
  22408. else {
  22409. this._condition._evaluationId = currentRenderId;
  22410. if (!this._condition.isValid()) {
  22411. this._condition._currentResult = false;
  22412. return;
  22413. }
  22414. this._condition._currentResult = true;
  22415. }
  22416. }
  22417. this._nextActiveAction.execute(evt);
  22418. if (this._nextActiveAction._child) {
  22419. if (!this._nextActiveAction._child._actionManager) {
  22420. this._nextActiveAction._child._actionManager = this._actionManager;
  22421. }
  22422. this._nextActiveAction = this._nextActiveAction._child;
  22423. }
  22424. else {
  22425. this._nextActiveAction = this;
  22426. }
  22427. };
  22428. Action.prototype.execute = function (evt) {
  22429. };
  22430. Action.prototype.then = function (action) {
  22431. this._child = action;
  22432. action._actionManager = this._actionManager;
  22433. action._prepare();
  22434. return action;
  22435. };
  22436. Action.prototype._getProperty = function (propertyPath) {
  22437. return this._actionManager._getProperty(propertyPath);
  22438. };
  22439. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  22440. return this._actionManager._getEffectiveTarget(target, propertyPath);
  22441. };
  22442. return Action;
  22443. })();
  22444. BABYLON.Action = Action;
  22445. })(BABYLON || (BABYLON = {}));
  22446. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  22447. (function (BABYLON) {
  22448. var ActionEvent = (function () {
  22449. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  22450. this.source = source;
  22451. this.pointerX = pointerX;
  22452. this.pointerY = pointerY;
  22453. this.meshUnderPointer = meshUnderPointer;
  22454. this.sourceEvent = sourceEvent;
  22455. }
  22456. ActionEvent.CreateNew = function (source, evt) {
  22457. var scene = source.getScene();
  22458. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22459. };
  22460. ActionEvent.CreateNewFromScene = function (scene, evt) {
  22461. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  22462. };
  22463. return ActionEvent;
  22464. })();
  22465. BABYLON.ActionEvent = ActionEvent;
  22466. var ActionManager = (function () {
  22467. function ActionManager(scene) {
  22468. // Members
  22469. this.actions = new Array();
  22470. this._scene = scene;
  22471. scene._actionManagers.push(this);
  22472. }
  22473. Object.defineProperty(ActionManager, "NothingTrigger", {
  22474. get: function () {
  22475. return ActionManager._NothingTrigger;
  22476. },
  22477. enumerable: true,
  22478. configurable: true
  22479. });
  22480. Object.defineProperty(ActionManager, "OnPickTrigger", {
  22481. get: function () {
  22482. return ActionManager._OnPickTrigger;
  22483. },
  22484. enumerable: true,
  22485. configurable: true
  22486. });
  22487. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  22488. get: function () {
  22489. return ActionManager._OnLeftPickTrigger;
  22490. },
  22491. enumerable: true,
  22492. configurable: true
  22493. });
  22494. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  22495. get: function () {
  22496. return ActionManager._OnRightPickTrigger;
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  22502. get: function () {
  22503. return ActionManager._OnCenterPickTrigger;
  22504. },
  22505. enumerable: true,
  22506. configurable: true
  22507. });
  22508. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  22509. get: function () {
  22510. return ActionManager._OnPointerOverTrigger;
  22511. },
  22512. enumerable: true,
  22513. configurable: true
  22514. });
  22515. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  22516. get: function () {
  22517. return ActionManager._OnPointerOutTrigger;
  22518. },
  22519. enumerable: true,
  22520. configurable: true
  22521. });
  22522. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  22523. get: function () {
  22524. return ActionManager._OnEveryFrameTrigger;
  22525. },
  22526. enumerable: true,
  22527. configurable: true
  22528. });
  22529. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  22530. get: function () {
  22531. return ActionManager._OnIntersectionEnterTrigger;
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  22537. get: function () {
  22538. return ActionManager._OnIntersectionExitTrigger;
  22539. },
  22540. enumerable: true,
  22541. configurable: true
  22542. });
  22543. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  22544. get: function () {
  22545. return ActionManager._OnKeyDownTrigger;
  22546. },
  22547. enumerable: true,
  22548. configurable: true
  22549. });
  22550. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  22551. get: function () {
  22552. return ActionManager._OnKeyUpTrigger;
  22553. },
  22554. enumerable: true,
  22555. configurable: true
  22556. });
  22557. // Methods
  22558. ActionManager.prototype.dispose = function () {
  22559. var index = this._scene._actionManagers.indexOf(this);
  22560. if (index > -1) {
  22561. this._scene._actionManagers.splice(index, 1);
  22562. }
  22563. };
  22564. ActionManager.prototype.getScene = function () {
  22565. return this._scene;
  22566. };
  22567. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  22568. for (var index = 0; index < this.actions.length; index++) {
  22569. var action = this.actions[index];
  22570. if (triggers.indexOf(action.trigger) > -1) {
  22571. return true;
  22572. }
  22573. }
  22574. return false;
  22575. };
  22576. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  22577. get: function () {
  22578. for (var index = 0; index < this.actions.length; index++) {
  22579. var action = this.actions[index];
  22580. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  22581. return true;
  22582. }
  22583. }
  22584. return false;
  22585. },
  22586. enumerable: true,
  22587. configurable: true
  22588. });
  22589. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  22590. get: function () {
  22591. for (var index = 0; index < this.actions.length; index++) {
  22592. var action = this.actions[index];
  22593. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  22594. return true;
  22595. }
  22596. }
  22597. return false;
  22598. },
  22599. enumerable: true,
  22600. configurable: true
  22601. });
  22602. ActionManager.prototype.registerAction = function (action) {
  22603. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  22604. if (this.getScene().actionManager !== this) {
  22605. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  22606. return null;
  22607. }
  22608. }
  22609. this.actions.push(action);
  22610. action._actionManager = this;
  22611. action._prepare();
  22612. return action;
  22613. };
  22614. ActionManager.prototype.processTrigger = function (trigger, evt) {
  22615. for (var index = 0; index < this.actions.length; index++) {
  22616. var action = this.actions[index];
  22617. if (action.trigger === trigger) {
  22618. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  22619. var parameter = action.getTriggerParameter();
  22620. if (parameter) {
  22621. if (evt.sourceEvent.key !== parameter) {
  22622. continue;
  22623. }
  22624. }
  22625. }
  22626. action._executeCurrent(evt);
  22627. }
  22628. }
  22629. };
  22630. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  22631. var properties = propertyPath.split(".");
  22632. for (var index = 0; index < properties.length - 1; index++) {
  22633. target = target[properties[index]];
  22634. }
  22635. return target;
  22636. };
  22637. ActionManager.prototype._getProperty = function (propertyPath) {
  22638. var properties = propertyPath.split(".");
  22639. return properties[properties.length - 1];
  22640. };
  22641. // Statics
  22642. ActionManager._NothingTrigger = 0;
  22643. ActionManager._OnPickTrigger = 1;
  22644. ActionManager._OnLeftPickTrigger = 2;
  22645. ActionManager._OnRightPickTrigger = 3;
  22646. ActionManager._OnCenterPickTrigger = 4;
  22647. ActionManager._OnPointerOverTrigger = 5;
  22648. ActionManager._OnPointerOutTrigger = 6;
  22649. ActionManager._OnEveryFrameTrigger = 7;
  22650. ActionManager._OnIntersectionEnterTrigger = 8;
  22651. ActionManager._OnIntersectionExitTrigger = 9;
  22652. ActionManager._OnKeyDownTrigger = 10;
  22653. ActionManager._OnKeyUpTrigger = 11;
  22654. return ActionManager;
  22655. })();
  22656. BABYLON.ActionManager = ActionManager;
  22657. })(BABYLON || (BABYLON = {}));
  22658. //# sourceMappingURL=babylon.actionManager.js.map
  22659. var BABYLON;
  22660. (function (BABYLON) {
  22661. var InterpolateValueAction = (function (_super) {
  22662. __extends(InterpolateValueAction, _super);
  22663. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  22664. if (duration === void 0) { duration = 1000; }
  22665. _super.call(this, triggerOptions, condition);
  22666. this.propertyPath = propertyPath;
  22667. this.value = value;
  22668. this.duration = duration;
  22669. this.stopOtherAnimations = stopOtherAnimations;
  22670. this._target = target;
  22671. }
  22672. InterpolateValueAction.prototype._prepare = function () {
  22673. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22674. this._property = this._getProperty(this.propertyPath);
  22675. };
  22676. InterpolateValueAction.prototype.execute = function () {
  22677. var scene = this._actionManager.getScene();
  22678. var keys = [
  22679. {
  22680. frame: 0,
  22681. value: this._target[this._property]
  22682. },
  22683. {
  22684. frame: 100,
  22685. value: this.value
  22686. }
  22687. ];
  22688. var dataType;
  22689. if (typeof this.value === "number") {
  22690. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  22691. }
  22692. else if (this.value instanceof BABYLON.Color3) {
  22693. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  22694. }
  22695. else if (this.value instanceof BABYLON.Vector3) {
  22696. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  22697. }
  22698. else if (this.value instanceof BABYLON.Matrix) {
  22699. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  22700. }
  22701. else if (this.value instanceof BABYLON.Quaternion) {
  22702. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  22703. }
  22704. else {
  22705. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  22706. return;
  22707. }
  22708. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  22709. animation.setKeys(keys);
  22710. if (this.stopOtherAnimations) {
  22711. scene.stopAnimation(this._target);
  22712. }
  22713. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  22714. };
  22715. return InterpolateValueAction;
  22716. })(BABYLON.Action);
  22717. BABYLON.InterpolateValueAction = InterpolateValueAction;
  22718. })(BABYLON || (BABYLON = {}));
  22719. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  22720. var BABYLON;
  22721. (function (BABYLON) {
  22722. var SwitchBooleanAction = (function (_super) {
  22723. __extends(SwitchBooleanAction, _super);
  22724. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  22725. _super.call(this, triggerOptions, condition);
  22726. this.propertyPath = propertyPath;
  22727. this._target = target;
  22728. }
  22729. SwitchBooleanAction.prototype._prepare = function () {
  22730. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22731. this._property = this._getProperty(this.propertyPath);
  22732. };
  22733. SwitchBooleanAction.prototype.execute = function () {
  22734. this._target[this._property] = !this._target[this._property];
  22735. };
  22736. return SwitchBooleanAction;
  22737. })(BABYLON.Action);
  22738. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  22739. var SetStateAction = (function (_super) {
  22740. __extends(SetStateAction, _super);
  22741. function SetStateAction(triggerOptions, target, value, condition) {
  22742. _super.call(this, triggerOptions, condition);
  22743. this.value = value;
  22744. this._target = target;
  22745. }
  22746. SetStateAction.prototype.execute = function () {
  22747. this._target.state = this.value;
  22748. };
  22749. return SetStateAction;
  22750. })(BABYLON.Action);
  22751. BABYLON.SetStateAction = SetStateAction;
  22752. var SetValueAction = (function (_super) {
  22753. __extends(SetValueAction, _super);
  22754. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  22755. _super.call(this, triggerOptions, condition);
  22756. this.propertyPath = propertyPath;
  22757. this.value = value;
  22758. this._target = target;
  22759. }
  22760. SetValueAction.prototype._prepare = function () {
  22761. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22762. this._property = this._getProperty(this.propertyPath);
  22763. };
  22764. SetValueAction.prototype.execute = function () {
  22765. this._target[this._property] = this.value;
  22766. };
  22767. return SetValueAction;
  22768. })(BABYLON.Action);
  22769. BABYLON.SetValueAction = SetValueAction;
  22770. var IncrementValueAction = (function (_super) {
  22771. __extends(IncrementValueAction, _super);
  22772. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  22773. _super.call(this, triggerOptions, condition);
  22774. this.propertyPath = propertyPath;
  22775. this.value = value;
  22776. this._target = target;
  22777. }
  22778. IncrementValueAction.prototype._prepare = function () {
  22779. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  22780. this._property = this._getProperty(this.propertyPath);
  22781. if (typeof this._target[this._property] !== "number") {
  22782. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  22783. }
  22784. };
  22785. IncrementValueAction.prototype.execute = function () {
  22786. this._target[this._property] += this.value;
  22787. };
  22788. return IncrementValueAction;
  22789. })(BABYLON.Action);
  22790. BABYLON.IncrementValueAction = IncrementValueAction;
  22791. var PlayAnimationAction = (function (_super) {
  22792. __extends(PlayAnimationAction, _super);
  22793. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  22794. _super.call(this, triggerOptions, condition);
  22795. this.from = from;
  22796. this.to = to;
  22797. this.loop = loop;
  22798. this._target = target;
  22799. }
  22800. PlayAnimationAction.prototype._prepare = function () {
  22801. };
  22802. PlayAnimationAction.prototype.execute = function () {
  22803. var scene = this._actionManager.getScene();
  22804. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  22805. };
  22806. return PlayAnimationAction;
  22807. })(BABYLON.Action);
  22808. BABYLON.PlayAnimationAction = PlayAnimationAction;
  22809. var StopAnimationAction = (function (_super) {
  22810. __extends(StopAnimationAction, _super);
  22811. function StopAnimationAction(triggerOptions, target, condition) {
  22812. _super.call(this, triggerOptions, condition);
  22813. this._target = target;
  22814. }
  22815. StopAnimationAction.prototype._prepare = function () {
  22816. };
  22817. StopAnimationAction.prototype.execute = function () {
  22818. var scene = this._actionManager.getScene();
  22819. scene.stopAnimation(this._target);
  22820. };
  22821. return StopAnimationAction;
  22822. })(BABYLON.Action);
  22823. BABYLON.StopAnimationAction = StopAnimationAction;
  22824. var DoNothingAction = (function (_super) {
  22825. __extends(DoNothingAction, _super);
  22826. function DoNothingAction(triggerOptions, condition) {
  22827. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  22828. _super.call(this, triggerOptions, condition);
  22829. }
  22830. DoNothingAction.prototype.execute = function () {
  22831. };
  22832. return DoNothingAction;
  22833. })(BABYLON.Action);
  22834. BABYLON.DoNothingAction = DoNothingAction;
  22835. var CombineAction = (function (_super) {
  22836. __extends(CombineAction, _super);
  22837. function CombineAction(triggerOptions, children, condition) {
  22838. _super.call(this, triggerOptions, condition);
  22839. this.children = children;
  22840. }
  22841. CombineAction.prototype._prepare = function () {
  22842. for (var index = 0; index < this.children.length; index++) {
  22843. this.children[index]._actionManager = this._actionManager;
  22844. this.children[index]._prepare();
  22845. }
  22846. };
  22847. CombineAction.prototype.execute = function (evt) {
  22848. for (var index = 0; index < this.children.length; index++) {
  22849. this.children[index].execute(evt);
  22850. }
  22851. };
  22852. return CombineAction;
  22853. })(BABYLON.Action);
  22854. BABYLON.CombineAction = CombineAction;
  22855. var ExecuteCodeAction = (function (_super) {
  22856. __extends(ExecuteCodeAction, _super);
  22857. function ExecuteCodeAction(triggerOptions, func, condition) {
  22858. _super.call(this, triggerOptions, condition);
  22859. this.func = func;
  22860. }
  22861. ExecuteCodeAction.prototype.execute = function (evt) {
  22862. this.func(evt);
  22863. };
  22864. return ExecuteCodeAction;
  22865. })(BABYLON.Action);
  22866. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  22867. var SetParentAction = (function (_super) {
  22868. __extends(SetParentAction, _super);
  22869. function SetParentAction(triggerOptions, target, parent, condition) {
  22870. _super.call(this, triggerOptions, condition);
  22871. this._target = target;
  22872. this._parent = parent;
  22873. }
  22874. SetParentAction.prototype._prepare = function () {
  22875. };
  22876. SetParentAction.prototype.execute = function () {
  22877. if (this._target.parent === this._parent) {
  22878. return;
  22879. }
  22880. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  22881. invertParentWorldMatrix.invert();
  22882. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  22883. this._target.parent = this._parent;
  22884. };
  22885. return SetParentAction;
  22886. })(BABYLON.Action);
  22887. BABYLON.SetParentAction = SetParentAction;
  22888. })(BABYLON || (BABYLON = {}));
  22889. //# sourceMappingURL=babylon.directActions.js.map
  22890. var BABYLON;
  22891. (function (BABYLON) {
  22892. var Geometry = (function () {
  22893. function Geometry(id, scene, vertexData, updatable, mesh) {
  22894. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22895. this._totalVertices = 0;
  22896. this._indices = [];
  22897. this.id = id;
  22898. this._engine = scene.getEngine();
  22899. this._meshes = [];
  22900. this._scene = scene;
  22901. // vertexData
  22902. if (vertexData) {
  22903. this.setAllVerticesData(vertexData, updatable);
  22904. }
  22905. else {
  22906. this._totalVertices = 0;
  22907. this._indices = [];
  22908. }
  22909. // applyToMesh
  22910. if (mesh) {
  22911. this.applyToMesh(mesh);
  22912. }
  22913. }
  22914. Geometry.prototype.getScene = function () {
  22915. return this._scene;
  22916. };
  22917. Geometry.prototype.getEngine = function () {
  22918. return this._engine;
  22919. };
  22920. Geometry.prototype.isReady = function () {
  22921. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  22922. };
  22923. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  22924. vertexData.applyToGeometry(this, updatable);
  22925. };
  22926. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  22927. this._vertexBuffers = this._vertexBuffers || {};
  22928. if (this._vertexBuffers[kind]) {
  22929. this._vertexBuffers[kind].dispose();
  22930. }
  22931. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  22932. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22933. stride = this._vertexBuffers[kind].getStrideSize();
  22934. this._totalVertices = data.length / stride;
  22935. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22936. var meshes = this._meshes;
  22937. var numOfMeshes = meshes.length;
  22938. for (var index = 0; index < numOfMeshes; index++) {
  22939. var mesh = meshes[index];
  22940. mesh._resetPointsArrayCache();
  22941. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22942. mesh._createGlobalSubMesh();
  22943. mesh.computeWorldMatrix(true);
  22944. }
  22945. }
  22946. };
  22947. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  22948. var vertexBuffer = this.getVertexBuffer(kind);
  22949. if (!vertexBuffer) {
  22950. return;
  22951. }
  22952. vertexBuffer.updateDirectly(data, offset);
  22953. };
  22954. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  22955. var vertexBuffer = this.getVertexBuffer(kind);
  22956. if (!vertexBuffer) {
  22957. return;
  22958. }
  22959. vertexBuffer.update(data);
  22960. if (kind === BABYLON.VertexBuffer.PositionKind) {
  22961. var extend;
  22962. var stride = vertexBuffer.getStrideSize();
  22963. this._totalVertices = data.length / stride;
  22964. if (updateExtends) {
  22965. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  22966. }
  22967. var meshes = this._meshes;
  22968. var numOfMeshes = meshes.length;
  22969. for (var index = 0; index < numOfMeshes; index++) {
  22970. var mesh = meshes[index];
  22971. mesh._resetPointsArrayCache();
  22972. if (updateExtends) {
  22973. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22974. }
  22975. }
  22976. }
  22977. };
  22978. Geometry.prototype.getTotalVertices = function () {
  22979. if (!this.isReady()) {
  22980. return 0;
  22981. }
  22982. return this._totalVertices;
  22983. };
  22984. Geometry.prototype.getVerticesData = function (kind) {
  22985. var vertexBuffer = this.getVertexBuffer(kind);
  22986. if (!vertexBuffer) {
  22987. return null;
  22988. }
  22989. return vertexBuffer.getData();
  22990. };
  22991. Geometry.prototype.getVertexBuffer = function (kind) {
  22992. if (!this.isReady()) {
  22993. return null;
  22994. }
  22995. return this._vertexBuffers[kind];
  22996. };
  22997. Geometry.prototype.getVertexBuffers = function () {
  22998. if (!this.isReady()) {
  22999. return null;
  23000. }
  23001. return this._vertexBuffers;
  23002. };
  23003. Geometry.prototype.isVerticesDataPresent = function (kind) {
  23004. if (!this._vertexBuffers) {
  23005. if (this._delayInfo) {
  23006. return this._delayInfo.indexOf(kind) !== -1;
  23007. }
  23008. return false;
  23009. }
  23010. return this._vertexBuffers[kind] !== undefined;
  23011. };
  23012. Geometry.prototype.getVerticesDataKinds = function () {
  23013. var result = [];
  23014. if (!this._vertexBuffers && this._delayInfo) {
  23015. for (var kind in this._delayInfo) {
  23016. result.push(kind);
  23017. }
  23018. }
  23019. else {
  23020. for (kind in this._vertexBuffers) {
  23021. result.push(kind);
  23022. }
  23023. }
  23024. return result;
  23025. };
  23026. Geometry.prototype.setIndices = function (indices, totalVertices) {
  23027. if (this._indexBuffer) {
  23028. this._engine._releaseBuffer(this._indexBuffer);
  23029. }
  23030. this._indices = indices;
  23031. if (this._meshes.length !== 0 && this._indices) {
  23032. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23033. }
  23034. if (totalVertices !== undefined) {
  23035. this._totalVertices = totalVertices;
  23036. }
  23037. var meshes = this._meshes;
  23038. var numOfMeshes = meshes.length;
  23039. for (var index = 0; index < numOfMeshes; index++) {
  23040. meshes[index]._createGlobalSubMesh();
  23041. }
  23042. };
  23043. Geometry.prototype.getTotalIndices = function () {
  23044. if (!this.isReady()) {
  23045. return 0;
  23046. }
  23047. return this._indices.length;
  23048. };
  23049. Geometry.prototype.getIndices = function () {
  23050. if (!this.isReady()) {
  23051. return null;
  23052. }
  23053. return this._indices;
  23054. };
  23055. Geometry.prototype.getIndexBuffer = function () {
  23056. if (!this.isReady()) {
  23057. return null;
  23058. }
  23059. return this._indexBuffer;
  23060. };
  23061. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  23062. var meshes = this._meshes;
  23063. var index = meshes.indexOf(mesh);
  23064. if (index === -1) {
  23065. return;
  23066. }
  23067. for (var kind in this._vertexBuffers) {
  23068. this._vertexBuffers[kind].dispose();
  23069. }
  23070. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  23071. this._indexBuffer = null;
  23072. }
  23073. meshes.splice(index, 1);
  23074. mesh._geometry = null;
  23075. if (meshes.length === 0 && shouldDispose) {
  23076. this.dispose();
  23077. }
  23078. };
  23079. Geometry.prototype.applyToMesh = function (mesh) {
  23080. if (mesh._geometry === this) {
  23081. return;
  23082. }
  23083. var previousGeometry = mesh._geometry;
  23084. if (previousGeometry) {
  23085. previousGeometry.releaseForMesh(mesh);
  23086. }
  23087. var meshes = this._meshes;
  23088. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  23089. mesh._geometry = this;
  23090. this._scene.pushGeometry(this);
  23091. meshes.push(mesh);
  23092. if (this.isReady()) {
  23093. this._applyToMesh(mesh);
  23094. }
  23095. else {
  23096. mesh._boundingInfo = this._boundingInfo;
  23097. }
  23098. };
  23099. Geometry.prototype._applyToMesh = function (mesh) {
  23100. var numOfMeshes = this._meshes.length;
  23101. for (var kind in this._vertexBuffers) {
  23102. if (numOfMeshes === 1) {
  23103. this._vertexBuffers[kind].create();
  23104. }
  23105. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  23106. if (kind === BABYLON.VertexBuffer.PositionKind) {
  23107. mesh._resetPointsArrayCache();
  23108. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  23109. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23110. mesh._createGlobalSubMesh();
  23111. //bounding info was just created again, world matrix should be applied again.
  23112. mesh._updateBoundingInfo();
  23113. }
  23114. }
  23115. // indexBuffer
  23116. if (numOfMeshes === 1 && this._indices) {
  23117. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  23118. }
  23119. if (this._indexBuffer) {
  23120. this._indexBuffer.references = numOfMeshes;
  23121. }
  23122. };
  23123. Geometry.prototype.load = function (scene, onLoaded) {
  23124. var _this = this;
  23125. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23126. return;
  23127. }
  23128. if (this.isReady()) {
  23129. if (onLoaded) {
  23130. onLoaded();
  23131. }
  23132. return;
  23133. }
  23134. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  23135. scene._addPendingData(this);
  23136. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  23137. _this._delayLoadingFunction(JSON.parse(data), _this);
  23138. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23139. _this._delayInfo = [];
  23140. scene._removePendingData(_this);
  23141. var meshes = _this._meshes;
  23142. var numOfMeshes = meshes.length;
  23143. for (var index = 0; index < numOfMeshes; index++) {
  23144. _this._applyToMesh(meshes[index]);
  23145. }
  23146. if (onLoaded) {
  23147. onLoaded();
  23148. }
  23149. }, function () {
  23150. }, scene.database);
  23151. };
  23152. Geometry.prototype.dispose = function () {
  23153. var meshes = this._meshes;
  23154. var numOfMeshes = meshes.length;
  23155. var index;
  23156. for (index = 0; index < numOfMeshes; index++) {
  23157. this.releaseForMesh(meshes[index]);
  23158. }
  23159. this._meshes = [];
  23160. for (var kind in this._vertexBuffers) {
  23161. this._vertexBuffers[kind].dispose();
  23162. }
  23163. this._vertexBuffers = [];
  23164. this._totalVertices = 0;
  23165. if (this._indexBuffer) {
  23166. this._engine._releaseBuffer(this._indexBuffer);
  23167. }
  23168. this._indexBuffer = null;
  23169. this._indices = [];
  23170. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23171. this.delayLoadingFile = null;
  23172. this._delayLoadingFunction = null;
  23173. this._delayInfo = [];
  23174. this._boundingInfo = null; // todo: .dispose()
  23175. var geometries = this._scene.getGeometries();
  23176. index = geometries.indexOf(this);
  23177. if (index > -1) {
  23178. geometries.splice(index, 1);
  23179. }
  23180. };
  23181. Geometry.prototype.copy = function (id) {
  23182. var vertexData = new BABYLON.VertexData();
  23183. vertexData.indices = [];
  23184. var indices = this.getIndices();
  23185. for (var index = 0; index < indices.length; index++) {
  23186. vertexData.indices.push(indices[index]);
  23187. }
  23188. var updatable = false;
  23189. var stopChecking = false;
  23190. for (var kind in this._vertexBuffers) {
  23191. vertexData.set(this.getVerticesData(kind), kind);
  23192. if (!stopChecking) {
  23193. updatable = this.getVertexBuffer(kind).isUpdatable();
  23194. stopChecking = !updatable;
  23195. }
  23196. }
  23197. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  23198. geometry.delayLoadState = this.delayLoadState;
  23199. geometry.delayLoadingFile = this.delayLoadingFile;
  23200. geometry._delayLoadingFunction = this._delayLoadingFunction;
  23201. for (kind in this._delayInfo) {
  23202. geometry._delayInfo = geometry._delayInfo || [];
  23203. geometry._delayInfo.push(kind);
  23204. }
  23205. // Bounding info
  23206. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  23207. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23208. return geometry;
  23209. };
  23210. // Statics
  23211. Geometry.ExtractFromMesh = function (mesh, id) {
  23212. var geometry = mesh._geometry;
  23213. if (!geometry) {
  23214. return null;
  23215. }
  23216. return geometry.copy(id);
  23217. };
  23218. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  23219. // be aware Math.random() could cause collisions
  23220. Geometry.RandomId = function () {
  23221. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  23222. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  23223. return v.toString(16);
  23224. });
  23225. };
  23226. return Geometry;
  23227. })();
  23228. BABYLON.Geometry = Geometry;
  23229. /////// Primitives //////////////////////////////////////////////
  23230. var Geometry;
  23231. (function (Geometry) {
  23232. var Primitives;
  23233. (function (Primitives) {
  23234. /// Abstract class
  23235. var _Primitive = (function (_super) {
  23236. __extends(_Primitive, _super);
  23237. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  23238. this._beingRegenerated = true;
  23239. this._canBeRegenerated = canBeRegenerated;
  23240. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  23241. this._beingRegenerated = false;
  23242. }
  23243. _Primitive.prototype.canBeRegenerated = function () {
  23244. return this._canBeRegenerated;
  23245. };
  23246. _Primitive.prototype.regenerate = function () {
  23247. if (!this._canBeRegenerated) {
  23248. return;
  23249. }
  23250. this._beingRegenerated = true;
  23251. this.setAllVerticesData(this._regenerateVertexData(), false);
  23252. this._beingRegenerated = false;
  23253. };
  23254. _Primitive.prototype.asNewGeometry = function (id) {
  23255. return _super.prototype.copy.call(this, id);
  23256. };
  23257. // overrides
  23258. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  23259. if (!this._beingRegenerated) {
  23260. return;
  23261. }
  23262. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  23263. };
  23264. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  23265. if (!this._beingRegenerated) {
  23266. return;
  23267. }
  23268. _super.prototype.setVerticesData.call(this, kind, data, false);
  23269. };
  23270. // to override
  23271. // protected
  23272. _Primitive.prototype._regenerateVertexData = function () {
  23273. throw new Error("Abstract method");
  23274. };
  23275. _Primitive.prototype.copy = function (id) {
  23276. throw new Error("Must be overriden in sub-classes.");
  23277. };
  23278. return _Primitive;
  23279. })(Geometry);
  23280. Primitives._Primitive = _Primitive;
  23281. var Box = (function (_super) {
  23282. __extends(Box, _super);
  23283. function Box(id, scene, size, canBeRegenerated, mesh) {
  23284. this.size = size;
  23285. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23286. }
  23287. Box.prototype._regenerateVertexData = function () {
  23288. return BABYLON.VertexData.CreateBox(this.size);
  23289. };
  23290. Box.prototype.copy = function (id) {
  23291. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23292. };
  23293. return Box;
  23294. })(_Primitive);
  23295. Primitives.Box = Box;
  23296. var Sphere = (function (_super) {
  23297. __extends(Sphere, _super);
  23298. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh) {
  23299. this.segments = segments;
  23300. this.diameter = diameter;
  23301. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23302. }
  23303. Sphere.prototype._regenerateVertexData = function () {
  23304. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter);
  23305. };
  23306. Sphere.prototype.copy = function (id) {
  23307. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null);
  23308. };
  23309. return Sphere;
  23310. })(_Primitive);
  23311. Primitives.Sphere = Sphere;
  23312. var Cylinder = (function (_super) {
  23313. __extends(Cylinder, _super);
  23314. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh) {
  23315. if (subdivisions === void 0) { subdivisions = 1; }
  23316. this.height = height;
  23317. this.diameterTop = diameterTop;
  23318. this.diameterBottom = diameterBottom;
  23319. this.tessellation = tessellation;
  23320. this.subdivisions = subdivisions;
  23321. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23322. }
  23323. Cylinder.prototype._regenerateVertexData = function () {
  23324. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions);
  23325. };
  23326. Cylinder.prototype.copy = function (id) {
  23327. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null);
  23328. };
  23329. return Cylinder;
  23330. })(_Primitive);
  23331. Primitives.Cylinder = Cylinder;
  23332. var Torus = (function (_super) {
  23333. __extends(Torus, _super);
  23334. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh) {
  23335. this.diameter = diameter;
  23336. this.thickness = thickness;
  23337. this.tessellation = tessellation;
  23338. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23339. }
  23340. Torus.prototype._regenerateVertexData = function () {
  23341. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation);
  23342. };
  23343. Torus.prototype.copy = function (id) {
  23344. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null);
  23345. };
  23346. return Torus;
  23347. })(_Primitive);
  23348. Primitives.Torus = Torus;
  23349. var Ground = (function (_super) {
  23350. __extends(Ground, _super);
  23351. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  23352. this.width = width;
  23353. this.height = height;
  23354. this.subdivisions = subdivisions;
  23355. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23356. }
  23357. Ground.prototype._regenerateVertexData = function () {
  23358. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  23359. };
  23360. Ground.prototype.copy = function (id) {
  23361. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  23362. };
  23363. return Ground;
  23364. })(_Primitive);
  23365. Primitives.Ground = Ground;
  23366. var TiledGround = (function (_super) {
  23367. __extends(TiledGround, _super);
  23368. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  23369. this.xmin = xmin;
  23370. this.zmin = zmin;
  23371. this.xmax = xmax;
  23372. this.zmax = zmax;
  23373. this.subdivisions = subdivisions;
  23374. this.precision = precision;
  23375. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23376. }
  23377. TiledGround.prototype._regenerateVertexData = function () {
  23378. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  23379. };
  23380. TiledGround.prototype.copy = function (id) {
  23381. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  23382. };
  23383. return TiledGround;
  23384. })(_Primitive);
  23385. Primitives.TiledGround = TiledGround;
  23386. var Plane = (function (_super) {
  23387. __extends(Plane, _super);
  23388. function Plane(id, scene, size, canBeRegenerated, mesh) {
  23389. this.size = size;
  23390. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23391. }
  23392. Plane.prototype._regenerateVertexData = function () {
  23393. return BABYLON.VertexData.CreatePlane(this.size);
  23394. };
  23395. Plane.prototype.copy = function (id) {
  23396. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null);
  23397. };
  23398. return Plane;
  23399. })(_Primitive);
  23400. Primitives.Plane = Plane;
  23401. var TorusKnot = (function (_super) {
  23402. __extends(TorusKnot, _super);
  23403. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh) {
  23404. this.radius = radius;
  23405. this.tube = tube;
  23406. this.radialSegments = radialSegments;
  23407. this.tubularSegments = tubularSegments;
  23408. this.p = p;
  23409. this.q = q;
  23410. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  23411. }
  23412. TorusKnot.prototype._regenerateVertexData = function () {
  23413. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q);
  23414. };
  23415. TorusKnot.prototype.copy = function (id) {
  23416. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null);
  23417. };
  23418. return TorusKnot;
  23419. })(_Primitive);
  23420. Primitives.TorusKnot = TorusKnot;
  23421. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  23422. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  23423. })(BABYLON || (BABYLON = {}));
  23424. //# sourceMappingURL=babylon.geometry.js.map
  23425. var BABYLON;
  23426. (function (BABYLON) {
  23427. var Gamepads = (function () {
  23428. function Gamepads(ongamedpadconnected) {
  23429. var _this = this;
  23430. this.babylonGamepads = [];
  23431. this.oneGamepadConnected = false;
  23432. this.isMonitoring = false;
  23433. this.gamepadEventSupported = 'GamepadEvent' in window;
  23434. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  23435. 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=";
  23436. this._callbackGamepadConnected = ongamedpadconnected;
  23437. if (this.gamepadSupportAvailable) {
  23438. // Checking if the gamepad connected event is supported (like in Firefox)
  23439. if (this.gamepadEventSupported) {
  23440. window.addEventListener('gamepadconnected', function (evt) {
  23441. _this._onGamepadConnected(evt);
  23442. }, false);
  23443. window.addEventListener('gamepaddisconnected', function (evt) {
  23444. _this._onGamepadDisconnected(evt);
  23445. }, false);
  23446. }
  23447. else {
  23448. this._startMonitoringGamepads();
  23449. }
  23450. if (!this.oneGamepadConnected) {
  23451. this._insertGamepadDOMInstructions();
  23452. }
  23453. }
  23454. else {
  23455. this._insertGamepadDOMNotSupported();
  23456. }
  23457. }
  23458. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  23459. Gamepads.gamepadDOMInfo = document.createElement("div");
  23460. var buttonAImage = document.createElement("img");
  23461. buttonAImage.src = this.buttonADataURL;
  23462. var spanMessage = document.createElement("span");
  23463. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  23464. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  23465. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23466. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23467. Gamepads.gamepadDOMInfo.style.width = "100%";
  23468. Gamepads.gamepadDOMInfo.style.height = "48px";
  23469. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23470. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23471. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23472. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23473. buttonAImage.style.position = "relative";
  23474. buttonAImage.style.bottom = "8px";
  23475. spanMessage.style.position = "relative";
  23476. spanMessage.style.fontSize = "32px";
  23477. spanMessage.style.bottom = "32px";
  23478. spanMessage.style.color = "green";
  23479. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23480. };
  23481. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  23482. Gamepads.gamepadDOMInfo = document.createElement("div");
  23483. var spanMessage = document.createElement("span");
  23484. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  23485. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  23486. Gamepads.gamepadDOMInfo.style.position = "absolute";
  23487. Gamepads.gamepadDOMInfo.style.width = "100%";
  23488. Gamepads.gamepadDOMInfo.style.height = "40px";
  23489. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  23490. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  23491. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  23492. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  23493. spanMessage.style.position = "relative";
  23494. spanMessage.style.fontSize = "32px";
  23495. spanMessage.style.color = "red";
  23496. document.body.appendChild(Gamepads.gamepadDOMInfo);
  23497. };
  23498. Gamepads.prototype.dispose = function () {
  23499. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23500. };
  23501. Gamepads.prototype._onGamepadConnected = function (evt) {
  23502. var newGamepad = this._addNewGamepad(evt.gamepad);
  23503. if (this._callbackGamepadConnected)
  23504. this._callbackGamepadConnected(newGamepad);
  23505. this._startMonitoringGamepads();
  23506. };
  23507. Gamepads.prototype._addNewGamepad = function (gamepad) {
  23508. if (!this.oneGamepadConnected) {
  23509. this.oneGamepadConnected = true;
  23510. if (Gamepads.gamepadDOMInfo) {
  23511. document.body.removeChild(Gamepads.gamepadDOMInfo);
  23512. Gamepads.gamepadDOMInfo = null;
  23513. }
  23514. }
  23515. var newGamepad;
  23516. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  23517. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  23518. }
  23519. else {
  23520. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  23521. }
  23522. this.babylonGamepads.push(newGamepad);
  23523. return newGamepad;
  23524. };
  23525. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  23526. for (var i in this.babylonGamepads) {
  23527. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  23528. this.babylonGamepads.splice(i, 1);
  23529. break;
  23530. }
  23531. }
  23532. // If no gamepads are left, stop the polling loop.
  23533. if (this.babylonGamepads.length == 0) {
  23534. this._stopMonitoringGamepads();
  23535. }
  23536. };
  23537. Gamepads.prototype._startMonitoringGamepads = function () {
  23538. if (!this.isMonitoring) {
  23539. this.isMonitoring = true;
  23540. this._checkGamepadsStatus();
  23541. }
  23542. };
  23543. Gamepads.prototype._stopMonitoringGamepads = function () {
  23544. this.isMonitoring = false;
  23545. };
  23546. Gamepads.prototype._checkGamepadsStatus = function () {
  23547. var _this = this;
  23548. // updating gamepad objects
  23549. this._updateGamepadObjects();
  23550. for (var i in this.babylonGamepads) {
  23551. this.babylonGamepads[i].update();
  23552. }
  23553. if (this.isMonitoring) {
  23554. if (window.requestAnimationFrame) {
  23555. window.requestAnimationFrame(function () {
  23556. _this._checkGamepadsStatus();
  23557. });
  23558. }
  23559. else if (window.mozRequestAnimationFrame) {
  23560. window.mozRequestAnimationFrame(function () {
  23561. _this._checkGamepadsStatus();
  23562. });
  23563. }
  23564. else if (window.webkitRequestAnimationFrame) {
  23565. window.webkitRequestAnimationFrame(function () {
  23566. _this._checkGamepadsStatus();
  23567. });
  23568. }
  23569. }
  23570. };
  23571. // This function is called only on Chrome, which does not yet support
  23572. // connection/disconnection events, but requires you to monitor
  23573. // an array for changes.
  23574. Gamepads.prototype._updateGamepadObjects = function () {
  23575. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  23576. for (var i = 0; i < gamepads.length; i++) {
  23577. if (gamepads[i]) {
  23578. if (!(gamepads[i].index in this.babylonGamepads)) {
  23579. var newGamepad = this._addNewGamepad(gamepads[i]);
  23580. if (this._callbackGamepadConnected) {
  23581. this._callbackGamepadConnected(newGamepad);
  23582. }
  23583. }
  23584. else {
  23585. this.babylonGamepads[i].browserGamepad = gamepads[i];
  23586. }
  23587. }
  23588. }
  23589. };
  23590. return Gamepads;
  23591. })();
  23592. BABYLON.Gamepads = Gamepads;
  23593. var StickValues = (function () {
  23594. function StickValues(x, y) {
  23595. this.x = x;
  23596. this.y = y;
  23597. }
  23598. return StickValues;
  23599. })();
  23600. BABYLON.StickValues = StickValues;
  23601. var Gamepad = (function () {
  23602. function Gamepad(id, index, browserGamepad) {
  23603. this.id = id;
  23604. this.index = index;
  23605. this.browserGamepad = browserGamepad;
  23606. if (this.browserGamepad.axes.length >= 2) {
  23607. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23608. }
  23609. if (this.browserGamepad.axes.length >= 4) {
  23610. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23611. }
  23612. }
  23613. Gamepad.prototype.onleftstickchanged = function (callback) {
  23614. this._onleftstickchanged = callback;
  23615. };
  23616. Gamepad.prototype.onrightstickchanged = function (callback) {
  23617. this._onrightstickchanged = callback;
  23618. };
  23619. Object.defineProperty(Gamepad.prototype, "leftStick", {
  23620. get: function () {
  23621. return this._leftStick;
  23622. },
  23623. set: function (newValues) {
  23624. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  23625. this._onleftstickchanged(newValues);
  23626. }
  23627. this._leftStick = newValues;
  23628. },
  23629. enumerable: true,
  23630. configurable: true
  23631. });
  23632. Object.defineProperty(Gamepad.prototype, "rightStick", {
  23633. get: function () {
  23634. return this._rightStick;
  23635. },
  23636. set: function (newValues) {
  23637. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  23638. this._onrightstickchanged(newValues);
  23639. }
  23640. this._rightStick = newValues;
  23641. },
  23642. enumerable: true,
  23643. configurable: true
  23644. });
  23645. Gamepad.prototype.update = function () {
  23646. if (this._leftStick) {
  23647. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  23648. }
  23649. if (this._rightStick) {
  23650. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  23651. }
  23652. };
  23653. return Gamepad;
  23654. })();
  23655. BABYLON.Gamepad = Gamepad;
  23656. var GenericPad = (function (_super) {
  23657. __extends(GenericPad, _super);
  23658. function GenericPad(id, index, gamepad) {
  23659. _super.call(this, id, index, gamepad);
  23660. this.id = id;
  23661. this.index = index;
  23662. this.gamepad = gamepad;
  23663. this._buttons = new Array(gamepad.buttons.length);
  23664. }
  23665. GenericPad.prototype.onbuttondown = function (callback) {
  23666. this._onbuttondown = callback;
  23667. };
  23668. GenericPad.prototype.onbuttonup = function (callback) {
  23669. this._onbuttonup = callback;
  23670. };
  23671. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  23672. if (newValue !== currentValue) {
  23673. if (this._onbuttondown && newValue === 1) {
  23674. this._onbuttondown(buttonIndex);
  23675. }
  23676. if (this._onbuttonup && newValue === 0) {
  23677. this._onbuttonup(buttonIndex);
  23678. }
  23679. }
  23680. return newValue;
  23681. };
  23682. GenericPad.prototype.update = function () {
  23683. _super.prototype.update.call(this);
  23684. for (var index = 0; index < this._buttons.length; index++) {
  23685. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  23686. }
  23687. };
  23688. return GenericPad;
  23689. })(Gamepad);
  23690. BABYLON.GenericPad = GenericPad;
  23691. (function (Xbox360Button) {
  23692. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  23693. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  23694. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  23695. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  23696. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  23697. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  23698. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  23699. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  23700. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  23701. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  23702. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  23703. var Xbox360Button = BABYLON.Xbox360Button;
  23704. (function (Xbox360Dpad) {
  23705. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  23706. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  23707. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  23708. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  23709. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  23710. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  23711. var Xbox360Pad = (function (_super) {
  23712. __extends(Xbox360Pad, _super);
  23713. function Xbox360Pad() {
  23714. _super.apply(this, arguments);
  23715. this._leftTrigger = 0;
  23716. this._rightTrigger = 0;
  23717. this._buttonA = 0;
  23718. this._buttonB = 0;
  23719. this._buttonX = 0;
  23720. this._buttonY = 0;
  23721. this._buttonBack = 0;
  23722. this._buttonStart = 0;
  23723. this._buttonLB = 0;
  23724. this._buttonRB = 0;
  23725. this._buttonLeftStick = 0;
  23726. this._buttonRightStick = 0;
  23727. this._dPadUp = 0;
  23728. this._dPadDown = 0;
  23729. this._dPadLeft = 0;
  23730. this._dPadRight = 0;
  23731. }
  23732. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  23733. this._onlefttriggerchanged = callback;
  23734. };
  23735. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  23736. this._onrighttriggerchanged = callback;
  23737. };
  23738. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  23739. get: function () {
  23740. return this._leftTrigger;
  23741. },
  23742. set: function (newValue) {
  23743. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  23744. this._onlefttriggerchanged(newValue);
  23745. }
  23746. this._leftTrigger = newValue;
  23747. },
  23748. enumerable: true,
  23749. configurable: true
  23750. });
  23751. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  23752. get: function () {
  23753. return this._rightTrigger;
  23754. },
  23755. set: function (newValue) {
  23756. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  23757. this._onrighttriggerchanged(newValue);
  23758. }
  23759. this._rightTrigger = newValue;
  23760. },
  23761. enumerable: true,
  23762. configurable: true
  23763. });
  23764. Xbox360Pad.prototype.onbuttondown = function (callback) {
  23765. this._onbuttondown = callback;
  23766. };
  23767. Xbox360Pad.prototype.onbuttonup = function (callback) {
  23768. this._onbuttonup = callback;
  23769. };
  23770. Xbox360Pad.prototype.ondpaddown = function (callback) {
  23771. this._ondpaddown = callback;
  23772. };
  23773. Xbox360Pad.prototype.ondpadup = function (callback) {
  23774. this._ondpadup = callback;
  23775. };
  23776. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  23777. if (newValue !== currentValue) {
  23778. if (this._onbuttondown && newValue === 1) {
  23779. this._onbuttondown(buttonType);
  23780. }
  23781. if (this._onbuttonup && newValue === 0) {
  23782. this._onbuttonup(buttonType);
  23783. }
  23784. }
  23785. return newValue;
  23786. };
  23787. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  23788. if (newValue !== currentValue) {
  23789. if (this._ondpaddown && newValue === 1) {
  23790. this._ondpaddown(buttonType);
  23791. }
  23792. if (this._ondpadup && newValue === 0) {
  23793. this._ondpadup(buttonType);
  23794. }
  23795. }
  23796. return newValue;
  23797. };
  23798. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  23799. get: function () {
  23800. return this._buttonA;
  23801. },
  23802. set: function (value) {
  23803. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  23804. },
  23805. enumerable: true,
  23806. configurable: true
  23807. });
  23808. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  23809. get: function () {
  23810. return this._buttonB;
  23811. },
  23812. set: function (value) {
  23813. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  23814. },
  23815. enumerable: true,
  23816. configurable: true
  23817. });
  23818. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  23819. get: function () {
  23820. return this._buttonX;
  23821. },
  23822. set: function (value) {
  23823. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  23824. },
  23825. enumerable: true,
  23826. configurable: true
  23827. });
  23828. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  23829. get: function () {
  23830. return this._buttonY;
  23831. },
  23832. set: function (value) {
  23833. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  23834. },
  23835. enumerable: true,
  23836. configurable: true
  23837. });
  23838. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  23839. get: function () {
  23840. return this._buttonStart;
  23841. },
  23842. set: function (value) {
  23843. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  23844. },
  23845. enumerable: true,
  23846. configurable: true
  23847. });
  23848. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  23849. get: function () {
  23850. return this._buttonBack;
  23851. },
  23852. set: function (value) {
  23853. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  23854. },
  23855. enumerable: true,
  23856. configurable: true
  23857. });
  23858. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  23859. get: function () {
  23860. return this._buttonLB;
  23861. },
  23862. set: function (value) {
  23863. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  23864. },
  23865. enumerable: true,
  23866. configurable: true
  23867. });
  23868. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  23869. get: function () {
  23870. return this._buttonRB;
  23871. },
  23872. set: function (value) {
  23873. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  23874. },
  23875. enumerable: true,
  23876. configurable: true
  23877. });
  23878. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  23879. get: function () {
  23880. return this._buttonLeftStick;
  23881. },
  23882. set: function (value) {
  23883. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  23884. },
  23885. enumerable: true,
  23886. configurable: true
  23887. });
  23888. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  23889. get: function () {
  23890. return this._buttonRightStick;
  23891. },
  23892. set: function (value) {
  23893. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  23894. },
  23895. enumerable: true,
  23896. configurable: true
  23897. });
  23898. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  23899. get: function () {
  23900. return this._dPadUp;
  23901. },
  23902. set: function (value) {
  23903. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  23904. },
  23905. enumerable: true,
  23906. configurable: true
  23907. });
  23908. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  23909. get: function () {
  23910. return this._dPadDown;
  23911. },
  23912. set: function (value) {
  23913. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  23914. },
  23915. enumerable: true,
  23916. configurable: true
  23917. });
  23918. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  23919. get: function () {
  23920. return this._dPadLeft;
  23921. },
  23922. set: function (value) {
  23923. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  23924. },
  23925. enumerable: true,
  23926. configurable: true
  23927. });
  23928. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  23929. get: function () {
  23930. return this._dPadRight;
  23931. },
  23932. set: function (value) {
  23933. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  23934. },
  23935. enumerable: true,
  23936. configurable: true
  23937. });
  23938. Xbox360Pad.prototype.update = function () {
  23939. _super.prototype.update.call(this);
  23940. this.buttonA = this.browserGamepad.buttons[0].value;
  23941. this.buttonB = this.browserGamepad.buttons[1].value;
  23942. this.buttonX = this.browserGamepad.buttons[2].value;
  23943. this.buttonY = this.browserGamepad.buttons[3].value;
  23944. this.buttonLB = this.browserGamepad.buttons[4].value;
  23945. this.buttonRB = this.browserGamepad.buttons[5].value;
  23946. this.leftTrigger = this.browserGamepad.buttons[6].value;
  23947. this.rightTrigger = this.browserGamepad.buttons[7].value;
  23948. this.buttonBack = this.browserGamepad.buttons[8].value;
  23949. this.buttonStart = this.browserGamepad.buttons[9].value;
  23950. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  23951. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  23952. this.dPadUp = this.browserGamepad.buttons[12].value;
  23953. this.dPadDown = this.browserGamepad.buttons[13].value;
  23954. this.dPadLeft = this.browserGamepad.buttons[14].value;
  23955. this.dPadRight = this.browserGamepad.buttons[15].value;
  23956. };
  23957. return Xbox360Pad;
  23958. })(Gamepad);
  23959. BABYLON.Xbox360Pad = Xbox360Pad;
  23960. })(BABYLON || (BABYLON = {}));
  23961. //# sourceMappingURL=babylon.gamepads.js.map
  23962. var BABYLON;
  23963. (function (BABYLON) {
  23964. // We're mainly based on the logic defined into the FreeCamera code
  23965. var GamepadCamera = (function (_super) {
  23966. __extends(GamepadCamera, _super);
  23967. function GamepadCamera(name, position, scene) {
  23968. var _this = this;
  23969. _super.call(this, name, position, scene);
  23970. this.angularSensibility = 200;
  23971. this.moveSensibility = 75;
  23972. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  23973. _this._onNewGameConnected(gamepad);
  23974. });
  23975. }
  23976. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  23977. // Only the first gamepad can control the camera
  23978. if (gamepad.index === 0) {
  23979. this._gamepad = gamepad;
  23980. }
  23981. };
  23982. GamepadCamera.prototype._checkInputs = function () {
  23983. if (!this._gamepad) {
  23984. return;
  23985. }
  23986. var LSValues = this._gamepad.leftStick;
  23987. var normalizedLX = LSValues.x / this.moveSensibility;
  23988. var normalizedLY = LSValues.y / this.moveSensibility;
  23989. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  23990. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  23991. var RSValues = this._gamepad.rightStick;
  23992. var normalizedRX = RSValues.x / this.angularSensibility;
  23993. var normalizedRY = RSValues.y / this.angularSensibility;
  23994. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  23995. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  23996. ;
  23997. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  23998. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  23999. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  24000. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  24001. };
  24002. GamepadCamera.prototype.dispose = function () {
  24003. this._gamepads.dispose();
  24004. _super.prototype.dispose.call(this);
  24005. };
  24006. return GamepadCamera;
  24007. })(BABYLON.FreeCamera);
  24008. BABYLON.GamepadCamera = GamepadCamera;
  24009. })(BABYLON || (BABYLON = {}));
  24010. //# sourceMappingURL=babylon.gamepadCamera.js.map
  24011. var BABYLON;
  24012. (function (BABYLON) {
  24013. var LinesMesh = (function (_super) {
  24014. __extends(LinesMesh, _super);
  24015. function LinesMesh(name, scene, updatable) {
  24016. if (updatable === void 0) { updatable = false; }
  24017. _super.call(this, name, scene);
  24018. this.color = new BABYLON.Color3(1, 1, 1);
  24019. this.alpha = 1;
  24020. this._indices = new Array();
  24021. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  24022. attributes: ["position"],
  24023. uniforms: ["worldViewProjection", "color"],
  24024. needAlphaBlending: true
  24025. });
  24026. }
  24027. Object.defineProperty(LinesMesh.prototype, "material", {
  24028. get: function () {
  24029. return this._colorShader;
  24030. },
  24031. enumerable: true,
  24032. configurable: true
  24033. });
  24034. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  24035. get: function () {
  24036. return false;
  24037. },
  24038. enumerable: true,
  24039. configurable: true
  24040. });
  24041. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  24042. get: function () {
  24043. return false;
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  24049. var engine = this.getScene().getEngine();
  24050. var indexToBind = this._geometry.getIndexBuffer();
  24051. // VBOs
  24052. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  24053. // Color
  24054. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  24055. };
  24056. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  24057. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  24058. return;
  24059. }
  24060. var engine = this.getScene().getEngine();
  24061. // Draw order
  24062. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  24063. };
  24064. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  24065. return null;
  24066. };
  24067. LinesMesh.prototype.dispose = function (doNotRecurse) {
  24068. this._colorShader.dispose();
  24069. _super.prototype.dispose.call(this, doNotRecurse);
  24070. };
  24071. return LinesMesh;
  24072. })(BABYLON.Mesh);
  24073. BABYLON.LinesMesh = LinesMesh;
  24074. })(BABYLON || (BABYLON = {}));
  24075. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  24076. (function (BABYLON) {
  24077. var OutlineRenderer = (function () {
  24078. function OutlineRenderer(scene) {
  24079. this._scene = scene;
  24080. }
  24081. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  24082. if (useOverlay === void 0) { useOverlay = false; }
  24083. var scene = this._scene;
  24084. var engine = this._scene.getEngine();
  24085. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  24086. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  24087. return;
  24088. }
  24089. var mesh = subMesh.getRenderingMesh();
  24090. var material = subMesh.getMaterial();
  24091. engine.enableEffect(this._effect);
  24092. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  24093. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  24094. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  24095. // Bones
  24096. var useBones = mesh.skeleton && scene.skeletonsEnabled && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  24097. if (useBones) {
  24098. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  24099. }
  24100. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  24101. // Alpha test
  24102. if (material && material.needAlphaTesting()) {
  24103. var alphaTexture = material.getAlphaTestTexture();
  24104. this._effect.setTexture("diffuseSampler", alphaTexture);
  24105. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  24106. }
  24107. if (hardwareInstancedRendering) {
  24108. mesh._renderWithInstances(subMesh, BABYLON.Material.TriangleFillMode, batch, this._effect, engine);
  24109. }
  24110. else {
  24111. if (batch.renderSelf[subMesh._id]) {
  24112. this._effect.setMatrix("world", mesh.getWorldMatrix());
  24113. // Draw
  24114. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24115. }
  24116. if (batch.visibleInstances[subMesh._id]) {
  24117. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  24118. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  24119. this._effect.setMatrix("world", instance.getWorldMatrix());
  24120. // Draw
  24121. mesh._draw(subMesh, BABYLON.Material.TriangleFillMode);
  24122. }
  24123. }
  24124. }
  24125. };
  24126. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  24127. var defines = [];
  24128. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  24129. var mesh = subMesh.getMesh();
  24130. var material = subMesh.getMaterial();
  24131. // Alpha test
  24132. if (material && material.needAlphaTesting()) {
  24133. defines.push("#define ALPHATEST");
  24134. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  24135. attribs.push(BABYLON.VertexBuffer.UVKind);
  24136. defines.push("#define UV1");
  24137. }
  24138. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  24139. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  24140. defines.push("#define UV2");
  24141. }
  24142. }
  24143. // Bones
  24144. if (mesh.skeleton && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  24145. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24146. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24147. defines.push("#define BONES");
  24148. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  24149. }
  24150. // Instances
  24151. if (useInstances) {
  24152. defines.push("#define INSTANCES");
  24153. attribs.push("world0");
  24154. attribs.push("world1");
  24155. attribs.push("world2");
  24156. attribs.push("world3");
  24157. }
  24158. // Get correct effect
  24159. var join = defines.join("\n");
  24160. if (this._cachedDefines != join) {
  24161. this._cachedDefines = join;
  24162. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  24163. }
  24164. return this._effect.isReady();
  24165. };
  24166. return OutlineRenderer;
  24167. })();
  24168. BABYLON.OutlineRenderer = OutlineRenderer;
  24169. })(BABYLON || (BABYLON = {}));
  24170. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  24171. (function (BABYLON) {
  24172. var MeshAssetTask = (function () {
  24173. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  24174. this.name = name;
  24175. this.meshesNames = meshesNames;
  24176. this.rootUrl = rootUrl;
  24177. this.sceneFilename = sceneFilename;
  24178. this.isCompleted = false;
  24179. }
  24180. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24181. var _this = this;
  24182. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  24183. _this.loadedMeshes = meshes;
  24184. _this.loadedParticleSystems = particleSystems;
  24185. _this.loadedSkeletons = skeletons;
  24186. _this.isCompleted = true;
  24187. if (_this.onSuccess) {
  24188. _this.onSuccess(_this);
  24189. }
  24190. onSuccess();
  24191. }, null, function () {
  24192. if (_this.onError) {
  24193. _this.onError(_this);
  24194. }
  24195. onError();
  24196. });
  24197. };
  24198. return MeshAssetTask;
  24199. })();
  24200. BABYLON.MeshAssetTask = MeshAssetTask;
  24201. var TextFileAssetTask = (function () {
  24202. function TextFileAssetTask(name, url) {
  24203. this.name = name;
  24204. this.url = url;
  24205. this.isCompleted = false;
  24206. }
  24207. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24208. var _this = this;
  24209. BABYLON.Tools.LoadFile(this.url, function (data) {
  24210. _this.text = data;
  24211. _this.isCompleted = true;
  24212. if (_this.onSuccess) {
  24213. _this.onSuccess(_this);
  24214. }
  24215. onSuccess();
  24216. }, null, scene.database, false, function () {
  24217. if (_this.onError) {
  24218. _this.onError(_this);
  24219. }
  24220. onError();
  24221. });
  24222. };
  24223. return TextFileAssetTask;
  24224. })();
  24225. BABYLON.TextFileAssetTask = TextFileAssetTask;
  24226. var BinaryFileAssetTask = (function () {
  24227. function BinaryFileAssetTask(name, url) {
  24228. this.name = name;
  24229. this.url = url;
  24230. this.isCompleted = false;
  24231. }
  24232. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24233. var _this = this;
  24234. BABYLON.Tools.LoadFile(this.url, function (data) {
  24235. _this.data = data;
  24236. _this.isCompleted = true;
  24237. if (_this.onSuccess) {
  24238. _this.onSuccess(_this);
  24239. }
  24240. onSuccess();
  24241. }, null, scene.database, true, function () {
  24242. if (_this.onError) {
  24243. _this.onError(_this);
  24244. }
  24245. onError();
  24246. });
  24247. };
  24248. return BinaryFileAssetTask;
  24249. })();
  24250. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  24251. var ImageAssetTask = (function () {
  24252. function ImageAssetTask(name, url) {
  24253. this.name = name;
  24254. this.url = url;
  24255. this.isCompleted = false;
  24256. }
  24257. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24258. var _this = this;
  24259. var img = new Image();
  24260. img.onload = function () {
  24261. _this.image = img;
  24262. _this.isCompleted = true;
  24263. if (_this.onSuccess) {
  24264. _this.onSuccess(_this);
  24265. }
  24266. onSuccess();
  24267. };
  24268. img.onerror = function () {
  24269. if (_this.onError) {
  24270. _this.onError(_this);
  24271. }
  24272. onError();
  24273. };
  24274. img.src = this.url;
  24275. };
  24276. return ImageAssetTask;
  24277. })();
  24278. BABYLON.ImageAssetTask = ImageAssetTask;
  24279. var TextureAssetTask = (function () {
  24280. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  24281. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24282. this.name = name;
  24283. this.url = url;
  24284. this.noMipmap = noMipmap;
  24285. this.invertY = invertY;
  24286. this.samplingMode = samplingMode;
  24287. this.isCompleted = false;
  24288. }
  24289. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  24290. var _this = this;
  24291. var onload = function () {
  24292. _this.isCompleted = true;
  24293. if (_this.onSuccess) {
  24294. _this.onSuccess(_this);
  24295. }
  24296. onSuccess();
  24297. };
  24298. var onerror = function () {
  24299. if (_this.onError) {
  24300. _this.onError(_this);
  24301. }
  24302. onError();
  24303. };
  24304. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  24305. };
  24306. return TextureAssetTask;
  24307. })();
  24308. BABYLON.TextureAssetTask = TextureAssetTask;
  24309. var AssetsManager = (function () {
  24310. function AssetsManager(scene) {
  24311. this._tasks = new Array();
  24312. this._waitingTasksCount = 0;
  24313. this.useDefaultLoadingScreen = true;
  24314. this._scene = scene;
  24315. }
  24316. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  24317. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  24318. this._tasks.push(task);
  24319. return task;
  24320. };
  24321. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  24322. var task = new TextFileAssetTask(taskName, url);
  24323. this._tasks.push(task);
  24324. return task;
  24325. };
  24326. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  24327. var task = new BinaryFileAssetTask(taskName, url);
  24328. this._tasks.push(task);
  24329. return task;
  24330. };
  24331. AssetsManager.prototype.addImageTask = function (taskName, url) {
  24332. var task = new ImageAssetTask(taskName, url);
  24333. this._tasks.push(task);
  24334. return task;
  24335. };
  24336. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  24337. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24338. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  24339. this._tasks.push(task);
  24340. return task;
  24341. };
  24342. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  24343. this._waitingTasksCount--;
  24344. if (this._waitingTasksCount === 0) {
  24345. if (this.onFinish) {
  24346. this.onFinish(this._tasks);
  24347. }
  24348. this._scene.getEngine().hideLoadingUI();
  24349. }
  24350. };
  24351. AssetsManager.prototype._runTask = function (task) {
  24352. var _this = this;
  24353. task.run(this._scene, function () {
  24354. if (_this.onTaskSuccess) {
  24355. _this.onTaskSuccess(task);
  24356. }
  24357. _this._decreaseWaitingTasksCount();
  24358. }, function () {
  24359. if (_this.onTaskError) {
  24360. _this.onTaskError(task);
  24361. }
  24362. _this._decreaseWaitingTasksCount();
  24363. });
  24364. };
  24365. AssetsManager.prototype.reset = function () {
  24366. this._tasks = new Array();
  24367. return this;
  24368. };
  24369. AssetsManager.prototype.load = function () {
  24370. this._waitingTasksCount = this._tasks.length;
  24371. if (this._waitingTasksCount === 0) {
  24372. if (this.onFinish) {
  24373. this.onFinish(this._tasks);
  24374. }
  24375. return this;
  24376. }
  24377. if (this.useDefaultLoadingScreen) {
  24378. this._scene.getEngine().displayLoadingUI();
  24379. }
  24380. for (var index = 0; index < this._tasks.length; index++) {
  24381. var task = this._tasks[index];
  24382. this._runTask(task);
  24383. }
  24384. return this;
  24385. };
  24386. return AssetsManager;
  24387. })();
  24388. BABYLON.AssetsManager = AssetsManager;
  24389. })(BABYLON || (BABYLON = {}));
  24390. //# sourceMappingURL=babylon.assetsManager.js.map
  24391. var BABYLON;
  24392. (function (BABYLON) {
  24393. var VRDeviceOrientationCamera = (function (_super) {
  24394. __extends(VRDeviceOrientationCamera, _super);
  24395. function VRDeviceOrientationCamera(name, position, scene) {
  24396. _super.call(this, name, position, scene);
  24397. this._alpha = 0;
  24398. this._beta = 0;
  24399. this._gamma = 0;
  24400. }
  24401. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  24402. this._alpha = +evt.alpha | 0;
  24403. this._beta = +evt.beta | 0;
  24404. this._gamma = +evt.gamma | 0;
  24405. if (this._gamma < 0) {
  24406. this._gamma = 90 + this._gamma;
  24407. }
  24408. else {
  24409. // Incline it in the correct angle.
  24410. this._gamma = 270 - this._gamma;
  24411. }
  24412. this.rotation.x = this._gamma / 180.0 * Math.PI;
  24413. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  24414. this.rotation.z = this._beta / 180.0 * Math.PI;
  24415. };
  24416. return VRDeviceOrientationCamera;
  24417. })(BABYLON.OculusCamera);
  24418. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  24419. })(BABYLON || (BABYLON = {}));
  24420. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  24421. var BABYLON;
  24422. (function (BABYLON) {
  24423. var WebVRCamera = (function (_super) {
  24424. __extends(WebVRCamera, _super);
  24425. function WebVRCamera(name, position, scene) {
  24426. _super.call(this, name, position, scene);
  24427. this._hmdDevice = null;
  24428. this._sensorDevice = null;
  24429. this._cacheState = null;
  24430. this._cacheQuaternion = new BABYLON.Quaternion();
  24431. this._cacheRotation = BABYLON.Vector3.Zero();
  24432. this._vrEnabled = false;
  24433. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  24434. }
  24435. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  24436. var size = devices.length;
  24437. var i = 0;
  24438. // Reset devices.
  24439. this._sensorDevice = null;
  24440. this._hmdDevice = null;
  24441. while (i < size && this._hmdDevice === null) {
  24442. if (devices[i] instanceof HMDVRDevice) {
  24443. this._hmdDevice = devices[i];
  24444. }
  24445. i++;
  24446. }
  24447. i = 0;
  24448. while (i < size && this._sensorDevice === null) {
  24449. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  24450. this._sensorDevice = devices[i];
  24451. }
  24452. i++;
  24453. }
  24454. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  24455. };
  24456. WebVRCamera.prototype._update = function () {
  24457. if (this._vrEnabled) {
  24458. this._cacheState = this._sensorDevice.getState();
  24459. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  24460. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  24461. this.rotation.x = -this._cacheRotation.z;
  24462. this.rotation.y = -this._cacheRotation.y;
  24463. this.rotation.z = this._cacheRotation.x;
  24464. }
  24465. _super.prototype._update.call(this);
  24466. };
  24467. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  24468. _super.prototype.attachControl.call(this, element, noPreventDefault);
  24469. if (navigator.getVRDevices) {
  24470. navigator.getVRDevices().then(this._getWebVRDevices);
  24471. }
  24472. else if (navigator.mozGetVRDevices) {
  24473. navigator.mozGetVRDevices(this._getWebVRDevices);
  24474. }
  24475. };
  24476. WebVRCamera.prototype.detachControl = function (element) {
  24477. _super.prototype.detachControl.call(this, element);
  24478. this._vrEnabled = false;
  24479. };
  24480. return WebVRCamera;
  24481. })(BABYLON.OculusCamera);
  24482. BABYLON.WebVRCamera = WebVRCamera;
  24483. })(BABYLON || (BABYLON = {}));
  24484. //# sourceMappingURL=babylon.webVRCamera.js.map
  24485. var BABYLON;
  24486. (function (BABYLON) {
  24487. // Standard optimizations
  24488. var SceneOptimization = (function () {
  24489. function SceneOptimization(priority) {
  24490. if (priority === void 0) { priority = 0; }
  24491. this.priority = priority;
  24492. this.apply = function (scene) {
  24493. return true; // Return true if everything that can be done was applied
  24494. };
  24495. }
  24496. return SceneOptimization;
  24497. })();
  24498. BABYLON.SceneOptimization = SceneOptimization;
  24499. var TextureOptimization = (function (_super) {
  24500. __extends(TextureOptimization, _super);
  24501. function TextureOptimization(priority, maximumSize) {
  24502. var _this = this;
  24503. if (priority === void 0) { priority = 0; }
  24504. if (maximumSize === void 0) { maximumSize = 1024; }
  24505. _super.call(this, priority);
  24506. this.priority = priority;
  24507. this.maximumSize = maximumSize;
  24508. this.apply = function (scene) {
  24509. var allDone = true;
  24510. for (var index = 0; index < scene.textures.length; index++) {
  24511. var texture = scene.textures[index];
  24512. if (!texture.canRescale) {
  24513. continue;
  24514. }
  24515. var currentSize = texture.getSize();
  24516. var maxDimension = Math.max(currentSize.width, currentSize.height);
  24517. if (maxDimension > _this.maximumSize) {
  24518. texture.scale(0.5);
  24519. allDone = false;
  24520. }
  24521. }
  24522. return allDone;
  24523. };
  24524. }
  24525. return TextureOptimization;
  24526. })(SceneOptimization);
  24527. BABYLON.TextureOptimization = TextureOptimization;
  24528. var HardwareScalingOptimization = (function (_super) {
  24529. __extends(HardwareScalingOptimization, _super);
  24530. function HardwareScalingOptimization(priority, maximumScale) {
  24531. var _this = this;
  24532. if (priority === void 0) { priority = 0; }
  24533. if (maximumScale === void 0) { maximumScale = 2; }
  24534. _super.call(this, priority);
  24535. this.priority = priority;
  24536. this.maximumScale = maximumScale;
  24537. this._currentScale = 1;
  24538. this.apply = function (scene) {
  24539. _this._currentScale++;
  24540. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  24541. return _this._currentScale >= _this.maximumScale;
  24542. };
  24543. }
  24544. return HardwareScalingOptimization;
  24545. })(SceneOptimization);
  24546. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  24547. var ShadowsOptimization = (function (_super) {
  24548. __extends(ShadowsOptimization, _super);
  24549. function ShadowsOptimization() {
  24550. _super.apply(this, arguments);
  24551. this.apply = function (scene) {
  24552. scene.shadowsEnabled = false;
  24553. return true;
  24554. };
  24555. }
  24556. return ShadowsOptimization;
  24557. })(SceneOptimization);
  24558. BABYLON.ShadowsOptimization = ShadowsOptimization;
  24559. var PostProcessesOptimization = (function (_super) {
  24560. __extends(PostProcessesOptimization, _super);
  24561. function PostProcessesOptimization() {
  24562. _super.apply(this, arguments);
  24563. this.apply = function (scene) {
  24564. scene.postProcessesEnabled = false;
  24565. return true;
  24566. };
  24567. }
  24568. return PostProcessesOptimization;
  24569. })(SceneOptimization);
  24570. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  24571. var LensFlaresOptimization = (function (_super) {
  24572. __extends(LensFlaresOptimization, _super);
  24573. function LensFlaresOptimization() {
  24574. _super.apply(this, arguments);
  24575. this.apply = function (scene) {
  24576. scene.lensFlaresEnabled = false;
  24577. return true;
  24578. };
  24579. }
  24580. return LensFlaresOptimization;
  24581. })(SceneOptimization);
  24582. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  24583. var ParticlesOptimization = (function (_super) {
  24584. __extends(ParticlesOptimization, _super);
  24585. function ParticlesOptimization() {
  24586. _super.apply(this, arguments);
  24587. this.apply = function (scene) {
  24588. scene.particlesEnabled = false;
  24589. return true;
  24590. };
  24591. }
  24592. return ParticlesOptimization;
  24593. })(SceneOptimization);
  24594. BABYLON.ParticlesOptimization = ParticlesOptimization;
  24595. var RenderTargetsOptimization = (function (_super) {
  24596. __extends(RenderTargetsOptimization, _super);
  24597. function RenderTargetsOptimization() {
  24598. _super.apply(this, arguments);
  24599. this.apply = function (scene) {
  24600. scene.renderTargetsEnabled = false;
  24601. return true;
  24602. };
  24603. }
  24604. return RenderTargetsOptimization;
  24605. })(SceneOptimization);
  24606. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  24607. var MergeMeshesOptimization = (function (_super) {
  24608. __extends(MergeMeshesOptimization, _super);
  24609. function MergeMeshesOptimization() {
  24610. var _this = this;
  24611. _super.apply(this, arguments);
  24612. this._canBeMerged = function (abstractMesh) {
  24613. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  24614. return false;
  24615. }
  24616. var mesh = abstractMesh;
  24617. if (!mesh.isVisible || !mesh.isEnabled()) {
  24618. return false;
  24619. }
  24620. if (mesh.instances.length > 0) {
  24621. return false;
  24622. }
  24623. if (mesh.skeleton || mesh.hasLODLevels) {
  24624. return false;
  24625. }
  24626. return true;
  24627. };
  24628. this.apply = function (scene) {
  24629. var globalPool = scene.meshes.slice(0);
  24630. var globalLength = globalPool.length;
  24631. for (var index = 0; index < globalLength; index++) {
  24632. var currentPool = new Array();
  24633. var current = globalPool[index];
  24634. // Checks
  24635. if (!_this._canBeMerged(current)) {
  24636. continue;
  24637. }
  24638. currentPool.push(current);
  24639. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  24640. var otherMesh = globalPool[subIndex];
  24641. if (!_this._canBeMerged(otherMesh)) {
  24642. continue;
  24643. }
  24644. if (otherMesh.material !== current.material) {
  24645. continue;
  24646. }
  24647. if (otherMesh.checkCollisions !== current.checkCollisions) {
  24648. continue;
  24649. }
  24650. currentPool.push(otherMesh);
  24651. globalLength--;
  24652. globalPool.splice(subIndex, 1);
  24653. subIndex--;
  24654. }
  24655. if (currentPool.length < 2) {
  24656. continue;
  24657. }
  24658. // Merge meshes
  24659. BABYLON.Mesh.MergeMeshes(currentPool);
  24660. }
  24661. return true;
  24662. };
  24663. }
  24664. return MergeMeshesOptimization;
  24665. })(SceneOptimization);
  24666. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  24667. // Options
  24668. var SceneOptimizerOptions = (function () {
  24669. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  24670. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  24671. if (trackerDuration === void 0) { trackerDuration = 2000; }
  24672. this.targetFrameRate = targetFrameRate;
  24673. this.trackerDuration = trackerDuration;
  24674. this.optimizations = new Array();
  24675. }
  24676. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  24677. var result = new SceneOptimizerOptions(targetFrameRate);
  24678. var priority = 0;
  24679. result.optimizations.push(new MergeMeshesOptimization(priority));
  24680. result.optimizations.push(new ShadowsOptimization(priority));
  24681. result.optimizations.push(new LensFlaresOptimization(priority));
  24682. // Next priority
  24683. priority++;
  24684. result.optimizations.push(new PostProcessesOptimization(priority));
  24685. result.optimizations.push(new ParticlesOptimization(priority));
  24686. // Next priority
  24687. priority++;
  24688. result.optimizations.push(new TextureOptimization(priority, 1024));
  24689. return result;
  24690. };
  24691. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  24692. var result = new SceneOptimizerOptions(targetFrameRate);
  24693. var priority = 0;
  24694. result.optimizations.push(new MergeMeshesOptimization(priority));
  24695. result.optimizations.push(new ShadowsOptimization(priority));
  24696. result.optimizations.push(new LensFlaresOptimization(priority));
  24697. // Next priority
  24698. priority++;
  24699. result.optimizations.push(new PostProcessesOptimization(priority));
  24700. result.optimizations.push(new ParticlesOptimization(priority));
  24701. // Next priority
  24702. priority++;
  24703. result.optimizations.push(new TextureOptimization(priority, 512));
  24704. // Next priority
  24705. priority++;
  24706. result.optimizations.push(new RenderTargetsOptimization(priority));
  24707. // Next priority
  24708. priority++;
  24709. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  24710. return result;
  24711. };
  24712. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  24713. var result = new SceneOptimizerOptions(targetFrameRate);
  24714. var priority = 0;
  24715. result.optimizations.push(new MergeMeshesOptimization(priority));
  24716. result.optimizations.push(new ShadowsOptimization(priority));
  24717. result.optimizations.push(new LensFlaresOptimization(priority));
  24718. // Next priority
  24719. priority++;
  24720. result.optimizations.push(new PostProcessesOptimization(priority));
  24721. result.optimizations.push(new ParticlesOptimization(priority));
  24722. // Next priority
  24723. priority++;
  24724. result.optimizations.push(new TextureOptimization(priority, 256));
  24725. // Next priority
  24726. priority++;
  24727. result.optimizations.push(new RenderTargetsOptimization(priority));
  24728. // Next priority
  24729. priority++;
  24730. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  24731. return result;
  24732. };
  24733. return SceneOptimizerOptions;
  24734. })();
  24735. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  24736. // Scene optimizer tool
  24737. var SceneOptimizer = (function () {
  24738. function SceneOptimizer() {
  24739. }
  24740. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  24741. // TODO: add an epsilon
  24742. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  24743. if (onSuccess) {
  24744. onSuccess();
  24745. }
  24746. return;
  24747. }
  24748. // Apply current level of optimizations
  24749. var allDone = true;
  24750. var noOptimizationApplied = true;
  24751. for (var index = 0; index < options.optimizations.length; index++) {
  24752. var optimization = options.optimizations[index];
  24753. if (optimization.priority === currentPriorityLevel) {
  24754. noOptimizationApplied = false;
  24755. allDone = allDone && optimization.apply(scene);
  24756. }
  24757. }
  24758. // If no optimization was applied, this is a failure :(
  24759. if (noOptimizationApplied) {
  24760. if (onFailure) {
  24761. onFailure();
  24762. }
  24763. return;
  24764. }
  24765. // If all optimizations were done, move to next level
  24766. if (allDone) {
  24767. currentPriorityLevel++;
  24768. }
  24769. // Let's the system running for a specific amount of time before checking FPS
  24770. scene.executeWhenReady(function () {
  24771. setTimeout(function () {
  24772. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  24773. }, options.trackerDuration);
  24774. });
  24775. };
  24776. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  24777. if (!options) {
  24778. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  24779. }
  24780. // Let's the system running for a specific amount of time before checking FPS
  24781. scene.executeWhenReady(function () {
  24782. setTimeout(function () {
  24783. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  24784. }, options.trackerDuration);
  24785. });
  24786. };
  24787. return SceneOptimizer;
  24788. })();
  24789. BABYLON.SceneOptimizer = SceneOptimizer;
  24790. })(BABYLON || (BABYLON = {}));
  24791. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  24792. (function (BABYLON) {
  24793. var Internals;
  24794. (function (Internals) {
  24795. var MeshLODLevel = (function () {
  24796. function MeshLODLevel(distance, mesh) {
  24797. this.distance = distance;
  24798. this.mesh = mesh;
  24799. }
  24800. return MeshLODLevel;
  24801. })();
  24802. Internals.MeshLODLevel = MeshLODLevel;
  24803. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  24804. })(BABYLON || (BABYLON = {}));
  24805. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  24806. (function (BABYLON) {
  24807. var AudioEngine = (function () {
  24808. function AudioEngine() {
  24809. this.audioContext = null;
  24810. this.canUseWebAudio = false;
  24811. try {
  24812. if (typeof AudioContext !== 'undefined') {
  24813. this.audioContext = new AudioContext();
  24814. this.canUseWebAudio = true;
  24815. }
  24816. else if (typeof webkitAudioContext !== 'undefined') {
  24817. this.audioContext = new webkitAudioContext();
  24818. this.canUseWebAudio = true;
  24819. }
  24820. }
  24821. catch (e) {
  24822. this.canUseWebAudio = false;
  24823. }
  24824. // create a global volume gain node
  24825. if (this.canUseWebAudio) {
  24826. this.masterGain = this.audioContext.createGain();
  24827. this.masterGain.gain.value = 1;
  24828. this.masterGain.connect(this.audioContext.destination);
  24829. }
  24830. }
  24831. AudioEngine.prototype.getGlobalVolume = function () {
  24832. if (this.canUseWebAudio) {
  24833. return this.masterGain.gain.value;
  24834. }
  24835. else {
  24836. return -1;
  24837. }
  24838. };
  24839. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  24840. if (this.canUseWebAudio) {
  24841. this.masterGain.gain.value = newVolume;
  24842. }
  24843. };
  24844. return AudioEngine;
  24845. })();
  24846. BABYLON.AudioEngine = AudioEngine;
  24847. })(BABYLON || (BABYLON = {}));
  24848. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  24849. (function (BABYLON) {
  24850. var Sound = (function () {
  24851. /**
  24852. * Create a sound and attach it to a scene
  24853. * @param name Name of your sound
  24854. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  24855. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  24856. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  24857. */
  24858. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  24859. var _this = this;
  24860. this.autoplay = false;
  24861. this.loop = false;
  24862. this.useCustomAttenuation = false;
  24863. this.spatialSound = false;
  24864. this.refDistance = 1;
  24865. this.rolloffFactor = 1;
  24866. this.maxDistance = 100;
  24867. this.distanceModel = "linear";
  24868. this.panningModel = "HRTF";
  24869. this.startTime = 0;
  24870. this.startOffset = 0;
  24871. this._position = BABYLON.Vector3.Zero();
  24872. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  24873. this._volume = 1;
  24874. this._isLoaded = false;
  24875. this._isReadyToPlay = false;
  24876. this._isPlaying = false;
  24877. this._isDirectional = false;
  24878. // Used if you'd like to create a directional sound.
  24879. // If not set, the sound will be omnidirectional
  24880. this._coneInnerAngle = 360;
  24881. this._coneOuterAngle = 360;
  24882. this._coneOuterGain = 0;
  24883. this._name = name;
  24884. this._scene = scene;
  24885. this._audioEngine = this._scene.getEngine().getAudioEngine();
  24886. this._readyToPlayCallback = readyToPlayCallback;
  24887. // Default custom attenuation function is a linear attenuation
  24888. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  24889. if (currentDistance < maxDistance) {
  24890. return currentVolume * (1 - currentDistance / maxDistance);
  24891. }
  24892. else {
  24893. return 0;
  24894. }
  24895. };
  24896. if (options) {
  24897. this.autoplay = options.autoplay || false;
  24898. this.loop = options.loop || false;
  24899. this._volume = options.volume || 1;
  24900. this.spatialSound = options.spatialSound || false;
  24901. this.maxDistance = options.maxDistance || 100;
  24902. this.useCustomAttenuation = options.useCustomAttenation || false;
  24903. this.rolloffFactor = options.rolloffFactor || 1;
  24904. this.refDistance = options.refDistance || 1;
  24905. this.distanceModel = options.distanceModel || "linear";
  24906. this.panningModel = options.panningModel || "HRTF";
  24907. }
  24908. if (this._audioEngine.canUseWebAudio) {
  24909. this._soundGain = this._audioEngine.audioContext.createGain();
  24910. this._soundGain.gain.value = this._volume;
  24911. if (this.spatialSound) {
  24912. this._createSpatialParameters();
  24913. }
  24914. else {
  24915. this._audioNode = this._soundGain;
  24916. }
  24917. this._scene.mainSoundTrack.AddSound(this);
  24918. if (typeof (urlOrArrayBuffer) === "string") {
  24919. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  24920. _this._soundLoaded(data);
  24921. }, null, null, true);
  24922. }
  24923. else {
  24924. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  24925. this._soundLoaded(urlOrArrayBuffer);
  24926. }
  24927. else {
  24928. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  24929. }
  24930. }
  24931. }
  24932. }
  24933. Sound.prototype.updateOptions = function (options) {
  24934. if (options) {
  24935. this.loop = options.loop || this.loop;
  24936. this.maxDistance = options.maxDistance || this.maxDistance;
  24937. this.useCustomAttenuation = options.useCustomAttenation || this.useCustomAttenuation;
  24938. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  24939. this.refDistance = options.refDistance || this.refDistance;
  24940. this.distanceModel = options.distanceModel || this.distanceModel;
  24941. this.panningModel = options.panningModel || this.panningModel;
  24942. }
  24943. };
  24944. Sound.prototype._createSpatialParameters = function () {
  24945. this._soundPanner = this._audioEngine.audioContext.createPanner();
  24946. if (this.useCustomAttenuation) {
  24947. // Tricks to disable in a way embedded Web Audio attenuation
  24948. this._soundPanner.distanceModel = "linear";
  24949. this._soundPanner.maxDistance = Number.MAX_VALUE;
  24950. this._soundPanner.refDistance = 1;
  24951. this._soundPanner.rolloffFactor = 1;
  24952. this._soundPanner.panningModel = "HRTF";
  24953. }
  24954. else {
  24955. this._soundPanner.distanceModel = this.distanceModel;
  24956. this._soundPanner.maxDistance = this.maxDistance;
  24957. this._soundPanner.refDistance = this.refDistance;
  24958. this._soundPanner.rolloffFactor = this.rolloffFactor;
  24959. this._soundPanner.panningModel = this.panningModel;
  24960. }
  24961. this._soundPanner.connect(this._soundGain);
  24962. this._audioNode = this._soundPanner;
  24963. };
  24964. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  24965. if (this._audioEngine.canUseWebAudio) {
  24966. this._audioNode.disconnect();
  24967. this._audioNode.connect(soundTrackAudioNode);
  24968. }
  24969. };
  24970. /**
  24971. * Transform this sound into a directional source
  24972. * @param coneInnerAngle Size of the inner cone in degree
  24973. * @param coneOuterAngle Size of the outer cone in degree
  24974. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  24975. */
  24976. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  24977. if (coneOuterAngle < coneInnerAngle) {
  24978. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  24979. return;
  24980. }
  24981. this._coneInnerAngle = coneInnerAngle;
  24982. this._coneOuterAngle = coneOuterAngle;
  24983. this._coneOuterGain = coneOuterGain;
  24984. this._isDirectional = true;
  24985. if (this._isPlaying && this.loop) {
  24986. this.stop();
  24987. this.play();
  24988. }
  24989. };
  24990. Sound.prototype.setPosition = function (newPosition) {
  24991. this._position = newPosition;
  24992. if (this._isPlaying && this.spatialSound) {
  24993. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  24994. }
  24995. };
  24996. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  24997. this._localDirection = newLocalDirection;
  24998. if (this._connectedMesh && this._isPlaying) {
  24999. this._updateDirection();
  25000. }
  25001. };
  25002. Sound.prototype._updateDirection = function () {
  25003. var mat = this._connectedMesh.getWorldMatrix();
  25004. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  25005. direction.normalize();
  25006. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  25007. };
  25008. Sound.prototype.updateDistanceFromListener = function () {
  25009. if (this._connectedMesh && this.useCustomAttenuation) {
  25010. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  25011. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  25012. }
  25013. };
  25014. Sound.prototype.setAttenuationFunction = function (callback) {
  25015. this._customAttenuationFunction = callback;
  25016. };
  25017. /**
  25018. * Play the sound
  25019. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  25020. */
  25021. Sound.prototype.play = function (time) {
  25022. if (this._isReadyToPlay) {
  25023. try {
  25024. var startTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25025. this._soundSource = this._audioEngine.audioContext.createBufferSource();
  25026. this._soundSource.buffer = this._audioBuffer;
  25027. if (this.spatialSound) {
  25028. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  25029. if (this._isDirectional) {
  25030. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  25031. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  25032. this._soundPanner.coneOuterGain = this._coneOuterGain;
  25033. if (this._connectedMesh) {
  25034. this._updateDirection();
  25035. }
  25036. else {
  25037. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  25038. }
  25039. }
  25040. }
  25041. this._soundSource.connect(this._audioNode);
  25042. this._soundSource.loop = this.loop;
  25043. this.startTime = startTime;
  25044. this._soundSource.start(startTime, this.startOffset % this._soundSource.buffer.duration);
  25045. this._isPlaying = true;
  25046. }
  25047. catch (ex) {
  25048. BABYLON.Tools.Error("Error while trying to play audio: " + this._name + ", " + ex.message);
  25049. }
  25050. }
  25051. };
  25052. /**
  25053. * Stop the sound
  25054. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  25055. */
  25056. Sound.prototype.stop = function (time) {
  25057. var stopTime = time ? this._audioEngine.audioContext.currentTime + time : 0;
  25058. this._soundSource.stop(stopTime);
  25059. this._isPlaying = false;
  25060. };
  25061. Sound.prototype.pause = function () {
  25062. this._soundSource.stop(0);
  25063. this.startOffset += this._audioEngine.audioContext.currentTime - this.startTime;
  25064. };
  25065. Sound.prototype.setVolume = function (newVolume) {
  25066. this._volume = newVolume;
  25067. this._soundGain.gain.value = newVolume;
  25068. };
  25069. Sound.prototype.getVolume = function () {
  25070. return this._volume;
  25071. };
  25072. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  25073. var _this = this;
  25074. this._connectedMesh = meshToConnectTo;
  25075. if (!this.spatialSound) {
  25076. this._createSpatialParameters();
  25077. this.spatialSound = true;
  25078. if (this._isPlaying && this.loop) {
  25079. this.stop();
  25080. this.play();
  25081. }
  25082. }
  25083. meshToConnectTo.registerAfterWorldMatrixUpdate(function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); });
  25084. };
  25085. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  25086. this.setPosition(connectedMesh.position);
  25087. if (this._isDirectional && this._isPlaying) {
  25088. this._updateDirection();
  25089. }
  25090. };
  25091. Sound.prototype._soundLoaded = function (audioData) {
  25092. var _this = this;
  25093. this._isLoaded = true;
  25094. this._audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  25095. _this._audioBuffer = buffer;
  25096. _this._isReadyToPlay = true;
  25097. if (_this.autoplay) {
  25098. _this.play();
  25099. }
  25100. if (_this._readyToPlayCallback) {
  25101. _this._readyToPlayCallback();
  25102. }
  25103. }, function (error) {
  25104. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  25105. });
  25106. };
  25107. return Sound;
  25108. })();
  25109. BABYLON.Sound = Sound;
  25110. })(BABYLON || (BABYLON = {}));
  25111. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  25112. (function (BABYLON) {
  25113. var SoundTrack = (function () {
  25114. function SoundTrack(scene, options) {
  25115. this.id = -1;
  25116. this._isMainTrack = false;
  25117. this._scene = scene;
  25118. this._audioEngine = scene.getEngine().getAudioEngine();
  25119. this.soundCollection = new Array();
  25120. if (this._audioEngine.canUseWebAudio) {
  25121. this._trackGain = this._audioEngine.audioContext.createGain();
  25122. //this._trackConvolver = this._audioEngine.audioContext.createConvolver();
  25123. //this._trackConvolver.connect(this._trackGain);
  25124. this._trackGain.connect(this._audioEngine.masterGain);
  25125. if (options) {
  25126. if (options.volume) {
  25127. this._trackGain.gain.value = options.volume;
  25128. }
  25129. if (options.mainTrack) {
  25130. this._isMainTrack = options.mainTrack;
  25131. }
  25132. }
  25133. }
  25134. if (!this._isMainTrack) {
  25135. this._scene.soundTracks.push(this);
  25136. this.id = this._scene.soundTracks.length - 1;
  25137. }
  25138. }
  25139. SoundTrack.prototype.AddSound = function (sound) {
  25140. sound.connectToSoundTrackAudioNode(this._trackGain);
  25141. if (sound.soundTrackId) {
  25142. if (sound.soundTrackId === -1) {
  25143. this._scene.mainSoundTrack.RemoveSound(sound);
  25144. }
  25145. else {
  25146. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  25147. }
  25148. }
  25149. this.soundCollection.push(sound);
  25150. sound.soundTrackId = this.id;
  25151. };
  25152. SoundTrack.prototype.RemoveSound = function (sound) {
  25153. var index = this.soundCollection.indexOf(sound);
  25154. if (index !== -1) {
  25155. this.soundCollection.splice(index, 1);
  25156. }
  25157. };
  25158. SoundTrack.prototype.setVolume = function (newVolume) {
  25159. if (this._audioEngine.canUseWebAudio) {
  25160. this._trackGain.gain.value = newVolume;
  25161. }
  25162. };
  25163. return SoundTrack;
  25164. })();
  25165. BABYLON.SoundTrack = SoundTrack;
  25166. })(BABYLON || (BABYLON = {}));
  25167. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  25168. (function (BABYLON) {
  25169. var DebugLayer = (function () {
  25170. function DebugLayer(scene) {
  25171. var _this = this;
  25172. this._enabled = false;
  25173. this._labelsEnabled = false;
  25174. this._displayStatistics = true;
  25175. this._displayTree = false;
  25176. this._displayLogs = false;
  25177. this._identityMatrix = BABYLON.Matrix.Identity();
  25178. this.axisRatio = 0.02;
  25179. this.accentColor = "orange";
  25180. this._scene = scene;
  25181. this._syncPositions = function () {
  25182. var engine = _this._scene.getEngine();
  25183. var canvasRect = engine.getRenderingCanvasClientRect();
  25184. if (_this._showUI) {
  25185. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  25186. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  25187. _this._statsDiv.style.width = "400px";
  25188. _this._statsDiv.style.height = "auto";
  25189. _this._statsSubsetDiv.style.maxHeight = "240px";
  25190. _this._optionsDiv.style.left = "0px";
  25191. _this._optionsDiv.style.top = "10px";
  25192. _this._optionsDiv.style.width = "200px";
  25193. _this._optionsDiv.style.height = "auto";
  25194. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  25195. _this._logDiv.style.left = "0px";
  25196. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  25197. _this._logDiv.style.width = "600px";
  25198. _this._logDiv.style.height = "160px";
  25199. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  25200. _this._treeDiv.style.top = "10px";
  25201. _this._treeDiv.style.width = "300px";
  25202. _this._treeDiv.style.height = "auto";
  25203. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  25204. }
  25205. _this._globalDiv.style.left = canvasRect.left + "px";
  25206. _this._globalDiv.style.top = canvasRect.top + "px";
  25207. _this._drawingCanvas.style.left = "0px";
  25208. _this._drawingCanvas.style.top = "0px";
  25209. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  25210. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  25211. var devicePixelRatio = window.devicePixelRatio || 1;
  25212. var context = _this._drawingContext;
  25213. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  25214. _this._ratio = devicePixelRatio / backingStoreRatio;
  25215. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  25216. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  25217. };
  25218. this._onCanvasClick = function (evt) {
  25219. _this._clickPosition = {
  25220. x: evt.clientX * _this._ratio,
  25221. y: evt.clientY * _this._ratio
  25222. };
  25223. };
  25224. this._syncData = function () {
  25225. if (_this._showUI) {
  25226. if (_this._displayStatistics) {
  25227. _this._displayStats();
  25228. _this._statsDiv.style.display = "";
  25229. }
  25230. else {
  25231. _this._statsDiv.style.display = "none";
  25232. }
  25233. if (_this._displayLogs) {
  25234. _this._logDiv.style.display = "";
  25235. }
  25236. else {
  25237. _this._logDiv.style.display = "none";
  25238. }
  25239. if (_this._displayTree) {
  25240. _this._treeDiv.style.display = "";
  25241. if (_this._needToRefreshMeshesTree) {
  25242. _this._needToRefreshMeshesTree = false;
  25243. _this._refreshMeshesTreeContent();
  25244. }
  25245. }
  25246. else {
  25247. _this._treeDiv.style.display = "none";
  25248. }
  25249. }
  25250. if (_this._labelsEnabled || !_this._showUI) {
  25251. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  25252. var engine = _this._scene.getEngine();
  25253. var viewport = _this._scene.activeCamera.viewport;
  25254. var globalViewport = viewport.toGlobal(engine);
  25255. // Meshes
  25256. var meshes = _this._scene.getActiveMeshes();
  25257. for (var index = 0; index < meshes.length; index++) {
  25258. var mesh = meshes.data[index];
  25259. var position = mesh.getBoundingInfo().boundingSphere.center;
  25260. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25261. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  25262. _this._renderAxis(projectedPosition, mesh, globalViewport);
  25263. }
  25264. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  25265. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  25266. mesh.renderOverlay = !mesh.renderOverlay;
  25267. }, function () {
  25268. return mesh.renderOverlay ? 'red' : 'black';
  25269. });
  25270. }
  25271. }
  25272. // Cameras
  25273. var cameras = _this._scene.cameras;
  25274. for (index = 0; index < cameras.length; index++) {
  25275. var camera = cameras[index];
  25276. if (camera === _this._scene.activeCamera) {
  25277. continue;
  25278. }
  25279. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._scene.getTransformMatrix(), globalViewport);
  25280. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  25281. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  25282. _this._scene.activeCamera.detachControl(engine.getRenderingCanvas());
  25283. _this._scene.activeCamera = camera;
  25284. _this._scene.activeCamera.attachControl(engine.getRenderingCanvas());
  25285. }, function () {
  25286. return "purple";
  25287. });
  25288. }
  25289. }
  25290. // Lights
  25291. var lights = _this._scene.lights;
  25292. for (index = 0; index < lights.length; index++) {
  25293. var light = lights[index];
  25294. if (light.position) {
  25295. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._scene.getTransformMatrix(), globalViewport);
  25296. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  25297. _this._renderLabel(light.name, projectedPosition, -20, function () {
  25298. light.setEnabled(!light.isEnabled());
  25299. }, function () {
  25300. return light.isEnabled() ? "orange" : "gray";
  25301. });
  25302. }
  25303. }
  25304. }
  25305. }
  25306. _this._clickPosition = undefined;
  25307. };
  25308. }
  25309. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  25310. while (this._treeSubsetDiv.hasChildNodes()) {
  25311. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  25312. }
  25313. // Add meshes
  25314. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  25315. sortedArray.sort(function (a, b) {
  25316. if (a.name === b.name) {
  25317. return 0;
  25318. }
  25319. return (a.name > b.name) ? 1 : -1;
  25320. });
  25321. for (var index = 0; index < sortedArray.length; index++) {
  25322. var mesh = sortedArray[index];
  25323. if (!mesh.isEnabled()) {
  25324. continue;
  25325. }
  25326. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  25327. m.isVisible = element.checked;
  25328. }, mesh);
  25329. }
  25330. };
  25331. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  25332. this._drawingContext.beginPath();
  25333. this._drawingContext.moveTo(zero.x, zero.y);
  25334. this._drawingContext.lineTo(unit.x, unit.y);
  25335. this._drawingContext.strokeStyle = color;
  25336. this._drawingContext.lineWidth = 4;
  25337. this._drawingContext.stroke();
  25338. this._drawingContext.font = "normal 14px Segoe UI";
  25339. this._drawingContext.fillStyle = color;
  25340. this._drawingContext.fillText(label, unitText.x, unitText.y);
  25341. };
  25342. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  25343. var position = mesh.getBoundingInfo().boundingSphere.center;
  25344. var worldMatrix = mesh.getWorldMatrix();
  25345. 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());
  25346. var unit = (unprojectedVector.subtract(position)).length();
  25347. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25348. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25349. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  25350. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25351. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25352. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  25353. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25354. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._scene.getTransformMatrix(), globalViewport);
  25355. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  25356. };
  25357. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  25358. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  25359. this._drawingContext.font = "normal 12px Segoe UI";
  25360. var textMetrics = this._drawingContext.measureText(text);
  25361. var centerX = projectedPosition.x - textMetrics.width / 2;
  25362. var centerY = projectedPosition.y;
  25363. if (this._isClickInsideRect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  25364. onClick();
  25365. }
  25366. this._drawingContext.beginPath();
  25367. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  25368. this._drawingContext.fillStyle = getFillStyle();
  25369. this._drawingContext.globalAlpha = 0.5;
  25370. this._drawingContext.fill();
  25371. this._drawingContext.globalAlpha = 1.0;
  25372. this._drawingContext.strokeStyle = '#FFFFFF';
  25373. this._drawingContext.lineWidth = 1;
  25374. this._drawingContext.stroke();
  25375. this._drawingContext.fillStyle = "#FFFFFF";
  25376. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  25377. this._drawingContext.beginPath();
  25378. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  25379. this._drawingContext.fill();
  25380. }
  25381. };
  25382. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  25383. if (!this._clickPosition) {
  25384. return false;
  25385. }
  25386. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  25387. return false;
  25388. }
  25389. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  25390. return false;
  25391. }
  25392. return true;
  25393. };
  25394. DebugLayer.prototype.isVisible = function () {
  25395. return this._enabled;
  25396. };
  25397. DebugLayer.prototype.hide = function () {
  25398. if (!this._enabled) {
  25399. return;
  25400. }
  25401. this._enabled = false;
  25402. var engine = this._scene.getEngine();
  25403. this._scene.unregisterAfterRender(this._syncData);
  25404. document.body.removeChild(this._globalDiv);
  25405. window.removeEventListener("resize", this._syncPositions);
  25406. this._scene.forceShowBoundingBoxes = false;
  25407. this._scene.forceWireframe = false;
  25408. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  25409. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  25410. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  25411. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  25412. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  25413. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  25414. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  25415. this._scene.shadowsEnabled = true;
  25416. this._scene.particlesEnabled = true;
  25417. this._scene.postProcessesEnabled = true;
  25418. this._scene.collisionsEnabled = true;
  25419. this._scene.lightsEnabled = true;
  25420. this._scene.texturesEnabled = true;
  25421. this._scene.lensFlaresEnabled = true;
  25422. this._scene.proceduralTexturesEnabled = true;
  25423. this._scene.renderTargetsEnabled = true;
  25424. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  25425. };
  25426. DebugLayer.prototype.show = function (showUI) {
  25427. if (showUI === void 0) { showUI = true; }
  25428. if (this._enabled) {
  25429. return;
  25430. }
  25431. this._enabled = true;
  25432. this._showUI = showUI;
  25433. var engine = this._scene.getEngine();
  25434. this._globalDiv = document.createElement("div");
  25435. document.body.appendChild(this._globalDiv);
  25436. this._generateDOMelements();
  25437. window.addEventListener("resize", this._syncPositions);
  25438. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  25439. this._syncPositions();
  25440. this._scene.registerAfterRender(this._syncData);
  25441. };
  25442. DebugLayer.prototype._clearLabels = function () {
  25443. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  25444. for (var index = 0; index < this._scene.meshes.length; index++) {
  25445. var mesh = this._scene.meshes[index];
  25446. mesh.renderOverlay = false;
  25447. }
  25448. };
  25449. DebugLayer.prototype._generateheader = function (root, text) {
  25450. var header = document.createElement("div");
  25451. header.innerHTML = text + "&nbsp;";
  25452. header.style.textAlign = "right";
  25453. header.style.width = "100%";
  25454. header.style.color = "white";
  25455. header.style.backgroundColor = "Black";
  25456. header.style.padding = "5px 5px 4px 0px";
  25457. header.style.marginLeft = "-5px";
  25458. header.style.fontWeight = "bold";
  25459. root.appendChild(header);
  25460. };
  25461. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  25462. var label = document.createElement("label");
  25463. label.innerHTML = title;
  25464. label.style.color = color;
  25465. root.appendChild(label);
  25466. root.appendChild(document.createElement("br"));
  25467. };
  25468. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  25469. if (tag === void 0) { tag = null; }
  25470. var label = document.createElement("label");
  25471. var boundingBoxesCheckbox = document.createElement("input");
  25472. boundingBoxesCheckbox.type = "checkbox";
  25473. boundingBoxesCheckbox.checked = initialState;
  25474. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25475. task(evt.target, tag);
  25476. });
  25477. label.appendChild(boundingBoxesCheckbox);
  25478. var container = document.createElement("span");
  25479. var leftPart = document.createElement("span");
  25480. var rightPart = document.createElement("span");
  25481. rightPart.style.cssFloat = "right";
  25482. leftPart.innerHTML = leftTitle;
  25483. rightPart.innerHTML = rightTitle;
  25484. rightPart.style.fontSize = "12px";
  25485. rightPart.style.maxWidth = "200px";
  25486. container.appendChild(leftPart);
  25487. container.appendChild(rightPart);
  25488. label.appendChild(container);
  25489. root.appendChild(label);
  25490. root.appendChild(document.createElement("br"));
  25491. };
  25492. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  25493. if (tag === void 0) { tag = null; }
  25494. var label = document.createElement("label");
  25495. var boundingBoxesCheckbox = document.createElement("input");
  25496. boundingBoxesCheckbox.type = "checkbox";
  25497. boundingBoxesCheckbox.checked = initialState;
  25498. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  25499. task(evt.target, tag);
  25500. });
  25501. label.appendChild(boundingBoxesCheckbox);
  25502. label.appendChild(document.createTextNode(title));
  25503. root.appendChild(label);
  25504. root.appendChild(document.createElement("br"));
  25505. };
  25506. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  25507. if (tag === void 0) { tag = null; }
  25508. var label = document.createElement("label");
  25509. var boundingBoxesRadio = document.createElement("input");
  25510. boundingBoxesRadio.type = "radio";
  25511. boundingBoxesRadio.name = name;
  25512. boundingBoxesRadio.checked = initialState;
  25513. boundingBoxesRadio.addEventListener("change", function (evt) {
  25514. task(evt.target, tag);
  25515. });
  25516. label.appendChild(boundingBoxesRadio);
  25517. label.appendChild(document.createTextNode(title));
  25518. root.appendChild(label);
  25519. root.appendChild(document.createElement("br"));
  25520. };
  25521. DebugLayer.prototype._generateDOMelements = function () {
  25522. var _this = this;
  25523. this._globalDiv.id = "DebugLayer";
  25524. this._globalDiv.style.position = "absolute";
  25525. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  25526. this._globalDiv.style.fontSize = "14px";
  25527. this._globalDiv.style.color = "white";
  25528. // Drawing canvas
  25529. this._drawingCanvas = document.createElement("canvas");
  25530. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  25531. this._drawingCanvas.style.position = "absolute";
  25532. this._drawingCanvas.style.pointerEvents = "none";
  25533. this._drawingContext = this._drawingCanvas.getContext("2d");
  25534. this._globalDiv.appendChild(this._drawingCanvas);
  25535. if (this._showUI) {
  25536. var background = "rgba(128, 128, 128, 0.4)";
  25537. var border = "rgb(180, 180, 180) solid 1px";
  25538. // Stats
  25539. this._statsDiv = document.createElement("div");
  25540. this._statsDiv.id = "DebugLayerStats";
  25541. this._statsDiv.style.border = border;
  25542. this._statsDiv.style.position = "absolute";
  25543. this._statsDiv.style.background = background;
  25544. this._statsDiv.style.padding = "0px 0px 0px 5px";
  25545. this._generateheader(this._statsDiv, "STATISTICS");
  25546. this._statsSubsetDiv = document.createElement("div");
  25547. this._statsSubsetDiv.style.paddingTop = "5px";
  25548. this._statsSubsetDiv.style.paddingBottom = "5px";
  25549. this._statsSubsetDiv.style.overflowY = "auto";
  25550. this._statsDiv.appendChild(this._statsSubsetDiv);
  25551. // Tree
  25552. this._treeDiv = document.createElement("div");
  25553. this._treeDiv.id = "DebugLayerTree";
  25554. this._treeDiv.style.border = border;
  25555. this._treeDiv.style.position = "absolute";
  25556. this._treeDiv.style.background = background;
  25557. this._treeDiv.style.padding = "0px 0px 0px 5px";
  25558. this._treeDiv.style.display = "none";
  25559. this._generateheader(this._treeDiv, "MESHES TREE");
  25560. this._treeSubsetDiv = document.createElement("div");
  25561. this._treeSubsetDiv.style.paddingTop = "5px";
  25562. this._treeSubsetDiv.style.paddingRight = "5px";
  25563. this._treeSubsetDiv.style.overflowY = "auto";
  25564. this._treeSubsetDiv.style.maxHeight = "300px";
  25565. this._treeDiv.appendChild(this._treeSubsetDiv);
  25566. this._needToRefreshMeshesTree = true;
  25567. // Logs
  25568. this._logDiv = document.createElement("div");
  25569. this._logDiv.style.border = border;
  25570. this._logDiv.id = "DebugLayerLogs";
  25571. this._logDiv.style.position = "absolute";
  25572. this._logDiv.style.background = background;
  25573. this._logDiv.style.padding = "0px 0px 0px 5px";
  25574. this._logDiv.style.display = "none";
  25575. this._generateheader(this._logDiv, "LOGS");
  25576. this._logSubsetDiv = document.createElement("div");
  25577. this._logSubsetDiv.style.height = "127px";
  25578. this._logSubsetDiv.style.paddingTop = "5px";
  25579. this._logSubsetDiv.style.overflowY = "auto";
  25580. this._logSubsetDiv.style.fontSize = "12px";
  25581. this._logSubsetDiv.style.fontFamily = "consolas";
  25582. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  25583. this._logDiv.appendChild(this._logSubsetDiv);
  25584. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  25585. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  25586. };
  25587. // Options
  25588. this._optionsDiv = document.createElement("div");
  25589. this._optionsDiv.id = "DebugLayerOptions";
  25590. this._optionsDiv.style.border = border;
  25591. this._optionsDiv.style.position = "absolute";
  25592. this._optionsDiv.style.background = background;
  25593. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  25594. this._optionsDiv.style.overflowY = "auto";
  25595. this._generateheader(this._optionsDiv, "OPTIONS");
  25596. this._optionsSubsetDiv = document.createElement("div");
  25597. this._optionsSubsetDiv.style.paddingTop = "5px";
  25598. this._optionsSubsetDiv.style.paddingBottom = "5px";
  25599. this._optionsSubsetDiv.style.overflowY = "auto";
  25600. this._optionsSubsetDiv.style.maxHeight = "200px";
  25601. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  25602. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  25603. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  25604. _this._displayStatistics = element.checked;
  25605. });
  25606. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  25607. _this._displayLogs = element.checked;
  25608. });
  25609. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  25610. _this._displayTree = element.checked;
  25611. _this._needToRefreshMeshesTree = true;
  25612. });
  25613. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25614. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  25615. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  25616. _this._scene.forceShowBoundingBoxes = element.checked;
  25617. });
  25618. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  25619. _this._labelsEnabled = element.checked;
  25620. if (!_this._labelsEnabled) {
  25621. _this._clearLabels();
  25622. }
  25623. });
  25624. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  25625. if (element.checked) {
  25626. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  25627. }
  25628. else {
  25629. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  25630. }
  25631. });
  25632. ;
  25633. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25634. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  25635. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  25636. if (element.checked) {
  25637. _this._scene.forceWireframe = false;
  25638. _this._scene.forcePointsCloud = false;
  25639. }
  25640. });
  25641. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  25642. if (element.checked) {
  25643. _this._scene.forceWireframe = true;
  25644. _this._scene.forcePointsCloud = false;
  25645. }
  25646. });
  25647. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  25648. if (element.checked) {
  25649. _this._scene.forceWireframe = false;
  25650. _this._scene.forcePointsCloud = true;
  25651. }
  25652. });
  25653. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25654. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  25655. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  25656. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  25657. });
  25658. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  25659. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  25660. });
  25661. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  25662. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  25663. });
  25664. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  25665. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  25666. });
  25667. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  25668. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  25669. });
  25670. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  25671. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  25672. });
  25673. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  25674. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  25675. });
  25676. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  25677. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  25678. });
  25679. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  25680. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  25681. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  25682. _this._scene.animationsEnabled = element.checked;
  25683. });
  25684. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  25685. _this._scene.collisionsEnabled = element.checked;
  25686. });
  25687. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  25688. _this._scene.fogEnabled = element.checked;
  25689. });
  25690. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  25691. _this._scene.lensFlaresEnabled = element.checked;
  25692. });
  25693. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  25694. _this._scene.lightsEnabled = element.checked;
  25695. });
  25696. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  25697. _this._scene.particlesEnabled = element.checked;
  25698. });
  25699. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  25700. _this._scene.postProcessesEnabled = element.checked;
  25701. });
  25702. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  25703. _this._scene.proceduralTexturesEnabled = element.checked;
  25704. });
  25705. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  25706. _this._scene.renderTargetsEnabled = element.checked;
  25707. });
  25708. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  25709. _this._scene.shadowsEnabled = element.checked;
  25710. });
  25711. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  25712. _this._scene.skeletonsEnabled = element.checked;
  25713. });
  25714. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  25715. _this._scene.texturesEnabled = element.checked;
  25716. });
  25717. this._globalDiv.appendChild(this._statsDiv);
  25718. this._globalDiv.appendChild(this._logDiv);
  25719. this._globalDiv.appendChild(this._optionsDiv);
  25720. this._globalDiv.appendChild(this._treeDiv);
  25721. }
  25722. };
  25723. DebugLayer.prototype._displayStats = function () {
  25724. var scene = this._scene;
  25725. var engine = scene.getEngine();
  25726. var glInfo = engine.getGlInfo();
  25727. 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>";
  25728. if (this.customStatsFunction) {
  25729. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  25730. }
  25731. };
  25732. return DebugLayer;
  25733. })();
  25734. BABYLON.DebugLayer = DebugLayer;
  25735. })(BABYLON || (BABYLON = {}));
  25736. //# sourceMappingURL=babylon.debugLayer.js.map
  25737. var BABYLON;
  25738. (function (BABYLON) {
  25739. var RawTexture = (function (_super) {
  25740. __extends(RawTexture, _super);
  25741. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  25742. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25743. if (invertY === void 0) { invertY = false; }
  25744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25745. _super.call(this, null, scene, !generateMipMaps, invertY);
  25746. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  25747. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25748. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25749. }
  25750. // Statics
  25751. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25752. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25753. if (invertY === void 0) { invertY = false; }
  25754. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25755. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  25756. };
  25757. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25758. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25759. if (invertY === void 0) { invertY = false; }
  25760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25761. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25762. };
  25763. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25764. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25765. if (invertY === void 0) { invertY = false; }
  25766. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25767. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  25768. };
  25769. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25770. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25771. if (invertY === void 0) { invertY = false; }
  25772. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25773. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  25774. };
  25775. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  25776. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25777. if (invertY === void 0) { invertY = false; }
  25778. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25779. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  25780. };
  25781. return RawTexture;
  25782. })(BABYLON.Texture);
  25783. BABYLON.RawTexture = RawTexture;
  25784. })(BABYLON || (BABYLON = {}));
  25785. //# sourceMappingURL=babylon.rawTexture.js.map
  25786. var BABYLON;
  25787. (function (BABYLON) {
  25788. var IndexedVector2 = (function (_super) {
  25789. __extends(IndexedVector2, _super);
  25790. function IndexedVector2(original, index) {
  25791. _super.call(this, original.x, original.y);
  25792. this.index = index;
  25793. }
  25794. return IndexedVector2;
  25795. })(BABYLON.Vector2);
  25796. var PolygonPoints = (function () {
  25797. function PolygonPoints() {
  25798. this.elements = new Array();
  25799. }
  25800. PolygonPoints.prototype.add = function (originalPoints) {
  25801. var _this = this;
  25802. var result = new Array();
  25803. originalPoints.forEach(function (point) {
  25804. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  25805. var newPoint = new IndexedVector2(point, _this.elements.length);
  25806. result.push(newPoint);
  25807. _this.elements.push(newPoint);
  25808. }
  25809. });
  25810. return result;
  25811. };
  25812. PolygonPoints.prototype.computeBounds = function () {
  25813. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25814. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  25815. this.elements.forEach(function (point) {
  25816. // x
  25817. if (point.x < lmin.x) {
  25818. lmin.x = point.x;
  25819. }
  25820. else if (point.x > lmax.x) {
  25821. lmax.x = point.x;
  25822. }
  25823. // y
  25824. if (point.y < lmin.y) {
  25825. lmin.y = point.y;
  25826. }
  25827. else if (point.y > lmax.y) {
  25828. lmax.y = point.y;
  25829. }
  25830. });
  25831. return {
  25832. min: lmin,
  25833. max: lmax,
  25834. width: lmax.x - lmin.x,
  25835. height: lmax.y - lmin.y
  25836. };
  25837. };
  25838. return PolygonPoints;
  25839. })();
  25840. var Polygon = (function () {
  25841. function Polygon() {
  25842. }
  25843. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  25844. return [
  25845. new BABYLON.Vector2(xmin, ymin),
  25846. new BABYLON.Vector2(xmax, ymin),
  25847. new BABYLON.Vector2(xmax, ymax),
  25848. new BABYLON.Vector2(xmin, ymax)
  25849. ];
  25850. };
  25851. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  25852. if (cx === void 0) { cx = 0; }
  25853. if (cy === void 0) { cy = 0; }
  25854. if (numberOfSides === void 0) { numberOfSides = 32; }
  25855. var result = new Array();
  25856. var angle = 0;
  25857. var increment = (Math.PI * 2) / numberOfSides;
  25858. for (var i = 0; i < numberOfSides; i++) {
  25859. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  25860. angle -= increment;
  25861. }
  25862. return result;
  25863. };
  25864. Polygon.Parse = function (input) {
  25865. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  25866. var i, result = [];
  25867. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  25868. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  25869. }
  25870. return result;
  25871. };
  25872. Polygon.StartingAt = function (x, y) {
  25873. return BABYLON.Path2.StartingAt(x, y);
  25874. };
  25875. return Polygon;
  25876. })();
  25877. BABYLON.Polygon = Polygon;
  25878. var PolygonMeshBuilder = (function () {
  25879. function PolygonMeshBuilder(name, contours, scene) {
  25880. this._points = new PolygonPoints();
  25881. if (!("poly2tri" in window)) {
  25882. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  25883. }
  25884. this._name = name;
  25885. this._scene = scene;
  25886. var points;
  25887. if (contours instanceof BABYLON.Path2) {
  25888. points = contours.getPoints();
  25889. }
  25890. else {
  25891. points = contours;
  25892. }
  25893. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  25894. }
  25895. PolygonMeshBuilder.prototype.addHole = function (hole) {
  25896. this._swctx.addHole(this._points.add(hole));
  25897. return this;
  25898. };
  25899. PolygonMeshBuilder.prototype.build = function (updatable) {
  25900. if (updatable === void 0) { updatable = false; }
  25901. var result = new BABYLON.Mesh(this._name, this._scene);
  25902. var normals = [];
  25903. var positions = [];
  25904. var uvs = [];
  25905. var bounds = this._points.computeBounds();
  25906. this._points.elements.forEach(function (p) {
  25907. normals.push(0, 1.0, 0);
  25908. positions.push(p.x, 0, p.y);
  25909. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  25910. });
  25911. var indices = [];
  25912. this._swctx.triangulate();
  25913. this._swctx.getTriangles().forEach(function (triangle) {
  25914. triangle.getPoints().forEach(function (point) {
  25915. indices.push(point.index);
  25916. });
  25917. });
  25918. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  25919. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  25920. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  25921. result.setIndices(indices);
  25922. return result;
  25923. };
  25924. return PolygonMeshBuilder;
  25925. })();
  25926. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  25927. })(BABYLON || (BABYLON = {}));
  25928. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  25929. (function (BABYLON) {
  25930. var SimplificationSettings = (function () {
  25931. function SimplificationSettings(quality, distance) {
  25932. this.quality = quality;
  25933. this.distance = distance;
  25934. }
  25935. return SimplificationSettings;
  25936. })();
  25937. BABYLON.SimplificationSettings = SimplificationSettings;
  25938. /**
  25939. * The implemented types of simplification.
  25940. * At the moment only Quadratic Error Decimation is implemented.
  25941. */
  25942. (function (SimplificationType) {
  25943. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  25944. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  25945. var SimplificationType = BABYLON.SimplificationType;
  25946. var DecimationTriangle = (function () {
  25947. function DecimationTriangle(vertices) {
  25948. this.vertices = vertices;
  25949. this.error = new Array(4);
  25950. this.deleted = false;
  25951. this.isDirty = false;
  25952. this.borderFactor = 0;
  25953. }
  25954. return DecimationTriangle;
  25955. })();
  25956. BABYLON.DecimationTriangle = DecimationTriangle;
  25957. var DecimationVertex = (function () {
  25958. function DecimationVertex(position, normal, uv, id) {
  25959. this.position = position;
  25960. this.normal = normal;
  25961. this.uv = uv;
  25962. this.id = id;
  25963. this.isBorder = true;
  25964. this.q = new QuadraticMatrix();
  25965. this.triangleCount = 0;
  25966. this.triangleStart = 0;
  25967. }
  25968. return DecimationVertex;
  25969. })();
  25970. BABYLON.DecimationVertex = DecimationVertex;
  25971. var QuadraticMatrix = (function () {
  25972. function QuadraticMatrix(data) {
  25973. this.data = new Array(10);
  25974. for (var i = 0; i < 10; ++i) {
  25975. if (data && data[i]) {
  25976. this.data[i] = data[i];
  25977. }
  25978. else {
  25979. this.data[i] = 0;
  25980. }
  25981. }
  25982. }
  25983. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  25984. 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];
  25985. return det;
  25986. };
  25987. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  25988. for (var i = 0; i < 10; ++i) {
  25989. this.data[i] += matrix.data[i];
  25990. }
  25991. };
  25992. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  25993. for (var i = 0; i < 10; ++i) {
  25994. this.data[i] += data[i];
  25995. }
  25996. };
  25997. QuadraticMatrix.prototype.add = function (matrix) {
  25998. var m = new QuadraticMatrix();
  25999. for (var i = 0; i < 10; ++i) {
  26000. m.data[i] = this.data[i] + matrix.data[i];
  26001. }
  26002. return m;
  26003. };
  26004. QuadraticMatrix.FromData = function (a, b, c, d) {
  26005. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  26006. };
  26007. //returning an array to avoid garbage collection
  26008. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  26009. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  26010. };
  26011. return QuadraticMatrix;
  26012. })();
  26013. BABYLON.QuadraticMatrix = QuadraticMatrix;
  26014. var Reference = (function () {
  26015. function Reference(vertexId, triangleId) {
  26016. this.vertexId = vertexId;
  26017. this.triangleId = triangleId;
  26018. }
  26019. return Reference;
  26020. })();
  26021. BABYLON.Reference = Reference;
  26022. /**
  26023. * An implementation of the Quadratic Error simplification algorithm.
  26024. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  26025. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  26026. * @author RaananW
  26027. */
  26028. var QuadraticErrorSimplification = (function () {
  26029. function QuadraticErrorSimplification(_mesh) {
  26030. this._mesh = _mesh;
  26031. this.initialised = false;
  26032. this.syncIterations = 5000;
  26033. this.aggressiveness = 7;
  26034. this.decimationIterations = 100;
  26035. }
  26036. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  26037. var _this = this;
  26038. this.initWithMesh(this._mesh, function () {
  26039. _this.runDecimation(settings, successCallback);
  26040. });
  26041. };
  26042. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  26043. var _this = this;
  26044. var targetCount = ~~(this.triangles.length * settings.quality);
  26045. var deletedTriangles = 0;
  26046. var triangleCount = this.triangles.length;
  26047. var iterationFunction = function (iteration, callback) {
  26048. setTimeout(function () {
  26049. if (iteration % 5 === 0) {
  26050. _this.updateMesh(iteration === 0);
  26051. }
  26052. for (var i = 0; i < _this.triangles.length; ++i) {
  26053. _this.triangles[i].isDirty = false;
  26054. }
  26055. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  26056. var trianglesIterator = function (i) {
  26057. var tIdx = ((_this.triangles.length / 2) + i) % _this.triangles.length;
  26058. var t = _this.triangles[tIdx];
  26059. if (!t)
  26060. return;
  26061. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  26062. return;
  26063. }
  26064. for (var j = 0; j < 3; ++j) {
  26065. if (t.error[j] < threshold) {
  26066. var deleted0 = [];
  26067. var deleted1 = [];
  26068. var i0 = t.vertices[j];
  26069. var i1 = t.vertices[(j + 1) % 3];
  26070. var v0 = _this.vertices[i0];
  26071. var v1 = _this.vertices[i1];
  26072. if (v0.isBorder !== v1.isBorder)
  26073. continue;
  26074. var p = BABYLON.Vector3.Zero();
  26075. var n = BABYLON.Vector3.Zero();
  26076. var uv = BABYLON.Vector2.Zero();
  26077. _this.calculateError(v0, v1, p, n, uv);
  26078. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor))
  26079. continue;
  26080. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor))
  26081. continue;
  26082. v0.position = p;
  26083. v0.normal = n;
  26084. v0.uv = uv;
  26085. v0.q = v1.q.add(v0.q);
  26086. var tStart = _this.references.length;
  26087. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  26088. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  26089. var tCount = _this.references.length - tStart;
  26090. if (tCount <= v0.triangleCount) {
  26091. if (tCount) {
  26092. for (var c = 0; c < tCount; c++) {
  26093. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  26094. }
  26095. }
  26096. }
  26097. else {
  26098. v0.triangleStart = tStart;
  26099. }
  26100. v0.triangleCount = tCount;
  26101. break;
  26102. }
  26103. }
  26104. };
  26105. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  26106. return (triangleCount - deletedTriangles <= targetCount);
  26107. });
  26108. }, 0);
  26109. };
  26110. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  26111. if (triangleCount - deletedTriangles <= targetCount)
  26112. loop.breakLoop();
  26113. else {
  26114. iterationFunction(loop.index, function () {
  26115. loop.executeNext();
  26116. });
  26117. }
  26118. }, function () {
  26119. setTimeout(function () {
  26120. successCallback(_this.reconstructMesh());
  26121. }, 0);
  26122. });
  26123. };
  26124. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  26125. var _this = this;
  26126. if (!mesh)
  26127. return;
  26128. this.vertices = [];
  26129. this.triangles = [];
  26130. this._mesh = mesh;
  26131. //It is assumed that a mesh has positions, normals and either uvs or colors.
  26132. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  26133. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  26134. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  26135. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  26136. var indices = mesh.getIndices();
  26137. var vertexInit = function (i) {
  26138. var uv;
  26139. if (uvs[i * 2]) {
  26140. uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  26141. }
  26142. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), uv, i);
  26143. if (!uv && colorsData[i * 3]) {
  26144. vertex.color = BABYLON.Color3.FromArray(colorsData, i * 3);
  26145. }
  26146. _this.vertices.push(vertex);
  26147. };
  26148. var totalVertices = mesh.getTotalVertices();
  26149. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  26150. var indicesInit = function (i) {
  26151. var pos = i * 3;
  26152. var i0 = indices[pos + 0];
  26153. var i1 = indices[pos + 1];
  26154. var i2 = indices[pos + 2];
  26155. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  26156. _this.triangles.push(triangle);
  26157. };
  26158. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  26159. _this.init(callback);
  26160. });
  26161. });
  26162. };
  26163. QuadraticErrorSimplification.prototype.init = function (callback) {
  26164. var _this = this;
  26165. var triangleInit1 = function (i) {
  26166. var t = _this.triangles[i];
  26167. 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();
  26168. for (var j = 0; j < 3; j++) {
  26169. _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))));
  26170. }
  26171. };
  26172. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  26173. var triangleInit2 = function (i) {
  26174. var t = _this.triangles[i];
  26175. for (var j = 0; j < 3; ++j) {
  26176. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  26177. }
  26178. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26179. };
  26180. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  26181. _this.initialised = true;
  26182. callback();
  26183. });
  26184. });
  26185. };
  26186. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  26187. var newTriangles = [];
  26188. var i;
  26189. for (i = 0; i < this.vertices.length; ++i) {
  26190. this.vertices[i].triangleCount = 0;
  26191. }
  26192. var t;
  26193. var j;
  26194. for (i = 0; i < this.triangles.length; ++i) {
  26195. if (!this.triangles[i].deleted) {
  26196. t = this.triangles[i];
  26197. for (j = 0; j < 3; ++j) {
  26198. this.vertices[t.vertices[j]].triangleCount = 1;
  26199. }
  26200. newTriangles.push(t);
  26201. }
  26202. }
  26203. var newVerticesOrder = [];
  26204. //compact vertices, get the IDs of the vertices used.
  26205. var dst = 0;
  26206. for (i = 0; i < this.vertices.length; ++i) {
  26207. if (this.vertices[i].triangleCount) {
  26208. this.vertices[i].triangleStart = dst;
  26209. this.vertices[dst].position = this.vertices[i].position;
  26210. this.vertices[dst].normal = this.vertices[i].normal;
  26211. this.vertices[dst].uv = this.vertices[i].uv;
  26212. newVerticesOrder.push(i);
  26213. dst++;
  26214. }
  26215. }
  26216. for (i = 0; i < newTriangles.length; ++i) {
  26217. t = newTriangles[i];
  26218. for (j = 0; j < 3; ++j) {
  26219. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  26220. }
  26221. }
  26222. this.vertices = this.vertices.slice(0, dst);
  26223. var newPositionData = [];
  26224. var newNormalData = [];
  26225. var newUVsData = [];
  26226. var newColorsData = [];
  26227. for (i = 0; i < newVerticesOrder.length; ++i) {
  26228. newPositionData.push(this.vertices[i].position.x);
  26229. newPositionData.push(this.vertices[i].position.y);
  26230. newPositionData.push(this.vertices[i].position.z);
  26231. newNormalData.push(this.vertices[i].normal.x);
  26232. newNormalData.push(this.vertices[i].normal.y);
  26233. newNormalData.push(this.vertices[i].normal.z);
  26234. if (this.vertices[i].uv) {
  26235. newUVsData.push(this.vertices[i].uv.x);
  26236. newUVsData.push(this.vertices[i].uv.y);
  26237. }
  26238. else if (this.vertices[i].color) {
  26239. newColorsData.push(this.vertices[i].color.r);
  26240. newColorsData.push(this.vertices[i].color.g);
  26241. newColorsData.push(this.vertices[i].color.b);
  26242. }
  26243. }
  26244. var newIndicesArray = [];
  26245. for (i = 0; i < newTriangles.length; ++i) {
  26246. newIndicesArray.push(newTriangles[i].vertices[0]);
  26247. newIndicesArray.push(newTriangles[i].vertices[1]);
  26248. newIndicesArray.push(newTriangles[i].vertices[2]);
  26249. }
  26250. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  26251. var newMesh = new BABYLON.Mesh(this._mesh + "Decimated", this._mesh.getScene());
  26252. newMesh.material = this._mesh.material;
  26253. newMesh.parent = this._mesh.parent;
  26254. newMesh.setIndices(newIndicesArray);
  26255. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  26256. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  26257. if (newUVsData.length > 0)
  26258. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  26259. if (newColorsData.length > 0)
  26260. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  26261. //preparing the skeleton support
  26262. if (this._mesh.skeleton) {
  26263. }
  26264. return newMesh;
  26265. };
  26266. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor) {
  26267. for (var i = 0; i < vertex1.triangleCount; ++i) {
  26268. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  26269. if (t.deleted)
  26270. continue;
  26271. var s = this.references[vertex1.triangleStart + i].vertexId;
  26272. var id1 = t.vertices[(s + 1) % 3];
  26273. var id2 = t.vertices[(s + 2) % 3];
  26274. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  26275. deletedArray[i] = true;
  26276. continue;
  26277. }
  26278. var d1 = this.vertices[id1].position.subtract(point);
  26279. d1 = d1.normalize();
  26280. var d2 = this.vertices[id2].position.subtract(point);
  26281. d2 = d2.normalize();
  26282. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  26283. return true;
  26284. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  26285. deletedArray[i] = false;
  26286. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  26287. return true;
  26288. }
  26289. return false;
  26290. };
  26291. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  26292. var newDeleted = deletedTriangles;
  26293. for (var i = 0; i < vertex.triangleCount; ++i) {
  26294. var ref = this.references[vertex.triangleStart + i];
  26295. var t = this.triangles[ref.triangleId];
  26296. if (t.deleted)
  26297. continue;
  26298. if (deletedArray[i]) {
  26299. t.deleted = true;
  26300. newDeleted++;
  26301. continue;
  26302. }
  26303. t.vertices[ref.vertexId] = vertexId;
  26304. t.isDirty = true;
  26305. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  26306. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  26307. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  26308. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  26309. this.references.push(ref);
  26310. }
  26311. return newDeleted;
  26312. };
  26313. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  26314. for (var i = 0; i < this.vertices.length; ++i) {
  26315. var vCount = [];
  26316. var vId = [];
  26317. var v = this.vertices[i];
  26318. var j;
  26319. for (j = 0; j < v.triangleCount; ++j) {
  26320. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  26321. for (var ii = 0; ii < 3; ii++) {
  26322. var ofs = 0;
  26323. var id = triangle.vertices[ii];
  26324. while (ofs < vCount.length) {
  26325. if (vId[ofs] === id)
  26326. break;
  26327. ++ofs;
  26328. }
  26329. if (ofs === vCount.length) {
  26330. vCount.push(1);
  26331. vId.push(id);
  26332. }
  26333. else {
  26334. vCount[ofs]++;
  26335. }
  26336. }
  26337. }
  26338. for (j = 0; j < vCount.length; ++j) {
  26339. if (vCount[j] === 1) {
  26340. this.vertices[vId[j]].isBorder = true;
  26341. }
  26342. else {
  26343. this.vertices[vId[j]].isBorder = false;
  26344. }
  26345. }
  26346. }
  26347. };
  26348. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  26349. if (identifyBorders === void 0) { identifyBorders = false; }
  26350. var i;
  26351. if (!identifyBorders) {
  26352. var newTrianglesVector = [];
  26353. for (i = 0; i < this.triangles.length; ++i) {
  26354. if (!this.triangles[i].deleted) {
  26355. newTrianglesVector.push(this.triangles[i]);
  26356. }
  26357. }
  26358. this.triangles = newTrianglesVector;
  26359. }
  26360. for (i = 0; i < this.vertices.length; ++i) {
  26361. this.vertices[i].triangleCount = 0;
  26362. this.vertices[i].triangleStart = 0;
  26363. }
  26364. var t;
  26365. var j;
  26366. var v;
  26367. for (i = 0; i < this.triangles.length; ++i) {
  26368. t = this.triangles[i];
  26369. for (j = 0; j < 3; ++j) {
  26370. v = this.vertices[t.vertices[j]];
  26371. v.triangleCount++;
  26372. }
  26373. }
  26374. var tStart = 0;
  26375. for (i = 0; i < this.vertices.length; ++i) {
  26376. this.vertices[i].triangleStart = tStart;
  26377. tStart += this.vertices[i].triangleCount;
  26378. this.vertices[i].triangleCount = 0;
  26379. }
  26380. var newReferences = new Array(this.triangles.length * 3);
  26381. for (i = 0; i < this.triangles.length; ++i) {
  26382. t = this.triangles[i];
  26383. for (j = 0; j < 3; ++j) {
  26384. v = this.vertices[t.vertices[j]];
  26385. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  26386. v.triangleCount++;
  26387. }
  26388. }
  26389. this.references = newReferences;
  26390. if (identifyBorders) {
  26391. this.identifyBorder();
  26392. }
  26393. };
  26394. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  26395. var x = point.x;
  26396. var y = point.y;
  26397. var z = point.z;
  26398. 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];
  26399. };
  26400. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult) {
  26401. var q = vertex1.q.add(vertex2.q);
  26402. var border = vertex1.isBorder && vertex2.isBorder;
  26403. var error = 0;
  26404. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  26405. if (qDet !== 0 && !border) {
  26406. if (!pointResult) {
  26407. pointResult = BABYLON.Vector3.Zero();
  26408. }
  26409. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  26410. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  26411. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  26412. error = this.vertexError(q, pointResult);
  26413. //TODO this should be correctly calculated
  26414. if (normalResult) {
  26415. normalResult.copyFrom(vertex1.normal);
  26416. uvResult.copyFrom(vertex1.uv);
  26417. }
  26418. }
  26419. else {
  26420. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  26421. var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new BABYLON.Vector3(2, 2, 2)).normalize();
  26422. var error1 = this.vertexError(q, vertex1.position);
  26423. var error2 = this.vertexError(q, vertex2.position);
  26424. var error3 = this.vertexError(q, p3);
  26425. error = Math.min(error1, error2, error3);
  26426. if (error === error1) {
  26427. if (pointResult) {
  26428. pointResult.copyFrom(vertex1.position);
  26429. normalResult.copyFrom(vertex1.normal);
  26430. uvResult.copyFrom(vertex1.uv);
  26431. }
  26432. }
  26433. else if (error === error2) {
  26434. if (pointResult) {
  26435. pointResult.copyFrom(vertex2.position);
  26436. normalResult.copyFrom(vertex2.normal);
  26437. uvResult.copyFrom(vertex2.uv);
  26438. }
  26439. }
  26440. else {
  26441. if (pointResult) {
  26442. pointResult.copyFrom(p3);
  26443. normalResult.copyFrom(norm3);
  26444. uvResult.copyFrom(vertex1.uv);
  26445. }
  26446. }
  26447. }
  26448. return error;
  26449. };
  26450. return QuadraticErrorSimplification;
  26451. })();
  26452. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  26453. })(BABYLON || (BABYLON = {}));
  26454. //# sourceMappingURL=babylon.meshSimplification.js.map