babylon.2.1-alpha.debug.js 1.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325
  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. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. 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));
  346. 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));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. 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;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. 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));
  657. 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));
  658. 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));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. 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);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. 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;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. 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)
  1124. }
  1125. else {
  1126. 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)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. 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));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. 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)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. 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))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. 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]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. 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]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = 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);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. 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);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. 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);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * 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
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. 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);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = [];
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = [];
  2418. this._distances = [];
  2419. this._tangents = [];
  2420. this._normals = [];
  2421. this._binormals = [];
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. })(BABYLON || (BABYLON = {}));
  2499. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2500. (function (BABYLON) {
  2501. // Screenshots
  2502. var screenshotCanvas;
  2503. var cloneValue = function (source, destinationObject) {
  2504. if (!source)
  2505. return null;
  2506. if (source instanceof BABYLON.Mesh) {
  2507. return null;
  2508. }
  2509. if (source instanceof BABYLON.SubMesh) {
  2510. return source.clone(destinationObject);
  2511. }
  2512. else if (source.clone) {
  2513. return source.clone();
  2514. }
  2515. return null;
  2516. };
  2517. var Tools = (function () {
  2518. function Tools() {
  2519. }
  2520. Tools.GetFilename = function (path) {
  2521. var index = path.lastIndexOf("/");
  2522. if (index < 0)
  2523. return path;
  2524. return path.substring(index + 1);
  2525. };
  2526. Tools.GetDOMTextContent = function (element) {
  2527. var result = "";
  2528. var child = element.firstChild;
  2529. while (child) {
  2530. if (child.nodeType === 3) {
  2531. result += child.textContent;
  2532. }
  2533. child = child.nextSibling;
  2534. }
  2535. return result;
  2536. };
  2537. Tools.ToDegrees = function (angle) {
  2538. return angle * 180 / Math.PI;
  2539. };
  2540. Tools.ToRadians = function (angle) {
  2541. return angle * Math.PI / 180;
  2542. };
  2543. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2544. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2545. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2546. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2547. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2548. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2549. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2550. }
  2551. return {
  2552. minimum: minimum,
  2553. maximum: maximum
  2554. };
  2555. };
  2556. Tools.ExtractMinAndMax = function (positions, start, count) {
  2557. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2558. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2559. for (var index = start; index < start + count; index++) {
  2560. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2561. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2562. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2563. }
  2564. return {
  2565. minimum: minimum,
  2566. maximum: maximum
  2567. };
  2568. };
  2569. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2570. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2571. return undefined;
  2572. return Array.isArray(obj) ? obj : [obj];
  2573. };
  2574. // Misc.
  2575. Tools.GetPointerPrefix = function () {
  2576. var eventPrefix = "pointer";
  2577. // Check if hand.js is referenced or if the browser natively supports pointer events
  2578. if (!navigator.pointerEnabled) {
  2579. eventPrefix = "mouse";
  2580. }
  2581. return eventPrefix;
  2582. };
  2583. Tools.QueueNewFrame = function (func) {
  2584. if (window.requestAnimationFrame)
  2585. window.requestAnimationFrame(func);
  2586. else if (window.msRequestAnimationFrame)
  2587. window.msRequestAnimationFrame(func);
  2588. else if (window.webkitRequestAnimationFrame)
  2589. window.webkitRequestAnimationFrame(func);
  2590. else if (window.mozRequestAnimationFrame)
  2591. window.mozRequestAnimationFrame(func);
  2592. else if (window.oRequestAnimationFrame)
  2593. window.oRequestAnimationFrame(func);
  2594. else {
  2595. window.setTimeout(func, 16);
  2596. }
  2597. };
  2598. Tools.RequestFullscreen = function (element) {
  2599. if (element.requestFullscreen)
  2600. element.requestFullscreen();
  2601. else if (element.msRequestFullscreen)
  2602. element.msRequestFullscreen();
  2603. else if (element.webkitRequestFullscreen)
  2604. element.webkitRequestFullscreen();
  2605. else if (element.mozRequestFullScreen)
  2606. element.mozRequestFullScreen();
  2607. };
  2608. Tools.ExitFullscreen = function () {
  2609. if (document.exitFullscreen) {
  2610. document.exitFullscreen();
  2611. }
  2612. else if (document.mozCancelFullScreen) {
  2613. document.mozCancelFullScreen();
  2614. }
  2615. else if (document.webkitCancelFullScreen) {
  2616. document.webkitCancelFullScreen();
  2617. }
  2618. else if (document.msCancelFullScreen) {
  2619. document.msCancelFullScreen();
  2620. }
  2621. };
  2622. // External files
  2623. Tools.CleanUrl = function (url) {
  2624. url = url.replace(/#/mg, "%23");
  2625. return url;
  2626. };
  2627. Tools.LoadImage = function (url, onload, onerror, database) {
  2628. url = Tools.CleanUrl(url);
  2629. var img = new Image();
  2630. if (url.substr(0, 5) !== "data:")
  2631. img.crossOrigin = 'anonymous';
  2632. img.onload = function () {
  2633. onload(img);
  2634. };
  2635. img.onerror = function (err) {
  2636. onerror(img, err);
  2637. };
  2638. var noIndexedDB = function () {
  2639. img.src = url;
  2640. };
  2641. var loadFromIndexedDB = function () {
  2642. database.loadImageFromDB(url, img);
  2643. };
  2644. //ANY database to do!
  2645. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2646. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2647. }
  2648. else {
  2649. if (url.indexOf("file:") === -1) {
  2650. noIndexedDB();
  2651. }
  2652. else {
  2653. try {
  2654. var textureName = url.substring(5);
  2655. var blobURL;
  2656. try {
  2657. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2658. }
  2659. catch (ex) {
  2660. // Chrome doesn't support oneTimeOnly parameter
  2661. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2662. }
  2663. img.src = blobURL;
  2664. }
  2665. catch (e) {
  2666. Tools.Log("Error while trying to load texture: " + textureName);
  2667. img.src = null;
  2668. }
  2669. }
  2670. }
  2671. return img;
  2672. };
  2673. //ANY
  2674. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2675. url = Tools.CleanUrl(url);
  2676. var noIndexedDB = function () {
  2677. var request = new XMLHttpRequest();
  2678. var loadUrl = Tools.BaseUrl + url;
  2679. request.open('GET', loadUrl, true);
  2680. if (useArrayBuffer) {
  2681. request.responseType = "arraybuffer";
  2682. }
  2683. request.onprogress = progressCallBack;
  2684. request.onreadystatechange = function () {
  2685. if (request.readyState === 4) {
  2686. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2687. callback(!useArrayBuffer ? request.responseText : request.response);
  2688. }
  2689. else {
  2690. if (onError) {
  2691. onError();
  2692. }
  2693. else {
  2694. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2695. }
  2696. }
  2697. }
  2698. };
  2699. request.send(null);
  2700. };
  2701. var loadFromIndexedDB = function () {
  2702. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2703. };
  2704. if (url.indexOf("file:") !== -1) {
  2705. var fileName = url.substring(5);
  2706. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2707. }
  2708. else {
  2709. // Caching all files
  2710. if (database && database.enableSceneOffline) {
  2711. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2712. }
  2713. else {
  2714. noIndexedDB();
  2715. }
  2716. }
  2717. };
  2718. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2719. var reader = new FileReader();
  2720. reader.onload = function (e) {
  2721. //target doesn't have result from ts 1.3
  2722. callback(e.target['result']);
  2723. };
  2724. reader.onprogress = progressCallback;
  2725. reader.readAsDataURL(fileToLoad);
  2726. };
  2727. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2728. var reader = new FileReader();
  2729. reader.onerror = function (e) {
  2730. Tools.Log("Error while reading file: " + fileToLoad.name);
  2731. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2732. };
  2733. reader.onload = function (e) {
  2734. //target doesn't have result from ts 1.3
  2735. callback(e.target['result']);
  2736. };
  2737. reader.onprogress = progressCallBack;
  2738. if (!useArrayBuffer) {
  2739. // Asynchronous read
  2740. reader.readAsText(fileToLoad);
  2741. }
  2742. else {
  2743. reader.readAsArrayBuffer(fileToLoad);
  2744. }
  2745. };
  2746. // Misc.
  2747. Tools.Clamp = function (value, min, max) {
  2748. if (min === void 0) { min = 0; }
  2749. if (max === void 0) { max = 1; }
  2750. return Math.min(max, Math.max(min, value));
  2751. };
  2752. // Returns -1 when value is a negative number and
  2753. // +1 when value is a positive number.
  2754. Tools.Sign = function (value) {
  2755. value = +value; // convert to a number
  2756. if (value === 0 || isNaN(value))
  2757. return value;
  2758. return value > 0 ? 1 : -1;
  2759. };
  2760. Tools.Format = function (value, decimals) {
  2761. if (decimals === void 0) { decimals = 2; }
  2762. return value.toFixed(decimals);
  2763. };
  2764. Tools.CheckExtends = function (v, min, max) {
  2765. if (v.x < min.x)
  2766. min.x = v.x;
  2767. if (v.y < min.y)
  2768. min.y = v.y;
  2769. if (v.z < min.z)
  2770. min.z = v.z;
  2771. if (v.x > max.x)
  2772. max.x = v.x;
  2773. if (v.y > max.y)
  2774. max.y = v.y;
  2775. if (v.z > max.z)
  2776. max.z = v.z;
  2777. };
  2778. Tools.WithinEpsilon = function (a, b, epsilon) {
  2779. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2780. var num = a - b;
  2781. return -epsilon <= num && num <= epsilon;
  2782. };
  2783. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2784. for (var prop in source) {
  2785. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2786. continue;
  2787. }
  2788. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2789. continue;
  2790. }
  2791. var sourceValue = source[prop];
  2792. var typeOfSourceValue = typeof sourceValue;
  2793. if (typeOfSourceValue === "function") {
  2794. continue;
  2795. }
  2796. if (typeOfSourceValue === "object") {
  2797. if (sourceValue instanceof Array) {
  2798. destination[prop] = [];
  2799. if (sourceValue.length > 0) {
  2800. if (typeof sourceValue[0] == "object") {
  2801. for (var index = 0; index < sourceValue.length; index++) {
  2802. var clonedValue = cloneValue(sourceValue[index], destination);
  2803. if (destination[prop].indexOf(clonedValue) === -1) {
  2804. destination[prop].push(clonedValue);
  2805. }
  2806. }
  2807. }
  2808. else {
  2809. destination[prop] = sourceValue.slice(0);
  2810. }
  2811. }
  2812. }
  2813. else {
  2814. destination[prop] = cloneValue(sourceValue, destination);
  2815. }
  2816. }
  2817. else {
  2818. destination[prop] = sourceValue;
  2819. }
  2820. }
  2821. };
  2822. Tools.IsEmpty = function (obj) {
  2823. for (var i in obj) {
  2824. return false;
  2825. }
  2826. return true;
  2827. };
  2828. Tools.RegisterTopRootEvents = function (events) {
  2829. for (var index = 0; index < events.length; index++) {
  2830. var event = events[index];
  2831. window.addEventListener(event.name, event.handler, false);
  2832. try {
  2833. if (window.parent) {
  2834. window.parent.addEventListener(event.name, event.handler, false);
  2835. }
  2836. }
  2837. catch (e) {
  2838. }
  2839. }
  2840. };
  2841. Tools.UnregisterTopRootEvents = function (events) {
  2842. for (var index = 0; index < events.length; index++) {
  2843. var event = events[index];
  2844. window.removeEventListener(event.name, event.handler);
  2845. try {
  2846. if (window.parent) {
  2847. window.parent.removeEventListener(event.name, event.handler);
  2848. }
  2849. }
  2850. catch (e) {
  2851. }
  2852. }
  2853. };
  2854. Tools.DumpFramebuffer = function (width, height, engine) {
  2855. // Read the contents of the framebuffer
  2856. var numberOfChannelsByLine = width * 4;
  2857. var halfHeight = height / 2;
  2858. //Reading datas from WebGL
  2859. var data = engine.readPixels(0, 0, width, height);
  2860. for (var i = 0; i < halfHeight; i++) {
  2861. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2862. var currentCell = j + i * numberOfChannelsByLine;
  2863. var targetLine = height - i - 1;
  2864. var targetCell = j + targetLine * numberOfChannelsByLine;
  2865. var temp = data[currentCell];
  2866. data[currentCell] = data[targetCell];
  2867. data[targetCell] = temp;
  2868. }
  2869. }
  2870. // Create a 2D canvas to store the result
  2871. if (!screenshotCanvas) {
  2872. screenshotCanvas = document.createElement('canvas');
  2873. }
  2874. screenshotCanvas.width = width;
  2875. screenshotCanvas.height = height;
  2876. var context = screenshotCanvas.getContext('2d');
  2877. // Copy the pixels to a 2D canvas
  2878. var imageData = context.createImageData(width, height);
  2879. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2880. var castData = imageData.data;
  2881. castData.set(data);
  2882. context.putImageData(imageData, 0, 0);
  2883. var base64Image = screenshotCanvas.toDataURL();
  2884. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2885. if (("download" in document.createElement("a"))) {
  2886. var a = window.document.createElement("a");
  2887. a.href = base64Image;
  2888. var date = new Date();
  2889. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2890. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2891. window.document.body.appendChild(a);
  2892. a.addEventListener("click", function () {
  2893. a.parentElement.removeChild(a);
  2894. });
  2895. a.click();
  2896. }
  2897. else {
  2898. var newWindow = window.open("");
  2899. var img = newWindow.document.createElement("img");
  2900. img.src = base64Image;
  2901. newWindow.document.body.appendChild(img);
  2902. }
  2903. };
  2904. Tools.CreateScreenshot = function (engine, camera, size) {
  2905. var width;
  2906. var height;
  2907. var scene = camera.getScene();
  2908. var previousCamera = null;
  2909. if (scene.activeCamera !== camera) {
  2910. previousCamera = scene.activeCamera;
  2911. scene.activeCamera = camera;
  2912. }
  2913. //If a precision value is specified
  2914. if (size.precision) {
  2915. width = Math.round(engine.getRenderWidth() * size.precision);
  2916. height = Math.round(width / engine.getAspectRatio(camera));
  2917. size = { width: width, height: height };
  2918. }
  2919. else if (size.width && size.height) {
  2920. width = size.width;
  2921. height = size.height;
  2922. }
  2923. else if (size.width && !size.height) {
  2924. width = size.width;
  2925. height = Math.round(width / engine.getAspectRatio(camera));
  2926. size = { width: width, height: height };
  2927. }
  2928. else if (size.height && !size.width) {
  2929. height = size.height;
  2930. width = Math.round(height * engine.getAspectRatio(camera));
  2931. size = { width: width, height: height };
  2932. }
  2933. else if (!isNaN(size)) {
  2934. height = size;
  2935. width = size;
  2936. }
  2937. else {
  2938. Tools.Error("Invalid 'size' parameter !");
  2939. return;
  2940. }
  2941. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2942. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2943. texture.renderList = scene.meshes;
  2944. texture.onAfterRender = function () {
  2945. Tools.DumpFramebuffer(width, height, engine);
  2946. };
  2947. scene.incrementRenderId();
  2948. texture.render(true);
  2949. texture.dispose();
  2950. if (previousCamera) {
  2951. scene.activeCamera = previousCamera;
  2952. }
  2953. };
  2954. // XHR response validator for local file scenario
  2955. Tools.ValidateXHRData = function (xhr, dataType) {
  2956. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2957. if (dataType === void 0) { dataType = 7; }
  2958. try {
  2959. if (dataType & 1) {
  2960. if (xhr.responseText && xhr.responseText.length > 0) {
  2961. return true;
  2962. }
  2963. else if (dataType === 1) {
  2964. return false;
  2965. }
  2966. }
  2967. if (dataType & 2) {
  2968. // Check header width and height since there is no "TGA" magic number
  2969. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2970. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2971. return true;
  2972. }
  2973. else if (dataType === 2) {
  2974. return false;
  2975. }
  2976. }
  2977. if (dataType & 4) {
  2978. // Check for the "DDS" magic number
  2979. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2980. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2981. return true;
  2982. }
  2983. else {
  2984. return false;
  2985. }
  2986. }
  2987. }
  2988. catch (e) {
  2989. }
  2990. return false;
  2991. };
  2992. Object.defineProperty(Tools, "NoneLogLevel", {
  2993. get: function () {
  2994. return Tools._NoneLogLevel;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. Object.defineProperty(Tools, "MessageLogLevel", {
  3000. get: function () {
  3001. return Tools._MessageLogLevel;
  3002. },
  3003. enumerable: true,
  3004. configurable: true
  3005. });
  3006. Object.defineProperty(Tools, "WarningLogLevel", {
  3007. get: function () {
  3008. return Tools._WarningLogLevel;
  3009. },
  3010. enumerable: true,
  3011. configurable: true
  3012. });
  3013. Object.defineProperty(Tools, "ErrorLogLevel", {
  3014. get: function () {
  3015. return Tools._ErrorLogLevel;
  3016. },
  3017. enumerable: true,
  3018. configurable: true
  3019. });
  3020. Object.defineProperty(Tools, "AllLogLevel", {
  3021. get: function () {
  3022. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3023. },
  3024. enumerable: true,
  3025. configurable: true
  3026. });
  3027. Tools._AddLogEntry = function (entry) {
  3028. Tools._LogCache = entry + Tools._LogCache;
  3029. if (Tools.OnNewCacheEntry) {
  3030. Tools.OnNewCacheEntry(entry);
  3031. }
  3032. };
  3033. Tools._FormatMessage = function (message) {
  3034. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3035. var date = new Date();
  3036. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3037. };
  3038. Tools._LogDisabled = function (message) {
  3039. // nothing to do
  3040. };
  3041. Tools._LogEnabled = function (message) {
  3042. var formattedMessage = Tools._FormatMessage(message);
  3043. console.log("BJS - " + formattedMessage);
  3044. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3045. Tools._AddLogEntry(entry);
  3046. };
  3047. Tools._WarnDisabled = function (message) {
  3048. // nothing to do
  3049. };
  3050. Tools._WarnEnabled = function (message) {
  3051. var formattedMessage = Tools._FormatMessage(message);
  3052. console.warn("BJS - " + formattedMessage);
  3053. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3054. Tools._AddLogEntry(entry);
  3055. };
  3056. Tools._ErrorDisabled = function (message) {
  3057. // nothing to do
  3058. };
  3059. Tools._ErrorEnabled = function (message) {
  3060. var formattedMessage = Tools._FormatMessage(message);
  3061. console.error("BJS - " + formattedMessage);
  3062. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3063. Tools._AddLogEntry(entry);
  3064. };
  3065. Object.defineProperty(Tools, "LogCache", {
  3066. get: function () {
  3067. return Tools._LogCache;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(Tools, "LogLevels", {
  3073. set: function (level) {
  3074. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3075. Tools.Log = Tools._LogEnabled;
  3076. }
  3077. else {
  3078. Tools.Log = Tools._LogDisabled;
  3079. }
  3080. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3081. Tools.Warn = Tools._WarnEnabled;
  3082. }
  3083. else {
  3084. Tools.Warn = Tools._WarnDisabled;
  3085. }
  3086. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3087. Tools.Error = Tools._ErrorEnabled;
  3088. }
  3089. else {
  3090. Tools.Error = Tools._ErrorDisabled;
  3091. }
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3097. get: function () {
  3098. return Tools._PerformanceNoneLogLevel;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3104. get: function () {
  3105. return Tools._PerformanceUserMarkLogLevel;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3111. get: function () {
  3112. return Tools._PerformanceConsoleLogLevel;
  3113. },
  3114. enumerable: true,
  3115. configurable: true
  3116. });
  3117. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3118. set: function (level) {
  3119. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3120. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3121. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3122. return;
  3123. }
  3124. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3125. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3126. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3127. return;
  3128. }
  3129. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3130. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3136. };
  3137. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3138. };
  3139. Tools._StartUserMark = function (counterName, condition) {
  3140. if (condition === void 0) { condition = true; }
  3141. if (!condition || !Tools._performance.mark) {
  3142. return;
  3143. }
  3144. Tools._performance.mark(counterName + "-Begin");
  3145. };
  3146. Tools._EndUserMark = function (counterName, condition) {
  3147. if (condition === void 0) { condition = true; }
  3148. if (!condition || !Tools._performance.mark) {
  3149. return;
  3150. }
  3151. Tools._performance.mark(counterName + "-End");
  3152. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3153. };
  3154. Tools._StartPerformanceConsole = function (counterName, condition) {
  3155. if (condition === void 0) { condition = true; }
  3156. if (!condition) {
  3157. return;
  3158. }
  3159. Tools._StartUserMark(counterName, condition);
  3160. if (console.time) {
  3161. console.time(counterName);
  3162. }
  3163. };
  3164. Tools._EndPerformanceConsole = function (counterName, condition) {
  3165. if (condition === void 0) { condition = true; }
  3166. if (!condition) {
  3167. return;
  3168. }
  3169. Tools._EndUserMark(counterName, condition);
  3170. if (console.time) {
  3171. console.timeEnd(counterName);
  3172. }
  3173. };
  3174. Object.defineProperty(Tools, "Now", {
  3175. get: function () {
  3176. if (window.performance && window.performance.now) {
  3177. return window.performance.now();
  3178. }
  3179. return new Date().getTime();
  3180. },
  3181. enumerable: true,
  3182. configurable: true
  3183. });
  3184. // Deprecated
  3185. Tools.GetFps = function () {
  3186. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3187. return 0;
  3188. };
  3189. Tools.BaseUrl = "";
  3190. Tools.GetExponantOfTwo = function (value, max) {
  3191. var count = 1;
  3192. do {
  3193. count *= 2;
  3194. } while (count < value);
  3195. if (count > max)
  3196. count = max;
  3197. return count;
  3198. };
  3199. // Logs
  3200. Tools._NoneLogLevel = 0;
  3201. Tools._MessageLogLevel = 1;
  3202. Tools._WarningLogLevel = 2;
  3203. Tools._ErrorLogLevel = 4;
  3204. Tools._LogCache = "";
  3205. Tools.Log = Tools._LogEnabled;
  3206. Tools.Warn = Tools._WarnEnabled;
  3207. Tools.Error = Tools._ErrorEnabled;
  3208. // Performances
  3209. Tools._PerformanceNoneLogLevel = 0;
  3210. Tools._PerformanceUserMarkLogLevel = 1;
  3211. Tools._PerformanceConsoleLogLevel = 2;
  3212. Tools._performance = window.performance;
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. return Tools;
  3216. })();
  3217. BABYLON.Tools = Tools;
  3218. /**
  3219. * An implementation of a loop for asynchronous functions.
  3220. */
  3221. var AsyncLoop = (function () {
  3222. /**
  3223. * Constroctor.
  3224. * @param iterations the number of iterations.
  3225. * @param _fn the function to run each iteration
  3226. * @param _successCallback the callback that will be called upon succesful execution
  3227. * @param offset starting offset.
  3228. */
  3229. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3230. if (offset === void 0) { offset = 0; }
  3231. this.iterations = iterations;
  3232. this._fn = _fn;
  3233. this._successCallback = _successCallback;
  3234. this.index = offset - 1;
  3235. this._done = false;
  3236. }
  3237. /**
  3238. * Execute the next iteration. Must be called after the last iteration was finished.
  3239. */
  3240. AsyncLoop.prototype.executeNext = function () {
  3241. if (!this._done) {
  3242. if (this.index + 1 < this.iterations) {
  3243. ++this.index;
  3244. this._fn(this);
  3245. }
  3246. else {
  3247. this.breakLoop();
  3248. }
  3249. }
  3250. };
  3251. /**
  3252. * Break the loop and run the success callback.
  3253. */
  3254. AsyncLoop.prototype.breakLoop = function () {
  3255. this._done = true;
  3256. this._successCallback();
  3257. };
  3258. /**
  3259. * Helper function
  3260. */
  3261. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3262. if (offset === void 0) { offset = 0; }
  3263. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3264. loop.executeNext();
  3265. return loop;
  3266. };
  3267. /**
  3268. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3269. * @param iterations total number of iterations
  3270. * @param syncedIterations number of synchronous iterations in each async iteration.
  3271. * @param fn the function to call each iteration.
  3272. * @param callback a success call back that will be called when iterating stops.
  3273. * @param breakFunction a break condition (optional)
  3274. * @param timeout timeout settings for the setTimeout function. default - 0.
  3275. * @constructor
  3276. */
  3277. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3278. if (timeout === void 0) { timeout = 0; }
  3279. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3280. if (breakFunction && breakFunction())
  3281. loop.breakLoop();
  3282. else {
  3283. setTimeout(function () {
  3284. for (var i = 0; i < syncedIterations; ++i) {
  3285. var iteration = (loop.index * syncedIterations) + i;
  3286. if (iteration >= iterations)
  3287. break;
  3288. fn(iteration);
  3289. if (breakFunction && breakFunction()) {
  3290. loop.breakLoop();
  3291. break;
  3292. }
  3293. }
  3294. loop.executeNext();
  3295. }, timeout);
  3296. }
  3297. }, callback);
  3298. };
  3299. return AsyncLoop;
  3300. })();
  3301. BABYLON.AsyncLoop = AsyncLoop;
  3302. })(BABYLON || (BABYLON = {}));
  3303. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3304. (function (BABYLON) {
  3305. var _DepthCullingState = (function () {
  3306. function _DepthCullingState() {
  3307. this._isDepthTestDirty = false;
  3308. this._isDepthMaskDirty = false;
  3309. this._isDepthFuncDirty = false;
  3310. this._isCullFaceDirty = false;
  3311. this._isCullDirty = false;
  3312. }
  3313. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3314. get: function () {
  3315. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3316. },
  3317. enumerable: true,
  3318. configurable: true
  3319. });
  3320. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3321. get: function () {
  3322. return this._cullFace;
  3323. },
  3324. set: function (value) {
  3325. if (this._cullFace === value) {
  3326. return;
  3327. }
  3328. this._cullFace = value;
  3329. this._isCullFaceDirty = true;
  3330. },
  3331. enumerable: true,
  3332. configurable: true
  3333. });
  3334. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3335. get: function () {
  3336. return this._cull;
  3337. },
  3338. set: function (value) {
  3339. if (this._cull === value) {
  3340. return;
  3341. }
  3342. this._cull = value;
  3343. this._isCullDirty = true;
  3344. },
  3345. enumerable: true,
  3346. configurable: true
  3347. });
  3348. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3349. get: function () {
  3350. return this._depthFunc;
  3351. },
  3352. set: function (value) {
  3353. if (this._depthFunc === value) {
  3354. return;
  3355. }
  3356. this._depthFunc = value;
  3357. this._isDepthFuncDirty = true;
  3358. },
  3359. enumerable: true,
  3360. configurable: true
  3361. });
  3362. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3363. get: function () {
  3364. return this._depthMask;
  3365. },
  3366. set: function (value) {
  3367. if (this._depthMask === value) {
  3368. return;
  3369. }
  3370. this._depthMask = value;
  3371. this._isDepthMaskDirty = true;
  3372. },
  3373. enumerable: true,
  3374. configurable: true
  3375. });
  3376. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3377. get: function () {
  3378. return this._depthTest;
  3379. },
  3380. set: function (value) {
  3381. if (this._depthTest === value) {
  3382. return;
  3383. }
  3384. this._depthTest = value;
  3385. this._isDepthTestDirty = true;
  3386. },
  3387. enumerable: true,
  3388. configurable: true
  3389. });
  3390. _DepthCullingState.prototype.reset = function () {
  3391. this._depthMask = true;
  3392. this._depthTest = true;
  3393. this._depthFunc = null;
  3394. this._cull = null;
  3395. this._cullFace = null;
  3396. this._isDepthTestDirty = true;
  3397. this._isDepthMaskDirty = true;
  3398. this._isDepthFuncDirty = false;
  3399. this._isCullFaceDirty = false;
  3400. this._isCullDirty = false;
  3401. };
  3402. _DepthCullingState.prototype.apply = function (gl) {
  3403. if (!this.isDirty) {
  3404. return;
  3405. }
  3406. // Cull
  3407. if (this._isCullDirty) {
  3408. if (this.cull) {
  3409. gl.enable(gl.CULL_FACE);
  3410. }
  3411. else {
  3412. gl.disable(gl.CULL_FACE);
  3413. }
  3414. this._isCullDirty = false;
  3415. }
  3416. // Cull face
  3417. if (this._isCullFaceDirty) {
  3418. gl.cullFace(this.cullFace);
  3419. this._isCullFaceDirty = false;
  3420. }
  3421. // Depth mask
  3422. if (this._isDepthMaskDirty) {
  3423. gl.depthMask(this.depthMask);
  3424. this._isDepthMaskDirty = false;
  3425. }
  3426. // Depth test
  3427. if (this._isDepthTestDirty) {
  3428. if (this.depthTest) {
  3429. gl.enable(gl.DEPTH_TEST);
  3430. }
  3431. else {
  3432. gl.disable(gl.DEPTH_TEST);
  3433. }
  3434. this._isDepthTestDirty = false;
  3435. }
  3436. // Depth func
  3437. if (this._isDepthFuncDirty) {
  3438. gl.depthFunc(this.depthFunc);
  3439. this._isDepthFuncDirty = false;
  3440. }
  3441. };
  3442. return _DepthCullingState;
  3443. })();
  3444. BABYLON._DepthCullingState = _DepthCullingState;
  3445. var _AlphaState = (function () {
  3446. function _AlphaState() {
  3447. this._isAlphaBlendDirty = false;
  3448. this._isBlendFunctionParametersDirty = false;
  3449. this._alphaBlend = false;
  3450. this._blendFunctionParameters = new Array(4);
  3451. }
  3452. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3453. get: function () {
  3454. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3455. },
  3456. enumerable: true,
  3457. configurable: true
  3458. });
  3459. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3460. get: function () {
  3461. return this._alphaBlend;
  3462. },
  3463. set: function (value) {
  3464. if (this._alphaBlend === value) {
  3465. return;
  3466. }
  3467. this._alphaBlend = value;
  3468. this._isAlphaBlendDirty = true;
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3474. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3475. return;
  3476. }
  3477. this._blendFunctionParameters[0] = value0;
  3478. this._blendFunctionParameters[1] = value1;
  3479. this._blendFunctionParameters[2] = value2;
  3480. this._blendFunctionParameters[3] = value3;
  3481. this._isBlendFunctionParametersDirty = true;
  3482. };
  3483. _AlphaState.prototype.reset = function () {
  3484. this._alphaBlend = false;
  3485. this._blendFunctionParameters[0] = null;
  3486. this._blendFunctionParameters[1] = null;
  3487. this._blendFunctionParameters[2] = null;
  3488. this._blendFunctionParameters[3] = null;
  3489. this._isAlphaBlendDirty = true;
  3490. this._isBlendFunctionParametersDirty = false;
  3491. };
  3492. _AlphaState.prototype.apply = function (gl) {
  3493. if (!this.isDirty) {
  3494. return;
  3495. }
  3496. // Alpha blend
  3497. if (this._isAlphaBlendDirty) {
  3498. if (this._alphaBlend) {
  3499. gl.enable(gl.BLEND);
  3500. }
  3501. else {
  3502. gl.disable(gl.BLEND);
  3503. }
  3504. this._isAlphaBlendDirty = false;
  3505. }
  3506. // Alpha function
  3507. if (this._isBlendFunctionParametersDirty) {
  3508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3509. this._isBlendFunctionParametersDirty = false;
  3510. }
  3511. };
  3512. return _AlphaState;
  3513. })();
  3514. BABYLON._AlphaState = _AlphaState;
  3515. var compileShader = function (gl, source, type, defines) {
  3516. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3517. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3518. gl.compileShader(shader);
  3519. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3520. throw new Error(gl.getShaderInfoLog(shader));
  3521. }
  3522. return shader;
  3523. };
  3524. var getWebGLTextureType = function (gl, type) {
  3525. var textureType = gl.UNSIGNED_BYTE;
  3526. if (type === Engine.TEXTURETYPE_FLOAT)
  3527. textureType = gl.FLOAT;
  3528. return textureType;
  3529. };
  3530. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3531. var magFilter = gl.NEAREST;
  3532. var minFilter = gl.NEAREST;
  3533. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3534. magFilter = gl.LINEAR;
  3535. if (generateMipMaps) {
  3536. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3537. }
  3538. else {
  3539. minFilter = gl.LINEAR;
  3540. }
  3541. }
  3542. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3543. magFilter = gl.LINEAR;
  3544. if (generateMipMaps) {
  3545. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3546. }
  3547. else {
  3548. minFilter = gl.LINEAR;
  3549. }
  3550. }
  3551. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3552. magFilter = gl.NEAREST;
  3553. if (generateMipMaps) {
  3554. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3555. }
  3556. else {
  3557. minFilter = gl.NEAREST;
  3558. }
  3559. }
  3560. return {
  3561. min: minFilter,
  3562. mag: magFilter
  3563. };
  3564. };
  3565. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3567. var engine = scene.getEngine();
  3568. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3569. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3570. gl.bindTexture(gl.TEXTURE_2D, texture);
  3571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3572. processFunction(potWidth, potHeight);
  3573. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3576. if (!noMipmap && !isCompressed) {
  3577. gl.generateMipmap(gl.TEXTURE_2D);
  3578. }
  3579. gl.bindTexture(gl.TEXTURE_2D, null);
  3580. engine._activeTexturesCache = [];
  3581. texture._baseWidth = width;
  3582. texture._baseHeight = height;
  3583. texture._width = potWidth;
  3584. texture._height = potHeight;
  3585. texture.isReady = true;
  3586. texture.samplingMode = samplingMode;
  3587. scene._removePendingData(texture);
  3588. };
  3589. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3590. var onload = function () {
  3591. loadedImages[index] = img;
  3592. loadedImages._internalCount++;
  3593. scene._removePendingData(img);
  3594. if (loadedImages._internalCount === 6) {
  3595. onfinish(loadedImages);
  3596. }
  3597. };
  3598. var onerror = function () {
  3599. scene._removePendingData(img);
  3600. };
  3601. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3602. scene._addPendingData(img);
  3603. };
  3604. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3605. var loadedImages = [];
  3606. loadedImages._internalCount = 0;
  3607. for (var index = 0; index < 6; index++) {
  3608. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3609. }
  3610. };
  3611. var EngineCapabilities = (function () {
  3612. function EngineCapabilities() {
  3613. }
  3614. return EngineCapabilities;
  3615. })();
  3616. BABYLON.EngineCapabilities = EngineCapabilities;
  3617. /**
  3618. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3619. */
  3620. var Engine = (function () {
  3621. /**
  3622. * @constructor
  3623. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3624. * @param {boolean} [antialias] - enable antialias
  3625. * @param options - further options to be sent to the getContext function
  3626. */
  3627. function Engine(canvas, antialias, options) {
  3628. var _this = this;
  3629. // Public members
  3630. this.isFullscreen = false;
  3631. this.isPointerLock = false;
  3632. this.cullBackFaces = true;
  3633. this.renderEvenInBackground = true;
  3634. this.scenes = new Array();
  3635. this._windowIsBackground = false;
  3636. this._loadingDivBackgroundColor = "black";
  3637. this._drawCalls = 0;
  3638. this._renderingQueueLaunched = false;
  3639. this._activeRenderLoops = [];
  3640. // FPS
  3641. this.fpsRange = 60;
  3642. this.previousFramesDuration = [];
  3643. this.fps = 60;
  3644. this.deltaTime = 0;
  3645. // States
  3646. this._depthCullingState = new _DepthCullingState();
  3647. this._alphaState = new _AlphaState();
  3648. this._alphaMode = Engine.ALPHA_DISABLE;
  3649. // Cache
  3650. this._loadedTexturesCache = new Array();
  3651. this._activeTexturesCache = new Array();
  3652. this._compiledEffects = {};
  3653. this._uintIndicesCurrentlySet = false;
  3654. this._renderingCanvas = canvas;
  3655. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3656. options = options || {};
  3657. options.antialias = antialias;
  3658. try {
  3659. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3660. }
  3661. catch (e) {
  3662. throw new Error("WebGL not supported");
  3663. }
  3664. if (!this._gl) {
  3665. throw new Error("WebGL not supported");
  3666. }
  3667. this._onBlur = function () {
  3668. _this._windowIsBackground = true;
  3669. };
  3670. this._onFocus = function () {
  3671. _this._windowIsBackground = false;
  3672. };
  3673. window.addEventListener("blur", this._onBlur);
  3674. window.addEventListener("focus", this._onFocus);
  3675. // Textures
  3676. this._workingCanvas = document.createElement("canvas");
  3677. this._workingContext = this._workingCanvas.getContext("2d");
  3678. // Viewport
  3679. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3680. this.resize();
  3681. // Caps
  3682. this._caps = new EngineCapabilities();
  3683. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3684. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3685. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3686. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3687. // Infos
  3688. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3689. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3690. if (rendererInfo != null) {
  3691. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3692. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3693. }
  3694. if (!this._glVendor) {
  3695. this._glVendor = "Unknown vendor";
  3696. }
  3697. if (!this._glRenderer) {
  3698. this._glRenderer = "Unknown renderer";
  3699. }
  3700. // Extensions
  3701. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3702. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3703. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3704. 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');
  3705. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3706. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3707. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3708. // Depth buffer
  3709. this.setDepthBuffer(true);
  3710. this.setDepthFunctionToLessOrEqual();
  3711. this.setDepthWrite(true);
  3712. // Fullscreen
  3713. this._onFullscreenChange = function () {
  3714. if (document.fullscreen !== undefined) {
  3715. _this.isFullscreen = document.fullscreen;
  3716. }
  3717. else if (document.mozFullScreen !== undefined) {
  3718. _this.isFullscreen = document.mozFullScreen;
  3719. }
  3720. else if (document.webkitIsFullScreen !== undefined) {
  3721. _this.isFullscreen = document.webkitIsFullScreen;
  3722. }
  3723. else if (document.msIsFullScreen !== undefined) {
  3724. _this.isFullscreen = document.msIsFullScreen;
  3725. }
  3726. // Pointer lock
  3727. if (_this.isFullscreen && _this._pointerLockRequested) {
  3728. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3729. if (canvas.requestPointerLock) {
  3730. canvas.requestPointerLock();
  3731. }
  3732. }
  3733. };
  3734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3738. // Pointer lock
  3739. this._onPointerLockChange = function () {
  3740. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3741. };
  3742. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3743. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3744. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3745. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3746. if (!Engine.audioEngine) {
  3747. Engine.audioEngine = new BABYLON.AudioEngine();
  3748. }
  3749. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3750. }
  3751. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3752. get: function () {
  3753. return Engine._ALPHA_DISABLE;
  3754. },
  3755. enumerable: true,
  3756. configurable: true
  3757. });
  3758. Object.defineProperty(Engine, "ALPHA_ADD", {
  3759. get: function () {
  3760. return Engine._ALPHA_ADD;
  3761. },
  3762. enumerable: true,
  3763. configurable: true
  3764. });
  3765. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3766. get: function () {
  3767. return Engine._ALPHA_COMBINE;
  3768. },
  3769. enumerable: true,
  3770. configurable: true
  3771. });
  3772. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3773. get: function () {
  3774. return Engine._DELAYLOADSTATE_NONE;
  3775. },
  3776. enumerable: true,
  3777. configurable: true
  3778. });
  3779. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3780. get: function () {
  3781. return Engine._DELAYLOADSTATE_LOADED;
  3782. },
  3783. enumerable: true,
  3784. configurable: true
  3785. });
  3786. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3787. get: function () {
  3788. return Engine._DELAYLOADSTATE_LOADING;
  3789. },
  3790. enumerable: true,
  3791. configurable: true
  3792. });
  3793. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3794. get: function () {
  3795. return Engine._DELAYLOADSTATE_NOTLOADED;
  3796. },
  3797. enumerable: true,
  3798. configurable: true
  3799. });
  3800. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3801. get: function () {
  3802. return Engine._TEXTUREFORMAT_ALPHA;
  3803. },
  3804. enumerable: true,
  3805. configurable: true
  3806. });
  3807. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3808. get: function () {
  3809. return Engine._TEXTUREFORMAT_LUMINANCE;
  3810. },
  3811. enumerable: true,
  3812. configurable: true
  3813. });
  3814. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3815. get: function () {
  3816. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3822. get: function () {
  3823. return Engine._TEXTUREFORMAT_RGB;
  3824. },
  3825. enumerable: true,
  3826. configurable: true
  3827. });
  3828. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3829. get: function () {
  3830. return Engine._TEXTUREFORMAT_RGBA;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3836. get: function () {
  3837. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3843. get: function () {
  3844. return Engine._TEXTURETYPE_FLOAT;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "Version", {
  3850. get: function () {
  3851. return "2.1.0 alpha";
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Engine.prototype.getGlInfo = function () {
  3857. return {
  3858. vendor: this._glVendor,
  3859. renderer: this._glRenderer,
  3860. version: this._glVersion
  3861. };
  3862. };
  3863. Engine.prototype.getAspectRatio = function (camera) {
  3864. var viewport = camera.viewport;
  3865. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3866. };
  3867. Engine.prototype.getRenderWidth = function () {
  3868. if (this._currentRenderTarget) {
  3869. return this._currentRenderTarget._width;
  3870. }
  3871. return this._renderingCanvas.width;
  3872. };
  3873. Engine.prototype.getRenderHeight = function () {
  3874. if (this._currentRenderTarget) {
  3875. return this._currentRenderTarget._height;
  3876. }
  3877. return this._renderingCanvas.height;
  3878. };
  3879. Engine.prototype.getRenderingCanvas = function () {
  3880. return this._renderingCanvas;
  3881. };
  3882. Engine.prototype.getRenderingCanvasClientRect = function () {
  3883. return this._renderingCanvas.getBoundingClientRect();
  3884. };
  3885. Engine.prototype.setHardwareScalingLevel = function (level) {
  3886. this._hardwareScalingLevel = level;
  3887. this.resize();
  3888. };
  3889. Engine.prototype.getHardwareScalingLevel = function () {
  3890. return this._hardwareScalingLevel;
  3891. };
  3892. Engine.prototype.getLoadedTexturesCache = function () {
  3893. return this._loadedTexturesCache;
  3894. };
  3895. Engine.prototype.getCaps = function () {
  3896. return this._caps;
  3897. };
  3898. Object.defineProperty(Engine.prototype, "drawCalls", {
  3899. get: function () {
  3900. return this._drawCalls;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. // Methods
  3906. Engine.prototype.resetDrawCalls = function () {
  3907. this._drawCalls = 0;
  3908. };
  3909. Engine.prototype.setDepthFunctionToGreater = function () {
  3910. this._depthCullingState.depthFunc = this._gl.GREATER;
  3911. };
  3912. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3913. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3914. };
  3915. Engine.prototype.setDepthFunctionToLess = function () {
  3916. this._depthCullingState.depthFunc = this._gl.LESS;
  3917. };
  3918. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3919. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3920. };
  3921. /**
  3922. * stop executing a render loop function and remove it from the execution array
  3923. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3924. */
  3925. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3926. if (!renderFunction) {
  3927. this._activeRenderLoops = [];
  3928. return;
  3929. }
  3930. var index = this._activeRenderLoops.indexOf(renderFunction);
  3931. if (index >= 0) {
  3932. this._activeRenderLoops.splice(index, 1);
  3933. }
  3934. };
  3935. Engine.prototype._renderLoop = function () {
  3936. var _this = this;
  3937. var shouldRender = true;
  3938. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3939. shouldRender = false;
  3940. }
  3941. if (shouldRender) {
  3942. // Start new frame
  3943. this.beginFrame();
  3944. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3945. var renderFunction = this._activeRenderLoops[index];
  3946. renderFunction();
  3947. }
  3948. // Present
  3949. this.endFrame();
  3950. }
  3951. if (this._activeRenderLoops.length > 0) {
  3952. // Register new frame
  3953. BABYLON.Tools.QueueNewFrame(function () {
  3954. _this._renderLoop();
  3955. });
  3956. }
  3957. else {
  3958. this._renderingQueueLaunched = false;
  3959. }
  3960. };
  3961. /**
  3962. * Register and execute a render loop. The engine can have more than one render function.
  3963. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3964. * @example
  3965. * engine.runRenderLoop(function () {
  3966. * scene.render()
  3967. * })
  3968. */
  3969. Engine.prototype.runRenderLoop = function (renderFunction) {
  3970. var _this = this;
  3971. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3972. return;
  3973. }
  3974. this._activeRenderLoops.push(renderFunction);
  3975. if (!this._renderingQueueLaunched) {
  3976. this._renderingQueueLaunched = true;
  3977. BABYLON.Tools.QueueNewFrame(function () {
  3978. _this._renderLoop();
  3979. });
  3980. }
  3981. };
  3982. /**
  3983. * Toggle full screen mode.
  3984. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3985. */
  3986. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3987. if (this.isFullscreen) {
  3988. BABYLON.Tools.ExitFullscreen();
  3989. }
  3990. else {
  3991. this._pointerLockRequested = requestPointerLock;
  3992. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3993. }
  3994. };
  3995. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3996. this.applyStates();
  3997. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3998. if (this._depthCullingState.depthMask) {
  3999. this._gl.clearDepth(1.0);
  4000. }
  4001. var mode = 0;
  4002. if (backBuffer)
  4003. mode |= this._gl.COLOR_BUFFER_BIT;
  4004. if (depthStencil && this._depthCullingState.depthMask)
  4005. mode |= this._gl.DEPTH_BUFFER_BIT;
  4006. this._gl.clear(mode);
  4007. };
  4008. /**
  4009. * Set the WebGL's viewport
  4010. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4011. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4012. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4013. */
  4014. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4015. var width = requiredWidth || this._renderingCanvas.width;
  4016. var height = requiredHeight || this._renderingCanvas.height;
  4017. var x = viewport.x || 0;
  4018. var y = viewport.y || 0;
  4019. this._cachedViewport = viewport;
  4020. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4021. };
  4022. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4023. this._cachedViewport = null;
  4024. this._gl.viewport(x, y, width, height);
  4025. };
  4026. Engine.prototype.beginFrame = function () {
  4027. this._measureFps();
  4028. };
  4029. Engine.prototype.endFrame = function () {
  4030. //this.flushFramebuffer();
  4031. };
  4032. /**
  4033. * resize the view according to the canvas' size.
  4034. * @example
  4035. * window.addEventListener("resize", function () {
  4036. * engine.resize();
  4037. * });
  4038. */
  4039. Engine.prototype.resize = function () {
  4040. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4041. };
  4042. /**
  4043. * force a specific size of the canvas
  4044. * @param {number} width - the new canvas' width
  4045. * @param {number} height - the new canvas' height
  4046. */
  4047. Engine.prototype.setSize = function (width, height) {
  4048. this._renderingCanvas.width = width;
  4049. this._renderingCanvas.height = height;
  4050. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4051. };
  4052. Engine.prototype.bindFramebuffer = function (texture) {
  4053. this._currentRenderTarget = texture;
  4054. var gl = this._gl;
  4055. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4056. this._gl.viewport(0, 0, texture._width, texture._height);
  4057. this.wipeCaches();
  4058. };
  4059. Engine.prototype.unBindFramebuffer = function (texture) {
  4060. this._currentRenderTarget = null;
  4061. if (texture.generateMipMaps) {
  4062. var gl = this._gl;
  4063. gl.bindTexture(gl.TEXTURE_2D, texture);
  4064. gl.generateMipmap(gl.TEXTURE_2D);
  4065. gl.bindTexture(gl.TEXTURE_2D, null);
  4066. }
  4067. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4068. };
  4069. Engine.prototype.flushFramebuffer = function () {
  4070. this._gl.flush();
  4071. };
  4072. Engine.prototype.restoreDefaultFramebuffer = function () {
  4073. this._currentRenderTarget = null;
  4074. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4075. this.setViewport(this._cachedViewport);
  4076. this.wipeCaches();
  4077. };
  4078. // VBOs
  4079. Engine.prototype._resetVertexBufferBinding = function () {
  4080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4081. this._cachedVertexBuffers = null;
  4082. };
  4083. Engine.prototype.createVertexBuffer = function (vertices) {
  4084. var vbo = this._gl.createBuffer();
  4085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4086. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4087. this._resetVertexBufferBinding();
  4088. vbo.references = 1;
  4089. return vbo;
  4090. };
  4091. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4092. var vbo = this._gl.createBuffer();
  4093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4094. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4095. this._resetVertexBufferBinding();
  4096. vbo.references = 1;
  4097. return vbo;
  4098. };
  4099. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4101. if (offset === undefined) {
  4102. offset = 0;
  4103. }
  4104. if (vertices instanceof Float32Array) {
  4105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4106. }
  4107. else {
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4109. }
  4110. this._resetVertexBufferBinding();
  4111. };
  4112. Engine.prototype._resetIndexBufferBinding = function () {
  4113. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4114. this._cachedIndexBuffer = null;
  4115. };
  4116. Engine.prototype.createIndexBuffer = function (indices) {
  4117. var vbo = this._gl.createBuffer();
  4118. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4119. // Check for 32 bits indices
  4120. var arrayBuffer;
  4121. var need32Bits = false;
  4122. if (this._caps.uintIndices) {
  4123. for (var index = 0; index < indices.length; index++) {
  4124. if (indices[index] > 65535) {
  4125. need32Bits = true;
  4126. break;
  4127. }
  4128. }
  4129. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4130. }
  4131. else {
  4132. arrayBuffer = new Uint16Array(indices);
  4133. }
  4134. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4135. this._resetIndexBufferBinding();
  4136. vbo.references = 1;
  4137. vbo.is32Bits = need32Bits;
  4138. return vbo;
  4139. };
  4140. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4141. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4142. this._cachedVertexBuffers = vertexBuffer;
  4143. this._cachedEffectForVertexBuffers = effect;
  4144. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4145. var offset = 0;
  4146. for (var index = 0; index < vertexDeclaration.length; index++) {
  4147. var order = effect.getAttributeLocation(index);
  4148. if (order >= 0) {
  4149. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4150. }
  4151. offset += vertexDeclaration[index] * 4;
  4152. }
  4153. }
  4154. if (this._cachedIndexBuffer !== indexBuffer) {
  4155. this._cachedIndexBuffer = indexBuffer;
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4157. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4158. }
  4159. };
  4160. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4161. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4162. this._cachedVertexBuffers = vertexBuffers;
  4163. this._cachedEffectForVertexBuffers = effect;
  4164. var attributes = effect.getAttributesNames();
  4165. for (var index = 0; index < attributes.length; index++) {
  4166. var order = effect.getAttributeLocation(index);
  4167. if (order >= 0) {
  4168. var vertexBuffer = vertexBuffers[attributes[index]];
  4169. if (!vertexBuffer) {
  4170. continue;
  4171. }
  4172. var stride = vertexBuffer.getStrideSize();
  4173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4174. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4175. }
  4176. }
  4177. }
  4178. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4179. this._cachedIndexBuffer = indexBuffer;
  4180. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4181. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4182. }
  4183. };
  4184. Engine.prototype._releaseBuffer = function (buffer) {
  4185. buffer.references--;
  4186. if (buffer.references === 0) {
  4187. this._gl.deleteBuffer(buffer);
  4188. return true;
  4189. }
  4190. return false;
  4191. };
  4192. Engine.prototype.createInstancesBuffer = function (capacity) {
  4193. var buffer = this._gl.createBuffer();
  4194. buffer.capacity = capacity;
  4195. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4196. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4197. return buffer;
  4198. };
  4199. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4200. this._gl.deleteBuffer(buffer);
  4201. };
  4202. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4203. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4205. for (var index = 0; index < 4; index++) {
  4206. var offsetLocation = offsetLocations[index];
  4207. this._gl.enableVertexAttribArray(offsetLocation);
  4208. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4209. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4210. }
  4211. };
  4212. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4214. for (var index = 0; index < 4; index++) {
  4215. var offsetLocation = offsetLocations[index];
  4216. this._gl.disableVertexAttribArray(offsetLocation);
  4217. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4218. }
  4219. };
  4220. Engine.prototype.applyStates = function () {
  4221. this._depthCullingState.apply(this._gl);
  4222. this._alphaState.apply(this._gl);
  4223. };
  4224. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4225. // Apply states
  4226. this.applyStates();
  4227. this._drawCalls++;
  4228. // Render
  4229. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4230. if (instancesCount) {
  4231. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4232. return;
  4233. }
  4234. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4235. };
  4236. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4237. // Apply states
  4238. this.applyStates();
  4239. this._drawCalls++;
  4240. if (instancesCount) {
  4241. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4242. return;
  4243. }
  4244. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4245. };
  4246. // Shaders
  4247. Engine.prototype._releaseEffect = function (effect) {
  4248. if (this._compiledEffects[effect._key]) {
  4249. delete this._compiledEffects[effect._key];
  4250. if (effect.getProgram()) {
  4251. this._gl.deleteProgram(effect.getProgram());
  4252. }
  4253. }
  4254. };
  4255. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4256. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4257. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4258. var name = vertex + "+" + fragment + "@" + defines;
  4259. if (this._compiledEffects[name]) {
  4260. return this._compiledEffects[name];
  4261. }
  4262. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4263. effect._key = name;
  4264. this._compiledEffects[name] = effect;
  4265. return effect;
  4266. };
  4267. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4268. if (uniformsNames === void 0) { uniformsNames = []; }
  4269. if (samplers === void 0) { samplers = []; }
  4270. if (defines === void 0) { defines = ""; }
  4271. return this.createEffect({
  4272. vertex: "particles",
  4273. fragmentElement: fragmentName
  4274. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4275. };
  4276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4277. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4278. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4279. var shaderProgram = this._gl.createProgram();
  4280. this._gl.attachShader(shaderProgram, vertexShader);
  4281. this._gl.attachShader(shaderProgram, fragmentShader);
  4282. this._gl.linkProgram(shaderProgram);
  4283. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4284. if (!linked) {
  4285. var error = this._gl.getProgramInfoLog(shaderProgram);
  4286. if (error) {
  4287. throw new Error(error);
  4288. }
  4289. }
  4290. this._gl.deleteShader(vertexShader);
  4291. this._gl.deleteShader(fragmentShader);
  4292. return shaderProgram;
  4293. };
  4294. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4295. var results = [];
  4296. for (var index = 0; index < uniformsNames.length; index++) {
  4297. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4298. }
  4299. return results;
  4300. };
  4301. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4302. var results = [];
  4303. for (var index = 0; index < attributesNames.length; index++) {
  4304. try {
  4305. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4306. }
  4307. catch (e) {
  4308. results.push(-1);
  4309. }
  4310. }
  4311. return results;
  4312. };
  4313. Engine.prototype.enableEffect = function (effect) {
  4314. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4315. if (effect && effect.onBind) {
  4316. effect.onBind(effect);
  4317. }
  4318. return;
  4319. }
  4320. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4321. // Use program
  4322. this._gl.useProgram(effect.getProgram());
  4323. for (var i in this._vertexAttribArrays) {
  4324. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4325. continue;
  4326. }
  4327. this._vertexAttribArrays[i] = false;
  4328. this._gl.disableVertexAttribArray(i);
  4329. }
  4330. var attributesCount = effect.getAttributesCount();
  4331. for (var index = 0; index < attributesCount; index++) {
  4332. // Attributes
  4333. var order = effect.getAttributeLocation(index);
  4334. if (order >= 0) {
  4335. this._vertexAttribArrays[order] = true;
  4336. this._gl.enableVertexAttribArray(order);
  4337. }
  4338. }
  4339. this._currentEffect = effect;
  4340. if (effect.onBind) {
  4341. effect.onBind(effect);
  4342. }
  4343. };
  4344. Engine.prototype.setArray = function (uniform, array) {
  4345. if (!uniform)
  4346. return;
  4347. this._gl.uniform1fv(uniform, array);
  4348. };
  4349. Engine.prototype.setArray2 = function (uniform, array) {
  4350. if (!uniform || array.length % 2 !== 0)
  4351. return;
  4352. this._gl.uniform2fv(uniform, array);
  4353. };
  4354. Engine.prototype.setArray3 = function (uniform, array) {
  4355. if (!uniform || array.length % 3 !== 0)
  4356. return;
  4357. this._gl.uniform3fv(uniform, array);
  4358. };
  4359. Engine.prototype.setArray4 = function (uniform, array) {
  4360. if (!uniform || array.length % 4 !== 0)
  4361. return;
  4362. this._gl.uniform4fv(uniform, array);
  4363. };
  4364. Engine.prototype.setMatrices = function (uniform, matrices) {
  4365. if (!uniform)
  4366. return;
  4367. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4368. };
  4369. Engine.prototype.setMatrix = function (uniform, matrix) {
  4370. if (!uniform)
  4371. return;
  4372. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4373. };
  4374. Engine.prototype.setFloat = function (uniform, value) {
  4375. if (!uniform)
  4376. return;
  4377. this._gl.uniform1f(uniform, value);
  4378. };
  4379. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4380. if (!uniform)
  4381. return;
  4382. this._gl.uniform2f(uniform, x, y);
  4383. };
  4384. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4385. if (!uniform)
  4386. return;
  4387. this._gl.uniform3f(uniform, x, y, z);
  4388. };
  4389. Engine.prototype.setBool = function (uniform, bool) {
  4390. if (!uniform)
  4391. return;
  4392. this._gl.uniform1i(uniform, bool);
  4393. };
  4394. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4395. if (!uniform)
  4396. return;
  4397. this._gl.uniform4f(uniform, x, y, z, w);
  4398. };
  4399. Engine.prototype.setColor3 = function (uniform, color3) {
  4400. if (!uniform)
  4401. return;
  4402. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4403. };
  4404. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4405. if (!uniform)
  4406. return;
  4407. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4408. };
  4409. // States
  4410. Engine.prototype.setState = function (culling, force) {
  4411. // Culling
  4412. if (this._depthCullingState.cull !== culling || force) {
  4413. if (culling) {
  4414. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4415. this._depthCullingState.cull = true;
  4416. }
  4417. else {
  4418. this._depthCullingState.cull = false;
  4419. }
  4420. }
  4421. };
  4422. Engine.prototype.setDepthBuffer = function (enable) {
  4423. this._depthCullingState.depthTest = enable;
  4424. };
  4425. Engine.prototype.getDepthWrite = function () {
  4426. return this._depthCullingState.depthMask;
  4427. };
  4428. Engine.prototype.setDepthWrite = function (enable) {
  4429. this._depthCullingState.depthMask = enable;
  4430. };
  4431. Engine.prototype.setColorWrite = function (enable) {
  4432. this._gl.colorMask(enable, enable, enable, enable);
  4433. };
  4434. Engine.prototype.setAlphaMode = function (mode) {
  4435. switch (mode) {
  4436. case Engine.ALPHA_DISABLE:
  4437. this.setDepthWrite(true);
  4438. this._alphaState.alphaBlend = false;
  4439. break;
  4440. case Engine.ALPHA_COMBINE:
  4441. this.setDepthWrite(false);
  4442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4443. this._alphaState.alphaBlend = true;
  4444. break;
  4445. case Engine.ALPHA_ADD:
  4446. this.setDepthWrite(false);
  4447. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4448. this._alphaState.alphaBlend = true;
  4449. break;
  4450. }
  4451. this._alphaMode = mode;
  4452. };
  4453. Engine.prototype.getAlphaMode = function () {
  4454. return this._alphaMode;
  4455. };
  4456. Engine.prototype.setAlphaTesting = function (enable) {
  4457. this._alphaTest = enable;
  4458. };
  4459. Engine.prototype.getAlphaTesting = function () {
  4460. return this._alphaTest;
  4461. };
  4462. // Textures
  4463. Engine.prototype.wipeCaches = function () {
  4464. this._activeTexturesCache = [];
  4465. this._currentEffect = null;
  4466. this._depthCullingState.reset();
  4467. this._alphaState.reset();
  4468. this._cachedVertexBuffers = null;
  4469. this._cachedIndexBuffer = null;
  4470. this._cachedEffectForVertexBuffers = null;
  4471. };
  4472. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4473. var gl = this._gl;
  4474. gl.bindTexture(gl.TEXTURE_2D, texture);
  4475. var magFilter = gl.NEAREST;
  4476. var minFilter = gl.NEAREST;
  4477. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4478. magFilter = gl.LINEAR;
  4479. minFilter = gl.LINEAR;
  4480. }
  4481. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4482. magFilter = gl.LINEAR;
  4483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4484. }
  4485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4487. gl.bindTexture(gl.TEXTURE_2D, null);
  4488. texture.samplingMode = samplingMode;
  4489. };
  4490. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4491. var _this = this;
  4492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4493. if (onLoad === void 0) { onLoad = null; }
  4494. if (onError === void 0) { onError = null; }
  4495. if (buffer === void 0) { buffer = null; }
  4496. var texture = this._gl.createTexture();
  4497. var extension;
  4498. var fromData = false;
  4499. if (url.substr(0, 5) === "data:") {
  4500. fromData = true;
  4501. }
  4502. if (!fromData)
  4503. extension = url.substr(url.length - 4, 4).toLowerCase();
  4504. else {
  4505. var oldUrl = url;
  4506. fromData = oldUrl.split(':');
  4507. url = oldUrl;
  4508. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4509. }
  4510. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4511. var isTGA = (extension === ".tga");
  4512. scene._addPendingData(texture);
  4513. texture.url = url;
  4514. texture.noMipmap = noMipmap;
  4515. texture.references = 1;
  4516. this._loadedTexturesCache.push(texture);
  4517. var onerror = function () {
  4518. scene._removePendingData(texture);
  4519. if (onError) {
  4520. onError();
  4521. }
  4522. };
  4523. if (isTGA) {
  4524. var callback = function (arrayBuffer) {
  4525. var data = new Uint8Array(arrayBuffer);
  4526. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4527. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4528. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4529. if (onLoad) {
  4530. onLoad();
  4531. }
  4532. }, samplingMode);
  4533. };
  4534. if (!(fromData instanceof Array))
  4535. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4536. callback(arrayBuffer);
  4537. }, onerror, scene.database, true);
  4538. else
  4539. callback(buffer);
  4540. }
  4541. else if (isDDS) {
  4542. callback = function (data) {
  4543. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4544. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4545. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4546. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4547. if (onLoad) {
  4548. onLoad();
  4549. }
  4550. }, samplingMode);
  4551. };
  4552. if (!(fromData instanceof Array))
  4553. BABYLON.Tools.LoadFile(url, function (data) {
  4554. callback(data);
  4555. }, onerror, scene.database, true);
  4556. else
  4557. callback(buffer);
  4558. }
  4559. else {
  4560. var onload = function (img) {
  4561. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4562. var isPot = (img.width === potWidth && img.height === potHeight);
  4563. if (!isPot) {
  4564. _this._workingCanvas.width = potWidth;
  4565. _this._workingCanvas.height = potHeight;
  4566. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4567. _this._workingContext.imageSmoothingEnabled = false;
  4568. _this._workingContext.mozImageSmoothingEnabled = false;
  4569. _this._workingContext.oImageSmoothingEnabled = false;
  4570. _this._workingContext.webkitImageSmoothingEnabled = false;
  4571. _this._workingContext.msImageSmoothingEnabled = false;
  4572. }
  4573. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4574. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4575. _this._workingContext.imageSmoothingEnabled = true;
  4576. _this._workingContext.mozImageSmoothingEnabled = true;
  4577. _this._workingContext.oImageSmoothingEnabled = true;
  4578. _this._workingContext.webkitImageSmoothingEnabled = true;
  4579. _this._workingContext.msImageSmoothingEnabled = true;
  4580. }
  4581. }
  4582. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4583. if (onLoad) {
  4584. onLoad();
  4585. }
  4586. }, samplingMode);
  4587. };
  4588. if (!(fromData instanceof Array))
  4589. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4590. else
  4591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4592. }
  4593. return texture;
  4594. };
  4595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4596. var texture = this._gl.createTexture();
  4597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4599. // Format
  4600. var internalFormat = this._gl.RGBA;
  4601. switch (format) {
  4602. case Engine.TEXTUREFORMAT_ALPHA:
  4603. internalFormat = this._gl.ALPHA;
  4604. break;
  4605. case Engine.TEXTUREFORMAT_LUMINANCE:
  4606. internalFormat = this._gl.LUMINANCE;
  4607. break;
  4608. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4609. internalFormat = this._gl.LUMINANCE_ALPHA;
  4610. break;
  4611. case Engine.TEXTUREFORMAT_RGB:
  4612. internalFormat = this._gl.RGB;
  4613. break;
  4614. case Engine.TEXTUREFORMAT_RGBA:
  4615. internalFormat = this._gl.RGBA;
  4616. break;
  4617. }
  4618. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4619. if (generateMipMaps) {
  4620. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4621. }
  4622. // Filters
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4627. this._activeTexturesCache = [];
  4628. texture._baseWidth = width;
  4629. texture._baseHeight = height;
  4630. texture._width = width;
  4631. texture._height = height;
  4632. texture.isReady = true;
  4633. texture.references = 1;
  4634. texture.samplingMode = samplingMode;
  4635. this._loadedTexturesCache.push(texture);
  4636. return texture;
  4637. };
  4638. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4639. var texture = this._gl.createTexture();
  4640. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4641. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4642. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4643. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._activeTexturesCache = [];
  4648. texture._baseWidth = width;
  4649. texture._baseHeight = height;
  4650. texture._width = width;
  4651. texture._height = height;
  4652. texture.isReady = false;
  4653. texture.generateMipMaps = generateMipMaps;
  4654. texture.references = 1;
  4655. texture.samplingMode = samplingMode;
  4656. this._loadedTexturesCache.push(texture);
  4657. return texture;
  4658. };
  4659. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4660. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4661. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4663. if (texture.generateMipMaps) {
  4664. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4665. }
  4666. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4667. this._activeTexturesCache = [];
  4668. texture.isReady = true;
  4669. };
  4670. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4671. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4672. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4673. // Scale the video if it is a NPOT using the current working canvas
  4674. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4675. if (!texture._workingCanvas) {
  4676. texture._workingCanvas = document.createElement("canvas");
  4677. texture._workingContext = texture._workingCanvas.getContext("2d");
  4678. texture._workingCanvas.width = texture._width;
  4679. texture._workingCanvas.height = texture._height;
  4680. }
  4681. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4682. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4683. }
  4684. else {
  4685. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4686. }
  4687. if (texture.generateMipMaps) {
  4688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4689. }
  4690. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4691. this._activeTexturesCache = [];
  4692. texture.isReady = true;
  4693. };
  4694. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4695. // old version had a "generateMipMaps" arg instead of options.
  4696. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4697. // in the same way, generateDepthBuffer is defaulted to true
  4698. var generateMipMaps = false;
  4699. var generateDepthBuffer = true;
  4700. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4701. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4702. if (options !== undefined) {
  4703. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4704. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4705. type = options.type === undefined ? type : options.type;
  4706. if (options.samplingMode !== undefined) {
  4707. samplingMode = options.samplingMode;
  4708. }
  4709. if (type === Engine.TEXTURETYPE_FLOAT) {
  4710. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4711. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4712. }
  4713. }
  4714. var gl = this._gl;
  4715. var texture = gl.createTexture();
  4716. gl.bindTexture(gl.TEXTURE_2D, texture);
  4717. var width = size.width || size;
  4718. var height = size.height || size;
  4719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4720. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4721. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4722. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4723. }
  4724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4728. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4729. var depthBuffer;
  4730. // Create the depth buffer
  4731. if (generateDepthBuffer) {
  4732. depthBuffer = gl.createRenderbuffer();
  4733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4734. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4735. }
  4736. // Create the framebuffer
  4737. var framebuffer = gl.createFramebuffer();
  4738. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4739. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4740. if (generateDepthBuffer) {
  4741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4742. }
  4743. // Unbind
  4744. gl.bindTexture(gl.TEXTURE_2D, null);
  4745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4746. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4747. texture._framebuffer = framebuffer;
  4748. if (generateDepthBuffer) {
  4749. texture._depthBuffer = depthBuffer;
  4750. }
  4751. texture._width = width;
  4752. texture._height = height;
  4753. texture.isReady = true;
  4754. texture.generateMipMaps = generateMipMaps;
  4755. texture.references = 1;
  4756. texture.samplingMode = samplingMode;
  4757. this._activeTexturesCache = [];
  4758. this._loadedTexturesCache.push(texture);
  4759. return texture;
  4760. };
  4761. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4762. var _this = this;
  4763. var gl = this._gl;
  4764. var texture = gl.createTexture();
  4765. texture.isCube = true;
  4766. texture.url = rootUrl;
  4767. texture.references = 1;
  4768. this._loadedTexturesCache.push(texture);
  4769. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4770. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4771. if (isDDS) {
  4772. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4773. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4774. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4775. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4776. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4778. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4780. }
  4781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4785. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4786. _this._activeTexturesCache = [];
  4787. texture._width = info.width;
  4788. texture._height = info.height;
  4789. texture.isReady = true;
  4790. }, null, null, true);
  4791. }
  4792. else {
  4793. cascadeLoad(rootUrl, scene, function (imgs) {
  4794. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4795. var height = width;
  4796. _this._workingCanvas.width = width;
  4797. _this._workingCanvas.height = height;
  4798. var faces = [
  4799. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4800. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4801. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4802. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4803. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4804. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4805. ];
  4806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4808. for (var index = 0; index < faces.length; index++) {
  4809. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4810. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4811. }
  4812. if (!noMipmap) {
  4813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4814. }
  4815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4819. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4820. _this._activeTexturesCache = [];
  4821. texture._width = width;
  4822. texture._height = height;
  4823. texture.isReady = true;
  4824. }, extensions);
  4825. }
  4826. return texture;
  4827. };
  4828. Engine.prototype._releaseTexture = function (texture) {
  4829. var gl = this._gl;
  4830. if (texture._framebuffer) {
  4831. gl.deleteFramebuffer(texture._framebuffer);
  4832. }
  4833. if (texture._depthBuffer) {
  4834. gl.deleteRenderbuffer(texture._depthBuffer);
  4835. }
  4836. gl.deleteTexture(texture);
  4837. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4839. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4841. this._activeTexturesCache[channel] = null;
  4842. }
  4843. var index = this._loadedTexturesCache.indexOf(texture);
  4844. if (index !== -1) {
  4845. this._loadedTexturesCache.splice(index, 1);
  4846. }
  4847. };
  4848. Engine.prototype.bindSamplers = function (effect) {
  4849. this._gl.useProgram(effect.getProgram());
  4850. var samplers = effect.getSamplers();
  4851. for (var index = 0; index < samplers.length; index++) {
  4852. var uniform = effect.getUniform(samplers[index]);
  4853. this._gl.uniform1i(uniform, index);
  4854. }
  4855. this._currentEffect = null;
  4856. };
  4857. Engine.prototype._bindTexture = function (channel, texture) {
  4858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4859. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4860. this._activeTexturesCache[channel] = null;
  4861. };
  4862. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4863. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4864. };
  4865. Engine.prototype.setTexture = function (channel, texture) {
  4866. if (channel < 0) {
  4867. return;
  4868. }
  4869. // Not ready?
  4870. if (!texture || !texture.isReady()) {
  4871. if (this._activeTexturesCache[channel] != null) {
  4872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4875. this._activeTexturesCache[channel] = null;
  4876. }
  4877. return;
  4878. }
  4879. // Video
  4880. if (texture instanceof BABYLON.VideoTexture) {
  4881. if (texture.update()) {
  4882. this._activeTexturesCache[channel] = null;
  4883. }
  4884. }
  4885. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4886. texture.delayLoad();
  4887. return;
  4888. }
  4889. if (this._activeTexturesCache[channel] === texture) {
  4890. return;
  4891. }
  4892. this._activeTexturesCache[channel] = texture;
  4893. var internalTexture = texture.getInternalTexture();
  4894. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4895. if (internalTexture.isCube) {
  4896. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4903. }
  4904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4905. }
  4906. else {
  4907. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4908. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4909. internalTexture._cachedWrapU = texture.wrapU;
  4910. switch (texture.wrapU) {
  4911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4913. break;
  4914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4916. break;
  4917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4919. break;
  4920. }
  4921. }
  4922. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4923. internalTexture._cachedWrapV = texture.wrapV;
  4924. switch (texture.wrapV) {
  4925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4927. break;
  4928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4930. break;
  4931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4933. break;
  4934. }
  4935. }
  4936. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4937. }
  4938. };
  4939. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4941. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4942. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4943. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4944. }
  4945. };
  4946. Engine.prototype.readPixels = function (x, y, width, height) {
  4947. var data = new Uint8Array(height * width * 4);
  4948. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4949. return data;
  4950. };
  4951. // Dispose
  4952. Engine.prototype.dispose = function () {
  4953. this.hideLoadingUI();
  4954. this.stopRenderLoop();
  4955. while (this.scenes.length) {
  4956. this.scenes[0].dispose();
  4957. }
  4958. // Release audio engine
  4959. Engine.audioEngine.dispose();
  4960. for (var name in this._compiledEffects) {
  4961. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4962. }
  4963. for (var i in this._vertexAttribArrays) {
  4964. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4965. continue;
  4966. }
  4967. this._gl.disableVertexAttribArray(i);
  4968. }
  4969. // Events
  4970. window.removeEventListener("blur", this._onBlur);
  4971. window.removeEventListener("focus", this._onFocus);
  4972. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4973. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4974. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4975. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4976. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4977. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4978. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4979. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4980. };
  4981. // Loading screen
  4982. Engine.prototype.displayLoadingUI = function () {
  4983. var _this = this;
  4984. this._loadingDiv = document.createElement("div");
  4985. this._loadingDiv.style.opacity = "0";
  4986. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4987. // Loading text
  4988. this._loadingTextDiv = document.createElement("div");
  4989. this._loadingTextDiv.style.position = "absolute";
  4990. this._loadingTextDiv.style.left = "0";
  4991. this._loadingTextDiv.style.top = "50%";
  4992. this._loadingTextDiv.style.marginTop = "80px";
  4993. this._loadingTextDiv.style.width = "100%";
  4994. this._loadingTextDiv.style.height = "20px";
  4995. this._loadingTextDiv.style.fontFamily = "Arial";
  4996. this._loadingTextDiv.style.fontSize = "14px";
  4997. this._loadingTextDiv.style.color = "white";
  4998. this._loadingTextDiv.style.textAlign = "center";
  4999. this._loadingTextDiv.innerHTML = "Loading";
  5000. this._loadingDiv.appendChild(this._loadingTextDiv);
  5001. // Loading img
  5002. var imgBack = new Image();
  5003. 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==";
  5004. imgBack.style.position = "absolute";
  5005. imgBack.style.left = "50%";
  5006. imgBack.style.top = "50%";
  5007. imgBack.style.marginLeft = "-50px";
  5008. imgBack.style.marginTop = "-50px";
  5009. imgBack.style.transition = "transform 1.0s ease";
  5010. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5011. var deg = 360;
  5012. var onTransitionEnd = function () {
  5013. deg += 360;
  5014. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5015. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5016. };
  5017. imgBack.addEventListener("transitionend", onTransitionEnd);
  5018. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5019. this._loadingDiv.appendChild(imgBack);
  5020. // front image
  5021. var imgFront = new Image();
  5022. 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=";
  5023. imgFront.style.position = "absolute";
  5024. imgFront.style.left = "50%";
  5025. imgFront.style.top = "50%";
  5026. imgFront.style.marginLeft = "-50px";
  5027. imgFront.style.marginTop = "-50px";
  5028. this._loadingDiv.appendChild(imgFront);
  5029. // Resize
  5030. this._resizeLoadingUI = function () {
  5031. var canvasRect = _this.getRenderingCanvasClientRect();
  5032. _this._loadingDiv.style.position = "absolute";
  5033. _this._loadingDiv.style.left = canvasRect.left + "px";
  5034. _this._loadingDiv.style.top = canvasRect.top + "px";
  5035. _this._loadingDiv.style.width = canvasRect.width + "px";
  5036. _this._loadingDiv.style.height = canvasRect.height + "px";
  5037. };
  5038. this._resizeLoadingUI();
  5039. window.addEventListener("resize", this._resizeLoadingUI);
  5040. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5041. document.body.appendChild(this._loadingDiv);
  5042. setTimeout(function () {
  5043. _this._loadingDiv.style.opacity = "1";
  5044. imgBack.style.transform = "rotateZ(360deg)";
  5045. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5046. }, 0);
  5047. };
  5048. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5049. set: function (text) {
  5050. if (!this._loadingDiv) {
  5051. return;
  5052. }
  5053. this._loadingTextDiv.innerHTML = text;
  5054. },
  5055. enumerable: true,
  5056. configurable: true
  5057. });
  5058. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5059. get: function () {
  5060. return this._loadingDivBackgroundColor;
  5061. },
  5062. set: function (color) {
  5063. this._loadingDivBackgroundColor = color;
  5064. if (!this._loadingDiv) {
  5065. return;
  5066. }
  5067. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5068. },
  5069. enumerable: true,
  5070. configurable: true
  5071. });
  5072. Engine.prototype.hideLoadingUI = function () {
  5073. var _this = this;
  5074. if (!this._loadingDiv) {
  5075. return;
  5076. }
  5077. var onTransitionEnd = function () {
  5078. if (!_this._loadingDiv) {
  5079. return;
  5080. }
  5081. document.body.removeChild(_this._loadingDiv);
  5082. window.removeEventListener("resize", _this._resizeLoadingUI);
  5083. _this._loadingDiv = null;
  5084. };
  5085. this._loadingDiv.style.opacity = "0";
  5086. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5087. };
  5088. // FPS
  5089. Engine.prototype.getFps = function () {
  5090. return this.fps;
  5091. };
  5092. Engine.prototype.getDeltaTime = function () {
  5093. return this.deltaTime;
  5094. };
  5095. Engine.prototype._measureFps = function () {
  5096. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5097. var length = this.previousFramesDuration.length;
  5098. if (length >= 2) {
  5099. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5100. }
  5101. if (length >= this.fpsRange) {
  5102. if (length > this.fpsRange) {
  5103. this.previousFramesDuration.splice(0, 1);
  5104. length = this.previousFramesDuration.length;
  5105. }
  5106. var sum = 0;
  5107. for (var id = 0; id < length - 1; id++) {
  5108. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5109. }
  5110. this.fps = 1000.0 / (sum / (length - 1));
  5111. }
  5112. };
  5113. // Statics
  5114. Engine.isSupported = function () {
  5115. try {
  5116. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5117. if (navigator.isCocoonJS) {
  5118. return true;
  5119. }
  5120. var tempcanvas = document.createElement("canvas");
  5121. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5122. return gl != null && !!window.WebGLRenderingContext;
  5123. }
  5124. catch (e) {
  5125. return false;
  5126. }
  5127. };
  5128. // Const statics
  5129. Engine._ALPHA_DISABLE = 0;
  5130. Engine._ALPHA_ADD = 1;
  5131. Engine._ALPHA_COMBINE = 2;
  5132. Engine._DELAYLOADSTATE_NONE = 0;
  5133. Engine._DELAYLOADSTATE_LOADED = 1;
  5134. Engine._DELAYLOADSTATE_LOADING = 2;
  5135. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5136. Engine._TEXTUREFORMAT_ALPHA = 0;
  5137. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5138. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5139. Engine._TEXTUREFORMAT_RGB = 4;
  5140. Engine._TEXTUREFORMAT_RGBA = 4;
  5141. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5142. Engine._TEXTURETYPE_FLOAT = 1;
  5143. // Updatable statics so stick with vars here
  5144. Engine.Epsilon = 0.001;
  5145. Engine.CollisionsEpsilon = 0.001;
  5146. Engine.ShadersRepository = "Babylon/Shaders/";
  5147. return Engine;
  5148. })();
  5149. BABYLON.Engine = Engine;
  5150. })(BABYLON || (BABYLON = {}));
  5151. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5152. (function (BABYLON) {
  5153. /**
  5154. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5155. */
  5156. var Node = (function () {
  5157. /**
  5158. * @constructor
  5159. * @param {string} name - the name and id to be given to this node
  5160. * @param {BABYLON.Scene} the scene this node will be added to
  5161. */
  5162. function Node(name, scene) {
  5163. this.state = "";
  5164. this.animations = new Array();
  5165. this._childrenFlag = -1;
  5166. this._isEnabled = true;
  5167. this._isReady = true;
  5168. this._currentRenderId = -1;
  5169. this.name = name;
  5170. this.id = name;
  5171. this._scene = scene;
  5172. this._initCache();
  5173. }
  5174. Node.prototype.getScene = function () {
  5175. return this._scene;
  5176. };
  5177. Node.prototype.getEngine = function () {
  5178. return this._scene.getEngine();
  5179. };
  5180. // override it in derived class
  5181. Node.prototype.getWorldMatrix = function () {
  5182. return BABYLON.Matrix.Identity();
  5183. };
  5184. // override it in derived class if you add new variables to the cache
  5185. // and call the parent class method
  5186. Node.prototype._initCache = function () {
  5187. this._cache = {};
  5188. this._cache.parent = undefined;
  5189. };
  5190. Node.prototype.updateCache = function (force) {
  5191. if (!force && this.isSynchronized())
  5192. return;
  5193. this._cache.parent = this.parent;
  5194. this._updateCache();
  5195. };
  5196. // override it in derived class if you add new variables to the cache
  5197. // and call the parent class method if !ignoreParentClass
  5198. Node.prototype._updateCache = function (ignoreParentClass) {
  5199. };
  5200. // override it in derived class if you add new variables to the cache
  5201. Node.prototype._isSynchronized = function () {
  5202. return true;
  5203. };
  5204. Node.prototype.isSynchronizedWithParent = function () {
  5205. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5206. };
  5207. Node.prototype.isSynchronized = function (updateCache) {
  5208. var check = this.hasNewParent();
  5209. check = check || !this.isSynchronizedWithParent();
  5210. check = check || !this._isSynchronized();
  5211. if (updateCache)
  5212. this.updateCache(true);
  5213. return !check;
  5214. };
  5215. Node.prototype.hasNewParent = function (update) {
  5216. if (this._cache.parent === this.parent)
  5217. return false;
  5218. if (update)
  5219. this._cache.parent = this.parent;
  5220. return true;
  5221. };
  5222. /**
  5223. * Is this node ready to be used/rendered
  5224. * @return {boolean} is it ready
  5225. */
  5226. Node.prototype.isReady = function () {
  5227. return this._isReady;
  5228. };
  5229. /**
  5230. * Is this node enabled.
  5231. * If the node has a parent and is enabled, the parent will be inspected as well.
  5232. * @return {boolean} whether this node (and its parent) is enabled.
  5233. * @see setEnabled
  5234. */
  5235. Node.prototype.isEnabled = function () {
  5236. if (!this._isEnabled) {
  5237. return false;
  5238. }
  5239. if (this.parent) {
  5240. return this.parent.isEnabled();
  5241. }
  5242. return true;
  5243. };
  5244. /**
  5245. * Set the enabled state of this node.
  5246. * @param {boolean} value - the new enabled state
  5247. * @see isEnabled
  5248. */
  5249. Node.prototype.setEnabled = function (value) {
  5250. this._isEnabled = value;
  5251. };
  5252. /**
  5253. * Is this node a descendant of the given node.
  5254. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5255. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5256. * @see parent
  5257. */
  5258. Node.prototype.isDescendantOf = function (ancestor) {
  5259. if (this.parent) {
  5260. if (this.parent === ancestor) {
  5261. return true;
  5262. }
  5263. return this.parent.isDescendantOf(ancestor);
  5264. }
  5265. return false;
  5266. };
  5267. Node.prototype._getDescendants = function (list, results) {
  5268. for (var index = 0; index < list.length; index++) {
  5269. var item = list[index];
  5270. if (item.isDescendantOf(this)) {
  5271. results.push(item);
  5272. }
  5273. }
  5274. };
  5275. /**
  5276. * Will return all nodes that have this node as parent.
  5277. * @return {BABYLON.Node[]} all children nodes of all types.
  5278. */
  5279. Node.prototype.getDescendants = function () {
  5280. var results = [];
  5281. this._getDescendants(this._scene.meshes, results);
  5282. this._getDescendants(this._scene.lights, results);
  5283. this._getDescendants(this._scene.cameras, results);
  5284. return results;
  5285. };
  5286. Node.prototype._setReady = function (state) {
  5287. if (state == this._isReady) {
  5288. return;
  5289. }
  5290. if (!state) {
  5291. this._isReady = false;
  5292. return;
  5293. }
  5294. this._isReady = true;
  5295. if (this.onReady) {
  5296. this.onReady(this);
  5297. }
  5298. };
  5299. return Node;
  5300. })();
  5301. BABYLON.Node = Node;
  5302. })(BABYLON || (BABYLON = {}));
  5303. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5304. (function (BABYLON) {
  5305. var BoundingSphere = (function () {
  5306. function BoundingSphere(minimum, maximum) {
  5307. this.minimum = minimum;
  5308. this.maximum = maximum;
  5309. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5310. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5311. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5312. this.radius = distance * 0.5;
  5313. this.centerWorld = BABYLON.Vector3.Zero();
  5314. this._update(BABYLON.Matrix.Identity());
  5315. }
  5316. // Methods
  5317. BoundingSphere.prototype._update = function (world) {
  5318. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5319. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5320. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5321. };
  5322. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5323. for (var i = 0; i < 6; i++) {
  5324. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5325. return false;
  5326. }
  5327. return true;
  5328. };
  5329. BoundingSphere.prototype.intersectsPoint = function (point) {
  5330. var x = this.centerWorld.x - point.x;
  5331. var y = this.centerWorld.y - point.y;
  5332. var z = this.centerWorld.z - point.z;
  5333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5334. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5335. return false;
  5336. return true;
  5337. };
  5338. // Statics
  5339. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5340. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5341. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5342. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5344. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5345. return false;
  5346. return true;
  5347. };
  5348. return BoundingSphere;
  5349. })();
  5350. BABYLON.BoundingSphere = BoundingSphere;
  5351. })(BABYLON || (BABYLON = {}));
  5352. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5353. (function (BABYLON) {
  5354. var BoundingBox = (function () {
  5355. function BoundingBox(minimum, maximum) {
  5356. this.minimum = minimum;
  5357. this.maximum = maximum;
  5358. this.vectors = new Array();
  5359. this.vectorsWorld = new Array();
  5360. // Bounding vectors
  5361. this.vectors.push(this.minimum.clone());
  5362. this.vectors.push(this.maximum.clone());
  5363. this.vectors.push(this.minimum.clone());
  5364. this.vectors[2].x = this.maximum.x;
  5365. this.vectors.push(this.minimum.clone());
  5366. this.vectors[3].y = this.maximum.y;
  5367. this.vectors.push(this.minimum.clone());
  5368. this.vectors[4].z = this.maximum.z;
  5369. this.vectors.push(this.maximum.clone());
  5370. this.vectors[5].z = this.minimum.z;
  5371. this.vectors.push(this.maximum.clone());
  5372. this.vectors[6].x = this.minimum.x;
  5373. this.vectors.push(this.maximum.clone());
  5374. this.vectors[7].y = this.minimum.y;
  5375. // OBB
  5376. this.center = this.maximum.add(this.minimum).scale(0.5);
  5377. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5378. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5379. for (var index = 0; index < this.vectors.length; index++) {
  5380. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5381. }
  5382. this.minimumWorld = BABYLON.Vector3.Zero();
  5383. this.maximumWorld = BABYLON.Vector3.Zero();
  5384. this._update(BABYLON.Matrix.Identity());
  5385. }
  5386. // Methods
  5387. BoundingBox.prototype.getWorldMatrix = function () {
  5388. return this._worldMatrix;
  5389. };
  5390. BoundingBox.prototype._update = function (world) {
  5391. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5392. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5393. for (var index = 0; index < this.vectors.length; index++) {
  5394. var v = this.vectorsWorld[index];
  5395. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5396. if (v.x < this.minimumWorld.x)
  5397. this.minimumWorld.x = v.x;
  5398. if (v.y < this.minimumWorld.y)
  5399. this.minimumWorld.y = v.y;
  5400. if (v.z < this.minimumWorld.z)
  5401. this.minimumWorld.z = v.z;
  5402. if (v.x > this.maximumWorld.x)
  5403. this.maximumWorld.x = v.x;
  5404. if (v.y > this.maximumWorld.y)
  5405. this.maximumWorld.y = v.y;
  5406. if (v.z > this.maximumWorld.z)
  5407. this.maximumWorld.z = v.z;
  5408. }
  5409. // OBB
  5410. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5411. this.center.scaleInPlace(0.5);
  5412. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5413. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5414. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5415. this._worldMatrix = world;
  5416. };
  5417. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5418. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5419. };
  5420. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5421. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5422. };
  5423. BoundingBox.prototype.intersectsPoint = function (point) {
  5424. var delta = BABYLON.Engine.Epsilon;
  5425. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5426. return false;
  5427. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5428. return false;
  5429. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5430. return false;
  5431. return true;
  5432. };
  5433. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5434. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5435. };
  5436. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5437. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5438. return false;
  5439. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5440. return false;
  5441. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5442. return false;
  5443. return true;
  5444. };
  5445. // Statics
  5446. BoundingBox.Intersects = function (box0, box1) {
  5447. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5448. return false;
  5449. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5450. return false;
  5451. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5452. return false;
  5453. return true;
  5454. };
  5455. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5456. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5457. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5458. return (num <= (sphereRadius * sphereRadius));
  5459. };
  5460. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5461. for (var p = 0; p < 6; p++) {
  5462. for (var i = 0; i < 8; i++) {
  5463. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5464. return false;
  5465. }
  5466. }
  5467. }
  5468. return true;
  5469. };
  5470. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5471. for (var p = 0; p < 6; p++) {
  5472. var inCount = 8;
  5473. for (var i = 0; i < 8; i++) {
  5474. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5475. --inCount;
  5476. }
  5477. else {
  5478. break;
  5479. }
  5480. }
  5481. if (inCount === 0)
  5482. return false;
  5483. }
  5484. return true;
  5485. };
  5486. return BoundingBox;
  5487. })();
  5488. BABYLON.BoundingBox = BoundingBox;
  5489. })(BABYLON || (BABYLON = {}));
  5490. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5491. (function (BABYLON) {
  5492. var computeBoxExtents = function (axis, box) {
  5493. var p = BABYLON.Vector3.Dot(box.center, axis);
  5494. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5495. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5496. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5497. var r = r0 + r1 + r2;
  5498. return {
  5499. min: p - r,
  5500. max: p + r
  5501. };
  5502. };
  5503. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5504. var axisOverlap = function (axis, box0, box1) {
  5505. var result0 = computeBoxExtents(axis, box0);
  5506. var result1 = computeBoxExtents(axis, box1);
  5507. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5508. };
  5509. var BoundingInfo = (function () {
  5510. function BoundingInfo(minimum, maximum) {
  5511. this.minimum = minimum;
  5512. this.maximum = maximum;
  5513. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5514. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5515. }
  5516. // Methods
  5517. BoundingInfo.prototype._update = function (world) {
  5518. this.boundingBox._update(world);
  5519. this.boundingSphere._update(world);
  5520. };
  5521. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5522. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5523. return false;
  5524. return this.boundingBox.isInFrustum(frustumPlanes);
  5525. };
  5526. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5527. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5528. };
  5529. BoundingInfo.prototype._checkCollision = function (collider) {
  5530. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5531. };
  5532. BoundingInfo.prototype.intersectsPoint = function (point) {
  5533. if (!this.boundingSphere.centerWorld) {
  5534. return false;
  5535. }
  5536. if (!this.boundingSphere.intersectsPoint(point)) {
  5537. return false;
  5538. }
  5539. if (!this.boundingBox.intersectsPoint(point)) {
  5540. return false;
  5541. }
  5542. return true;
  5543. };
  5544. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5545. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5546. return false;
  5547. }
  5548. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5549. return false;
  5550. }
  5551. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5552. return false;
  5553. }
  5554. if (!precise) {
  5555. return true;
  5556. }
  5557. var box0 = this.boundingBox;
  5558. var box1 = boundingInfo.boundingBox;
  5559. if (!axisOverlap(box0.directions[0], box0, box1))
  5560. return false;
  5561. if (!axisOverlap(box0.directions[1], box0, box1))
  5562. return false;
  5563. if (!axisOverlap(box0.directions[2], box0, box1))
  5564. return false;
  5565. if (!axisOverlap(box1.directions[0], box0, box1))
  5566. return false;
  5567. if (!axisOverlap(box1.directions[1], box0, box1))
  5568. return false;
  5569. if (!axisOverlap(box1.directions[2], box0, box1))
  5570. return false;
  5571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5572. return false;
  5573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5574. return false;
  5575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5576. return false;
  5577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5578. return false;
  5579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5580. return false;
  5581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5582. return false;
  5583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5584. return false;
  5585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5586. return false;
  5587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5588. return false;
  5589. return true;
  5590. };
  5591. return BoundingInfo;
  5592. })();
  5593. BABYLON.BoundingInfo = BoundingInfo;
  5594. })(BABYLON || (BABYLON = {}));
  5595. //# sourceMappingURL=babylon.boundingInfo.js.map
  5596. var BABYLON;
  5597. (function (BABYLON) {
  5598. var Light = (function (_super) {
  5599. __extends(Light, _super);
  5600. function Light(name, scene) {
  5601. _super.call(this, name, scene);
  5602. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5603. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5604. this.intensity = 1.0;
  5605. this.range = Number.MAX_VALUE;
  5606. this.includedOnlyMeshes = new Array();
  5607. this.excludedMeshes = new Array();
  5608. this._excludedMeshesIds = new Array();
  5609. this._includedOnlyMeshesIds = new Array();
  5610. scene.lights.push(this);
  5611. }
  5612. Light.prototype.getShadowGenerator = function () {
  5613. return this._shadowGenerator;
  5614. };
  5615. Light.prototype.getAbsolutePosition = function () {
  5616. return BABYLON.Vector3.Zero();
  5617. };
  5618. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5619. };
  5620. Light.prototype._getWorldMatrix = function () {
  5621. return BABYLON.Matrix.Identity();
  5622. };
  5623. Light.prototype.canAffectMesh = function (mesh) {
  5624. if (!mesh) {
  5625. return true;
  5626. }
  5627. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5628. return false;
  5629. }
  5630. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. Light.prototype.getWorldMatrix = function () {
  5636. this._currentRenderId = this.getScene().getRenderId();
  5637. var worldMatrix = this._getWorldMatrix();
  5638. if (this.parent && this.parent.getWorldMatrix) {
  5639. if (!this._parentedWorldMatrix) {
  5640. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5641. }
  5642. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5643. return this._parentedWorldMatrix;
  5644. }
  5645. return worldMatrix;
  5646. };
  5647. Light.prototype.dispose = function () {
  5648. if (this._shadowGenerator) {
  5649. this._shadowGenerator.dispose();
  5650. this._shadowGenerator = null;
  5651. }
  5652. // Remove from scene
  5653. var index = this.getScene().lights.indexOf(this);
  5654. this.getScene().lights.splice(index, 1);
  5655. };
  5656. return Light;
  5657. })(BABYLON.Node);
  5658. BABYLON.Light = Light;
  5659. })(BABYLON || (BABYLON = {}));
  5660. //# sourceMappingURL=babylon.light.js.map
  5661. var BABYLON;
  5662. (function (BABYLON) {
  5663. var PointLight = (function (_super) {
  5664. __extends(PointLight, _super);
  5665. function PointLight(name, position, scene) {
  5666. _super.call(this, name, scene);
  5667. this.position = position;
  5668. }
  5669. PointLight.prototype.getAbsolutePosition = function () {
  5670. return this._transformedPosition ? this._transformedPosition : this.position;
  5671. };
  5672. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5673. if (this.parent && this.parent.getWorldMatrix) {
  5674. if (!this._transformedPosition) {
  5675. this._transformedPosition = BABYLON.Vector3.Zero();
  5676. }
  5677. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5678. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5679. return;
  5680. }
  5681. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5682. };
  5683. PointLight.prototype.getShadowGenerator = function () {
  5684. return null;
  5685. };
  5686. PointLight.prototype._getWorldMatrix = function () {
  5687. if (!this._worldMatrix) {
  5688. this._worldMatrix = BABYLON.Matrix.Identity();
  5689. }
  5690. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5691. return this._worldMatrix;
  5692. };
  5693. return PointLight;
  5694. })(BABYLON.Light);
  5695. BABYLON.PointLight = PointLight;
  5696. })(BABYLON || (BABYLON = {}));
  5697. //# sourceMappingURL=babylon.pointLight.js.map
  5698. var BABYLON;
  5699. (function (BABYLON) {
  5700. var SpotLight = (function (_super) {
  5701. __extends(SpotLight, _super);
  5702. function SpotLight(name, position, direction, angle, exponent, scene) {
  5703. _super.call(this, name, scene);
  5704. this.position = position;
  5705. this.direction = direction;
  5706. this.angle = angle;
  5707. this.exponent = exponent;
  5708. }
  5709. SpotLight.prototype.getAbsolutePosition = function () {
  5710. return this.transformedPosition ? this.transformedPosition : this.position;
  5711. };
  5712. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5713. var activeCamera = this.getScene().activeCamera;
  5714. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5715. };
  5716. SpotLight.prototype.supportsVSM = function () {
  5717. return true;
  5718. };
  5719. SpotLight.prototype.needRefreshPerFrame = function () {
  5720. return false;
  5721. };
  5722. SpotLight.prototype.setDirectionToTarget = function (target) {
  5723. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5724. return this.direction;
  5725. };
  5726. SpotLight.prototype.computeTransformedPosition = function () {
  5727. if (this.parent && this.parent.getWorldMatrix) {
  5728. if (!this.transformedPosition) {
  5729. this.transformedPosition = BABYLON.Vector3.Zero();
  5730. }
  5731. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5732. return true;
  5733. }
  5734. return false;
  5735. };
  5736. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5737. var normalizeDirection;
  5738. if (this.parent && this.parent.getWorldMatrix) {
  5739. if (!this._transformedDirection) {
  5740. this._transformedDirection = BABYLON.Vector3.Zero();
  5741. }
  5742. this.computeTransformedPosition();
  5743. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5744. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5745. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5746. }
  5747. else {
  5748. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5749. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5750. }
  5751. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5752. };
  5753. SpotLight.prototype._getWorldMatrix = function () {
  5754. if (!this._worldMatrix) {
  5755. this._worldMatrix = BABYLON.Matrix.Identity();
  5756. }
  5757. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5758. return this._worldMatrix;
  5759. };
  5760. return SpotLight;
  5761. })(BABYLON.Light);
  5762. BABYLON.SpotLight = SpotLight;
  5763. })(BABYLON || (BABYLON = {}));
  5764. //# sourceMappingURL=babylon.spotLight.js.map
  5765. var BABYLON;
  5766. (function (BABYLON) {
  5767. var DirectionalLight = (function (_super) {
  5768. __extends(DirectionalLight, _super);
  5769. function DirectionalLight(name, direction, scene) {
  5770. _super.call(this, name, scene);
  5771. this.direction = direction;
  5772. this.shadowOrthoScale = 0.1;
  5773. this.position = direction.scale(-1);
  5774. }
  5775. DirectionalLight.prototype.getAbsolutePosition = function () {
  5776. return this.transformedPosition ? this.transformedPosition : this.position;
  5777. };
  5778. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5779. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5780. return this.direction;
  5781. };
  5782. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5783. var orthoLeft = Number.MAX_VALUE;
  5784. var orthoRight = Number.MIN_VALUE;
  5785. var orthoTop = Number.MIN_VALUE;
  5786. var orthoBottom = Number.MAX_VALUE;
  5787. var tempVector3 = BABYLON.Vector3.Zero();
  5788. var activeCamera = this.getScene().activeCamera;
  5789. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5790. var mesh = renderList[meshIndex];
  5791. if (!mesh) {
  5792. continue;
  5793. }
  5794. var boundingInfo = mesh.getBoundingInfo();
  5795. if (!boundingInfo) {
  5796. continue;
  5797. }
  5798. var boundingBox = boundingInfo.boundingBox;
  5799. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5800. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5801. if (tempVector3.x < orthoLeft)
  5802. orthoLeft = tempVector3.x;
  5803. if (tempVector3.y < orthoBottom)
  5804. orthoBottom = tempVector3.y;
  5805. if (tempVector3.x > orthoRight)
  5806. orthoRight = tempVector3.x;
  5807. if (tempVector3.y > orthoTop)
  5808. orthoTop = tempVector3.y;
  5809. }
  5810. }
  5811. var xOffset = orthoRight - orthoLeft;
  5812. var yOffset = orthoTop - orthoBottom;
  5813. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5814. };
  5815. DirectionalLight.prototype.supportsVSM = function () {
  5816. return true;
  5817. };
  5818. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5819. return true;
  5820. };
  5821. DirectionalLight.prototype.computeTransformedPosition = function () {
  5822. if (this.parent && this.parent.getWorldMatrix) {
  5823. if (!this.transformedPosition) {
  5824. this.transformedPosition = BABYLON.Vector3.Zero();
  5825. }
  5826. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5827. return true;
  5828. }
  5829. return false;
  5830. };
  5831. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5832. if (this.parent && this.parent.getWorldMatrix) {
  5833. if (!this._transformedDirection) {
  5834. this._transformedDirection = BABYLON.Vector3.Zero();
  5835. }
  5836. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5837. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5838. return;
  5839. }
  5840. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5841. };
  5842. DirectionalLight.prototype._getWorldMatrix = function () {
  5843. if (!this._worldMatrix) {
  5844. this._worldMatrix = BABYLON.Matrix.Identity();
  5845. }
  5846. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5847. return this._worldMatrix;
  5848. };
  5849. return DirectionalLight;
  5850. })(BABYLON.Light);
  5851. BABYLON.DirectionalLight = DirectionalLight;
  5852. })(BABYLON || (BABYLON = {}));
  5853. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5854. (function (BABYLON) {
  5855. var ShadowGenerator = (function () {
  5856. function ShadowGenerator(mapSize, light) {
  5857. var _this = this;
  5858. // Members
  5859. this.filter = ShadowGenerator.FILTER_NONE;
  5860. this.blurScale = 2;
  5861. this._blurBoxOffset = 0;
  5862. this._bias = 0.00005;
  5863. this._darkness = 0;
  5864. this._transparencyShadow = false;
  5865. this._viewMatrix = BABYLON.Matrix.Zero();
  5866. this._projectionMatrix = BABYLON.Matrix.Zero();
  5867. this._transformMatrix = BABYLON.Matrix.Zero();
  5868. this._worldViewProjection = BABYLON.Matrix.Zero();
  5869. this._light = light;
  5870. this._scene = light.getScene();
  5871. this._mapSize = mapSize;
  5872. light._shadowGenerator = this;
  5873. // Render target
  5874. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5875. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5876. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5877. this._shadowMap.renderParticles = false;
  5878. this._shadowMap.onAfterUnbind = function () {
  5879. if (!_this.useBlurVarianceShadowMap) {
  5880. return;
  5881. }
  5882. if (!_this._shadowMap2) {
  5883. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5884. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5885. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5886. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5887. _this._downSamplePostprocess.onApply = function (effect) {
  5888. effect.setTexture("textureSampler", _this._shadowMap);
  5889. };
  5890. _this.blurBoxOffset = 1;
  5891. }
  5892. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5893. };
  5894. // Custom render function
  5895. var renderSubMesh = function (subMesh) {
  5896. var mesh = subMesh.getRenderingMesh();
  5897. var scene = _this._scene;
  5898. var engine = scene.getEngine();
  5899. // Culling
  5900. engine.setState(subMesh.getMaterial().backFaceCulling);
  5901. // Managing instances
  5902. var batch = mesh._getInstancesRenderList(subMesh._id);
  5903. if (batch.mustReturn) {
  5904. return;
  5905. }
  5906. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5907. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5908. engine.enableEffect(_this._effect);
  5909. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5910. var material = subMesh.getMaterial();
  5911. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5912. // Alpha test
  5913. if (material && material.needAlphaTesting()) {
  5914. var alphaTexture = material.getAlphaTestTexture();
  5915. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5916. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5917. }
  5918. // Bones
  5919. if (mesh.useBones) {
  5920. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5921. }
  5922. // Draw
  5923. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5924. }
  5925. else {
  5926. // Need to reset refresh rate of the shadowMap
  5927. _this._shadowMap.resetRefreshCounter();
  5928. }
  5929. };
  5930. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5931. var index;
  5932. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5933. renderSubMesh(opaqueSubMeshes.data[index]);
  5934. }
  5935. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5936. renderSubMesh(alphaTestSubMeshes.data[index]);
  5937. }
  5938. if (_this._transparencyShadow) {
  5939. for (index = 0; index < transparentSubMeshes.length; index++) {
  5940. renderSubMesh(transparentSubMeshes.data[index]);
  5941. }
  5942. }
  5943. };
  5944. this._shadowMap.onClear = function (engine) {
  5945. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  5946. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  5947. }
  5948. else {
  5949. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  5950. }
  5951. };
  5952. }
  5953. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5954. // Static
  5955. get: function () {
  5956. return ShadowGenerator._FILTER_NONE;
  5957. },
  5958. enumerable: true,
  5959. configurable: true
  5960. });
  5961. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5962. get: function () {
  5963. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5964. },
  5965. enumerable: true,
  5966. configurable: true
  5967. });
  5968. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5969. get: function () {
  5970. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5971. },
  5972. enumerable: true,
  5973. configurable: true
  5974. });
  5975. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  5976. get: function () {
  5977. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  5978. },
  5979. enumerable: true,
  5980. configurable: true
  5981. });
  5982. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  5983. get: function () {
  5984. return this._bias;
  5985. },
  5986. set: function (bias) {
  5987. this._bias = bias;
  5988. },
  5989. enumerable: true,
  5990. configurable: true
  5991. });
  5992. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  5993. get: function () {
  5994. return this._blurBoxOffset;
  5995. },
  5996. set: function (value) {
  5997. var _this = this;
  5998. if (this._blurBoxOffset === value) {
  5999. return;
  6000. }
  6001. this._blurBoxOffset = value;
  6002. if (this._boxBlurPostprocess) {
  6003. this._boxBlurPostprocess.dispose();
  6004. }
  6005. this._boxBlurPostprocess = new BABYLON.PostProcess("DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0 / this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define OFFSET " + value);
  6006. this._boxBlurPostprocess.onApply = function (effect) {
  6007. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6008. };
  6009. },
  6010. enumerable: true,
  6011. configurable: true
  6012. });
  6013. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6014. get: function () {
  6015. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6016. },
  6017. set: function (value) {
  6018. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6019. },
  6020. enumerable: true,
  6021. configurable: true
  6022. });
  6023. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6024. get: function () {
  6025. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6026. },
  6027. set: function (value) {
  6028. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6029. },
  6030. enumerable: true,
  6031. configurable: true
  6032. });
  6033. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6034. get: function () {
  6035. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6036. },
  6037. set: function (value) {
  6038. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6039. },
  6040. enumerable: true,
  6041. configurable: true
  6042. });
  6043. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6044. var defines = [];
  6045. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6046. defines.push("#define VSM");
  6047. }
  6048. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6049. var mesh = subMesh.getMesh();
  6050. var material = subMesh.getMaterial();
  6051. // Alpha test
  6052. if (material && material.needAlphaTesting()) {
  6053. defines.push("#define ALPHATEST");
  6054. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6055. attribs.push(BABYLON.VertexBuffer.UVKind);
  6056. defines.push("#define UV1");
  6057. }
  6058. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6059. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6060. defines.push("#define UV2");
  6061. }
  6062. }
  6063. // Bones
  6064. if (mesh.useBones) {
  6065. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6066. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6067. defines.push("#define BONES");
  6068. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6069. }
  6070. // Instances
  6071. if (useInstances) {
  6072. defines.push("#define INSTANCES");
  6073. attribs.push("world0");
  6074. attribs.push("world1");
  6075. attribs.push("world2");
  6076. attribs.push("world3");
  6077. }
  6078. // Get correct effect
  6079. var join = defines.join("\n");
  6080. if (this._cachedDefines !== join) {
  6081. this._cachedDefines = join;
  6082. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6083. }
  6084. return this._effect.isReady();
  6085. };
  6086. ShadowGenerator.prototype.getShadowMap = function () {
  6087. return this._shadowMap;
  6088. };
  6089. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6090. if (this._shadowMap2) {
  6091. return this._shadowMap2;
  6092. }
  6093. return this._shadowMap;
  6094. };
  6095. ShadowGenerator.prototype.getLight = function () {
  6096. return this._light;
  6097. };
  6098. // Methods
  6099. ShadowGenerator.prototype.getTransformMatrix = function () {
  6100. var scene = this._scene;
  6101. if (this._currentRenderID === scene.getRenderId()) {
  6102. return this._transformMatrix;
  6103. }
  6104. this._currentRenderID = scene.getRenderId();
  6105. var lightPosition = this._light.position;
  6106. var lightDirection = this._light.direction;
  6107. if (this._light.computeTransformedPosition()) {
  6108. lightPosition = this._light.transformedPosition;
  6109. }
  6110. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6111. this._cachedPosition = lightPosition.clone();
  6112. this._cachedDirection = lightDirection.clone();
  6113. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6114. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6115. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6116. }
  6117. return this._transformMatrix;
  6118. };
  6119. ShadowGenerator.prototype.getDarkness = function () {
  6120. return this._darkness;
  6121. };
  6122. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6123. if (darkness >= 1.0)
  6124. this._darkness = 1.0;
  6125. else if (darkness <= 0.0)
  6126. this._darkness = 0.0;
  6127. else
  6128. this._darkness = darkness;
  6129. };
  6130. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6131. this._transparencyShadow = hasShadow;
  6132. };
  6133. ShadowGenerator.prototype._packHalf = function (depth) {
  6134. var scale = depth * 255.0;
  6135. var fract = scale - Math.floor(scale);
  6136. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6137. };
  6138. ShadowGenerator.prototype.dispose = function () {
  6139. this._shadowMap.dispose();
  6140. if (this._shadowMap2) {
  6141. this._shadowMap2.dispose();
  6142. }
  6143. if (this._downSamplePostprocess) {
  6144. this._downSamplePostprocess.dispose();
  6145. }
  6146. if (this._boxBlurPostprocess) {
  6147. this._boxBlurPostprocess.dispose();
  6148. }
  6149. };
  6150. ShadowGenerator._FILTER_NONE = 0;
  6151. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6152. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6153. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6154. return ShadowGenerator;
  6155. })();
  6156. BABYLON.ShadowGenerator = ShadowGenerator;
  6157. })(BABYLON || (BABYLON = {}));
  6158. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6159. var BABYLON;
  6160. (function (BABYLON) {
  6161. var HemisphericLight = (function (_super) {
  6162. __extends(HemisphericLight, _super);
  6163. function HemisphericLight(name, direction, scene) {
  6164. _super.call(this, name, scene);
  6165. this.direction = direction;
  6166. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6167. }
  6168. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6169. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6170. return this.direction;
  6171. };
  6172. HemisphericLight.prototype.getShadowGenerator = function () {
  6173. return null;
  6174. };
  6175. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6176. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6177. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6178. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6179. };
  6180. HemisphericLight.prototype._getWorldMatrix = function () {
  6181. if (!this._worldMatrix) {
  6182. this._worldMatrix = BABYLON.Matrix.Identity();
  6183. }
  6184. return this._worldMatrix;
  6185. };
  6186. return HemisphericLight;
  6187. })(BABYLON.Light);
  6188. BABYLON.HemisphericLight = HemisphericLight;
  6189. })(BABYLON || (BABYLON = {}));
  6190. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6191. (function (BABYLON) {
  6192. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6193. if (boxMin.x > sphereCenter.x + sphereRadius)
  6194. return false;
  6195. if (sphereCenter.x - sphereRadius > boxMax.x)
  6196. return false;
  6197. if (boxMin.y > sphereCenter.y + sphereRadius)
  6198. return false;
  6199. if (sphereCenter.y - sphereRadius > boxMax.y)
  6200. return false;
  6201. if (boxMin.z > sphereCenter.z + sphereRadius)
  6202. return false;
  6203. if (sphereCenter.z - sphereRadius > boxMax.z)
  6204. return false;
  6205. return true;
  6206. };
  6207. var getLowestRoot = function (a, b, c, maxR) {
  6208. var determinant = b * b - 4.0 * a * c;
  6209. var result = { root: 0, found: false };
  6210. if (determinant < 0)
  6211. return result;
  6212. var sqrtD = Math.sqrt(determinant);
  6213. var r1 = (-b - sqrtD) / (2.0 * a);
  6214. var r2 = (-b + sqrtD) / (2.0 * a);
  6215. if (r1 > r2) {
  6216. var temp = r2;
  6217. r2 = r1;
  6218. r1 = temp;
  6219. }
  6220. if (r1 > 0 && r1 < maxR) {
  6221. result.root = r1;
  6222. result.found = true;
  6223. return result;
  6224. }
  6225. if (r2 > 0 && r2 < maxR) {
  6226. result.root = r2;
  6227. result.found = true;
  6228. return result;
  6229. }
  6230. return result;
  6231. };
  6232. var Collider = (function () {
  6233. function Collider() {
  6234. this.radius = new BABYLON.Vector3(1, 1, 1);
  6235. this.retry = 0;
  6236. this.basePointWorld = BABYLON.Vector3.Zero();
  6237. this.velocityWorld = BABYLON.Vector3.Zero();
  6238. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6239. this._collisionPoint = BABYLON.Vector3.Zero();
  6240. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6241. this._tempVector = BABYLON.Vector3.Zero();
  6242. this._tempVector2 = BABYLON.Vector3.Zero();
  6243. this._tempVector3 = BABYLON.Vector3.Zero();
  6244. this._tempVector4 = BABYLON.Vector3.Zero();
  6245. this._edge = BABYLON.Vector3.Zero();
  6246. this._baseToVertex = BABYLON.Vector3.Zero();
  6247. this._destinationPoint = BABYLON.Vector3.Zero();
  6248. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6249. this._displacementVector = BABYLON.Vector3.Zero();
  6250. }
  6251. // Methods
  6252. Collider.prototype._initialize = function (source, dir, e) {
  6253. this.velocity = dir;
  6254. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6255. this.basePoint = source;
  6256. source.multiplyToRef(this.radius, this.basePointWorld);
  6257. dir.multiplyToRef(this.radius, this.velocityWorld);
  6258. this.velocityWorldLength = this.velocityWorld.length();
  6259. this.epsilon = e;
  6260. this.collisionFound = false;
  6261. };
  6262. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6263. pa.subtractToRef(point, this._tempVector);
  6264. pb.subtractToRef(point, this._tempVector2);
  6265. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6266. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6267. if (d < 0)
  6268. return false;
  6269. pc.subtractToRef(point, this._tempVector3);
  6270. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6271. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6272. if (d < 0)
  6273. return false;
  6274. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6275. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6276. return d >= 0;
  6277. };
  6278. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6279. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6280. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6281. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6282. return false;
  6283. }
  6284. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6285. return false;
  6286. return true;
  6287. };
  6288. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6289. var t0;
  6290. var embeddedInPlane = false;
  6291. if (!subMesh._trianglePlanes) {
  6292. subMesh._trianglePlanes = [];
  6293. }
  6294. if (!subMesh._trianglePlanes[faceIndex]) {
  6295. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6296. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6297. }
  6298. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6299. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6300. return;
  6301. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6302. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6303. if (normalDotVelocity == 0) {
  6304. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6305. return;
  6306. embeddedInPlane = true;
  6307. t0 = 0;
  6308. }
  6309. else {
  6310. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6311. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6312. if (t0 > t1) {
  6313. var temp = t1;
  6314. t1 = t0;
  6315. t0 = temp;
  6316. }
  6317. if (t0 > 1.0 || t1 < 0.0)
  6318. return;
  6319. if (t0 < 0)
  6320. t0 = 0;
  6321. if (t0 > 1.0)
  6322. t0 = 1.0;
  6323. }
  6324. this._collisionPoint.copyFromFloats(0, 0, 0);
  6325. var found = false;
  6326. var t = 1.0;
  6327. if (!embeddedInPlane) {
  6328. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6329. this.velocity.scaleToRef(t0, this._tempVector);
  6330. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6331. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6332. found = true;
  6333. t = t0;
  6334. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6335. }
  6336. }
  6337. if (!found) {
  6338. var velocitySquaredLength = this.velocity.lengthSquared();
  6339. var a = velocitySquaredLength;
  6340. this.basePoint.subtractToRef(p1, this._tempVector);
  6341. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6342. var c = this._tempVector.lengthSquared() - 1.0;
  6343. var lowestRoot = getLowestRoot(a, b, c, t);
  6344. if (lowestRoot.found) {
  6345. t = lowestRoot.root;
  6346. found = true;
  6347. this._collisionPoint.copyFrom(p1);
  6348. }
  6349. this.basePoint.subtractToRef(p2, this._tempVector);
  6350. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6351. c = this._tempVector.lengthSquared() - 1.0;
  6352. lowestRoot = getLowestRoot(a, b, c, t);
  6353. if (lowestRoot.found) {
  6354. t = lowestRoot.root;
  6355. found = true;
  6356. this._collisionPoint.copyFrom(p2);
  6357. }
  6358. this.basePoint.subtractToRef(p3, this._tempVector);
  6359. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6360. c = this._tempVector.lengthSquared() - 1.0;
  6361. lowestRoot = getLowestRoot(a, b, c, t);
  6362. if (lowestRoot.found) {
  6363. t = lowestRoot.root;
  6364. found = true;
  6365. this._collisionPoint.copyFrom(p3);
  6366. }
  6367. p2.subtractToRef(p1, this._edge);
  6368. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6369. var edgeSquaredLength = this._edge.lengthSquared();
  6370. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6371. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6372. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6373. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6374. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6375. lowestRoot = getLowestRoot(a, b, c, t);
  6376. if (lowestRoot.found) {
  6377. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6378. if (f >= 0.0 && f <= 1.0) {
  6379. t = lowestRoot.root;
  6380. found = true;
  6381. this._edge.scaleInPlace(f);
  6382. p1.addToRef(this._edge, this._collisionPoint);
  6383. }
  6384. }
  6385. p3.subtractToRef(p2, this._edge);
  6386. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6387. edgeSquaredLength = this._edge.lengthSquared();
  6388. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6389. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6390. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6391. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6392. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6393. lowestRoot = getLowestRoot(a, b, c, t);
  6394. if (lowestRoot.found) {
  6395. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6396. if (f >= 0.0 && f <= 1.0) {
  6397. t = lowestRoot.root;
  6398. found = true;
  6399. this._edge.scaleInPlace(f);
  6400. p2.addToRef(this._edge, this._collisionPoint);
  6401. }
  6402. }
  6403. p1.subtractToRef(p3, this._edge);
  6404. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6405. edgeSquaredLength = this._edge.lengthSquared();
  6406. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6407. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6408. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6409. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6410. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6411. lowestRoot = getLowestRoot(a, b, c, t);
  6412. if (lowestRoot.found) {
  6413. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6414. if (f >= 0.0 && f <= 1.0) {
  6415. t = lowestRoot.root;
  6416. found = true;
  6417. this._edge.scaleInPlace(f);
  6418. p3.addToRef(this._edge, this._collisionPoint);
  6419. }
  6420. }
  6421. }
  6422. if (found) {
  6423. var distToCollision = t * this.velocity.length();
  6424. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6425. if (!this.intersectionPoint) {
  6426. this.intersectionPoint = this._collisionPoint.clone();
  6427. }
  6428. else {
  6429. this.intersectionPoint.copyFrom(this._collisionPoint);
  6430. }
  6431. this.nearestDistance = distToCollision;
  6432. this.collisionFound = true;
  6433. this.collidedMesh = subMesh.getMesh();
  6434. }
  6435. }
  6436. };
  6437. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6438. for (var i = indexStart; i < indexEnd; i += 3) {
  6439. var p1 = pts[indices[i] - decal];
  6440. var p2 = pts[indices[i + 1] - decal];
  6441. var p3 = pts[indices[i + 2] - decal];
  6442. this._testTriangle(i, subMesh, p3, p2, p1);
  6443. }
  6444. };
  6445. Collider.prototype._getResponse = function (pos, vel) {
  6446. pos.addToRef(vel, this._destinationPoint);
  6447. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6448. this.basePoint.addToRef(vel, pos);
  6449. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6450. this._slidePlaneNormal.normalize();
  6451. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6452. pos.addInPlace(this._displacementVector);
  6453. this.intersectionPoint.addInPlace(this._displacementVector);
  6454. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6455. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6456. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6457. };
  6458. return Collider;
  6459. })();
  6460. BABYLON.Collider = Collider;
  6461. })(BABYLON || (BABYLON = {}));
  6462. //# sourceMappingURL=babylon.collider.js.map
  6463. var BABYLON;
  6464. (function (BABYLON) {
  6465. var Camera = (function (_super) {
  6466. __extends(Camera, _super);
  6467. function Camera(name, position, scene) {
  6468. _super.call(this, name, scene);
  6469. this.position = position;
  6470. // Members
  6471. this.upVector = BABYLON.Vector3.Up();
  6472. this.orthoLeft = null;
  6473. this.orthoRight = null;
  6474. this.orthoBottom = null;
  6475. this.orthoTop = null;
  6476. this.fov = 0.8;
  6477. this.minZ = 1.0;
  6478. this.maxZ = 10000.0;
  6479. this.inertia = 0.9;
  6480. this.mode = Camera.PERSPECTIVE_CAMERA;
  6481. this.isIntermediate = false;
  6482. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6483. this.subCameras = [];
  6484. this.layerMask = 0xFFFFFFFF;
  6485. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6486. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6487. this._projectionMatrix = new BABYLON.Matrix();
  6488. this._postProcesses = new Array();
  6489. this._postProcessesTakenIndices = [];
  6490. this._activeMeshes = new BABYLON.SmartArray(256);
  6491. scene.cameras.push(this);
  6492. if (!scene.activeCamera) {
  6493. scene.activeCamera = this;
  6494. }
  6495. }
  6496. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6497. get: function () {
  6498. return Camera._PERSPECTIVE_CAMERA;
  6499. },
  6500. enumerable: true,
  6501. configurable: true
  6502. });
  6503. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6504. get: function () {
  6505. return Camera._ORTHOGRAPHIC_CAMERA;
  6506. },
  6507. enumerable: true,
  6508. configurable: true
  6509. });
  6510. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6511. get: function () {
  6512. return Camera._FOVMODE_VERTICAL_FIXED;
  6513. },
  6514. enumerable: true,
  6515. configurable: true
  6516. });
  6517. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6518. get: function () {
  6519. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6520. },
  6521. enumerable: true,
  6522. configurable: true
  6523. });
  6524. Camera.prototype.getActiveMeshes = function () {
  6525. return this._activeMeshes;
  6526. };
  6527. Camera.prototype.isActiveMesh = function (mesh) {
  6528. return (this._activeMeshes.indexOf(mesh) !== -1);
  6529. };
  6530. //Cache
  6531. Camera.prototype._initCache = function () {
  6532. _super.prototype._initCache.call(this);
  6533. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6534. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6535. this._cache.mode = undefined;
  6536. this._cache.minZ = undefined;
  6537. this._cache.maxZ = undefined;
  6538. this._cache.fov = undefined;
  6539. this._cache.aspectRatio = undefined;
  6540. this._cache.orthoLeft = undefined;
  6541. this._cache.orthoRight = undefined;
  6542. this._cache.orthoBottom = undefined;
  6543. this._cache.orthoTop = undefined;
  6544. this._cache.renderWidth = undefined;
  6545. this._cache.renderHeight = undefined;
  6546. };
  6547. Camera.prototype._updateCache = function (ignoreParentClass) {
  6548. if (!ignoreParentClass) {
  6549. _super.prototype._updateCache.call(this);
  6550. }
  6551. var engine = this.getEngine();
  6552. this._cache.position.copyFrom(this.position);
  6553. this._cache.upVector.copyFrom(this.upVector);
  6554. this._cache.mode = this.mode;
  6555. this._cache.minZ = this.minZ;
  6556. this._cache.maxZ = this.maxZ;
  6557. this._cache.fov = this.fov;
  6558. this._cache.aspectRatio = engine.getAspectRatio(this);
  6559. this._cache.orthoLeft = this.orthoLeft;
  6560. this._cache.orthoRight = this.orthoRight;
  6561. this._cache.orthoBottom = this.orthoBottom;
  6562. this._cache.orthoTop = this.orthoTop;
  6563. this._cache.renderWidth = engine.getRenderWidth();
  6564. this._cache.renderHeight = engine.getRenderHeight();
  6565. };
  6566. Camera.prototype._updateFromScene = function () {
  6567. this.updateCache();
  6568. this._update();
  6569. };
  6570. // Synchronized
  6571. Camera.prototype._isSynchronized = function () {
  6572. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6573. };
  6574. Camera.prototype._isSynchronizedViewMatrix = function () {
  6575. if (!_super.prototype._isSynchronized.call(this))
  6576. return false;
  6577. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6578. };
  6579. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6580. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6581. if (!check) {
  6582. return false;
  6583. }
  6584. var engine = this.getEngine();
  6585. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6586. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6587. }
  6588. else {
  6589. 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();
  6590. }
  6591. return check;
  6592. };
  6593. // Controls
  6594. Camera.prototype.attachControl = function (element) {
  6595. };
  6596. Camera.prototype.detachControl = function (element) {
  6597. };
  6598. Camera.prototype._update = function () {
  6599. };
  6600. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6601. if (insertAt === void 0) { insertAt = null; }
  6602. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6603. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6604. return 0;
  6605. }
  6606. if (insertAt == null || insertAt < 0) {
  6607. this._postProcesses.push(postProcess);
  6608. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6609. return this._postProcesses.length - 1;
  6610. }
  6611. var add = 0;
  6612. if (this._postProcesses[insertAt]) {
  6613. var start = this._postProcesses.length - 1;
  6614. for (var i = start; i >= insertAt + 1; --i) {
  6615. this._postProcesses[i + 1] = this._postProcesses[i];
  6616. }
  6617. add = 1;
  6618. }
  6619. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6620. if (this._postProcessesTakenIndices[i] < insertAt) {
  6621. continue;
  6622. }
  6623. start = this._postProcessesTakenIndices.length - 1;
  6624. for (var j = start; j >= i; --j) {
  6625. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6626. }
  6627. this._postProcessesTakenIndices[i] = insertAt;
  6628. break;
  6629. }
  6630. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6631. this._postProcessesTakenIndices.push(insertAt);
  6632. }
  6633. var result = insertAt + add;
  6634. this._postProcesses[result] = postProcess;
  6635. return result;
  6636. };
  6637. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6638. if (atIndices === void 0) { atIndices = null; }
  6639. var result = [];
  6640. if (!atIndices) {
  6641. var length = this._postProcesses.length;
  6642. for (var i = 0; i < length; i++) {
  6643. if (this._postProcesses[i] !== postProcess) {
  6644. continue;
  6645. }
  6646. delete this._postProcesses[i];
  6647. var index = this._postProcessesTakenIndices.indexOf(i);
  6648. this._postProcessesTakenIndices.splice(index, 1);
  6649. }
  6650. }
  6651. else {
  6652. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6653. for (i = 0; i < atIndices.length; i++) {
  6654. var foundPostProcess = this._postProcesses[atIndices[i]];
  6655. if (foundPostProcess !== postProcess) {
  6656. result.push(i);
  6657. continue;
  6658. }
  6659. delete this._postProcesses[atIndices[i]];
  6660. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6661. this._postProcessesTakenIndices.splice(index, 1);
  6662. }
  6663. }
  6664. return result;
  6665. };
  6666. Camera.prototype.getWorldMatrix = function () {
  6667. if (!this._worldMatrix) {
  6668. this._worldMatrix = BABYLON.Matrix.Identity();
  6669. }
  6670. var viewMatrix = this.getViewMatrix();
  6671. viewMatrix.invertToRef(this._worldMatrix);
  6672. return this._worldMatrix;
  6673. };
  6674. Camera.prototype._getViewMatrix = function () {
  6675. return BABYLON.Matrix.Identity();
  6676. };
  6677. Camera.prototype.getViewMatrix = function () {
  6678. this._computedViewMatrix = this._computeViewMatrix();
  6679. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6680. return this._computedViewMatrix;
  6681. }
  6682. if (!this._worldMatrix) {
  6683. this._worldMatrix = BABYLON.Matrix.Identity();
  6684. }
  6685. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6686. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6687. this._computedViewMatrix.invert();
  6688. this._currentRenderId = this.getScene().getRenderId();
  6689. return this._computedViewMatrix;
  6690. };
  6691. Camera.prototype._computeViewMatrix = function (force) {
  6692. if (!force && this._isSynchronizedViewMatrix()) {
  6693. return this._computedViewMatrix;
  6694. }
  6695. this._computedViewMatrix = this._getViewMatrix();
  6696. if (!this.parent || !this.parent.getWorldMatrix) {
  6697. this._currentRenderId = this.getScene().getRenderId();
  6698. }
  6699. return this._computedViewMatrix;
  6700. };
  6701. Camera.prototype.getProjectionMatrix = function (force) {
  6702. if (!force && this._isSynchronizedProjectionMatrix()) {
  6703. return this._projectionMatrix;
  6704. }
  6705. var engine = this.getEngine();
  6706. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6707. if (this.minZ <= 0) {
  6708. this.minZ = 0.1;
  6709. }
  6710. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6711. return this._projectionMatrix;
  6712. }
  6713. var halfWidth = engine.getRenderWidth() / 2.0;
  6714. var halfHeight = engine.getRenderHeight() / 2.0;
  6715. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6716. return this._projectionMatrix;
  6717. };
  6718. Camera.prototype.dispose = function () {
  6719. // Remove from scene
  6720. var index = this.getScene().cameras.indexOf(this);
  6721. this.getScene().cameras.splice(index, 1);
  6722. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6723. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6724. }
  6725. };
  6726. // Statics
  6727. Camera._PERSPECTIVE_CAMERA = 0;
  6728. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6729. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6730. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6731. return Camera;
  6732. })(BABYLON.Node);
  6733. BABYLON.Camera = Camera;
  6734. })(BABYLON || (BABYLON = {}));
  6735. //# sourceMappingURL=babylon.camera.js.map
  6736. var BABYLON;
  6737. (function (BABYLON) {
  6738. var TargetCamera = (function (_super) {
  6739. __extends(TargetCamera, _super);
  6740. function TargetCamera(name, position, scene) {
  6741. _super.call(this, name, position, scene);
  6742. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6743. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6744. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6745. this.speed = 2.0;
  6746. this.noRotationConstraint = false;
  6747. this.lockedTarget = null;
  6748. this._currentTarget = BABYLON.Vector3.Zero();
  6749. this._viewMatrix = BABYLON.Matrix.Zero();
  6750. this._camMatrix = BABYLON.Matrix.Zero();
  6751. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6752. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6753. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6754. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6755. this._lookAtTemp = BABYLON.Matrix.Zero();
  6756. this._tempMatrix = BABYLON.Matrix.Zero();
  6757. }
  6758. TargetCamera.prototype._getLockedTargetPosition = function () {
  6759. if (!this.lockedTarget) {
  6760. return null;
  6761. }
  6762. return this.lockedTarget.position || this.lockedTarget;
  6763. };
  6764. // Cache
  6765. TargetCamera.prototype._initCache = function () {
  6766. _super.prototype._initCache.call(this);
  6767. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6768. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6769. };
  6770. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6771. if (!ignoreParentClass) {
  6772. _super.prototype._updateCache.call(this);
  6773. }
  6774. var lockedTargetPosition = this._getLockedTargetPosition();
  6775. if (!lockedTargetPosition) {
  6776. this._cache.lockedTarget = null;
  6777. }
  6778. else {
  6779. if (!this._cache.lockedTarget) {
  6780. this._cache.lockedTarget = lockedTargetPosition.clone();
  6781. }
  6782. else {
  6783. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6784. }
  6785. }
  6786. this._cache.rotation.copyFrom(this.rotation);
  6787. };
  6788. // Synchronized
  6789. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6790. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6791. return false;
  6792. }
  6793. var lockedTargetPosition = this._getLockedTargetPosition();
  6794. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6795. };
  6796. // Methods
  6797. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6798. var engine = this.getEngine();
  6799. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6800. };
  6801. // Target
  6802. TargetCamera.prototype.setTarget = function (target) {
  6803. this.upVector.normalize();
  6804. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6805. this._camMatrix.invert();
  6806. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6807. var vDir = target.subtract(this.position);
  6808. if (vDir.x >= 0.0) {
  6809. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6810. }
  6811. else {
  6812. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6813. }
  6814. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6815. if (isNaN(this.rotation.x)) {
  6816. this.rotation.x = 0;
  6817. }
  6818. if (isNaN(this.rotation.y)) {
  6819. this.rotation.y = 0;
  6820. }
  6821. if (isNaN(this.rotation.z)) {
  6822. this.rotation.z = 0;
  6823. }
  6824. };
  6825. TargetCamera.prototype.getTarget = function () {
  6826. return this._currentTarget;
  6827. };
  6828. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6829. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6830. };
  6831. TargetCamera.prototype._updatePosition = function () {
  6832. this.position.addInPlace(this.cameraDirection);
  6833. };
  6834. TargetCamera.prototype._update = function () {
  6835. var needToMove = this._decideIfNeedsToMove();
  6836. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6837. // Move
  6838. if (needToMove) {
  6839. this._updatePosition();
  6840. }
  6841. // Rotate
  6842. if (needToRotate) {
  6843. this.rotation.x += this.cameraRotation.x;
  6844. this.rotation.y += this.cameraRotation.y;
  6845. if (!this.noRotationConstraint) {
  6846. var limit = (Math.PI / 2) * 0.95;
  6847. if (this.rotation.x > limit)
  6848. this.rotation.x = limit;
  6849. if (this.rotation.x < -limit)
  6850. this.rotation.x = -limit;
  6851. }
  6852. }
  6853. // Inertia
  6854. if (needToMove) {
  6855. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6856. this.cameraDirection.x = 0;
  6857. }
  6858. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6859. this.cameraDirection.y = 0;
  6860. }
  6861. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6862. this.cameraDirection.z = 0;
  6863. }
  6864. this.cameraDirection.scaleInPlace(this.inertia);
  6865. }
  6866. if (needToRotate) {
  6867. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6868. this.cameraRotation.x = 0;
  6869. }
  6870. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6871. this.cameraRotation.y = 0;
  6872. }
  6873. this.cameraRotation.scaleInPlace(this.inertia);
  6874. }
  6875. };
  6876. TargetCamera.prototype._getViewMatrix = function () {
  6877. if (!this.lockedTarget) {
  6878. // Compute
  6879. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6880. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6881. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6882. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6883. this._lookAtTemp.invert();
  6884. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6885. }
  6886. else {
  6887. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6888. }
  6889. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6890. // Computing target and final matrix
  6891. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6892. }
  6893. else {
  6894. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6895. }
  6896. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6897. return this._viewMatrix;
  6898. };
  6899. return TargetCamera;
  6900. })(BABYLON.Camera);
  6901. BABYLON.TargetCamera = TargetCamera;
  6902. })(BABYLON || (BABYLON = {}));
  6903. //# sourceMappingURL=babylon.targetCamera.js.map
  6904. var BABYLON;
  6905. (function (BABYLON) {
  6906. var FollowCamera = (function (_super) {
  6907. __extends(FollowCamera, _super);
  6908. function FollowCamera(name, position, scene) {
  6909. _super.call(this, name, position, scene);
  6910. this.radius = 12;
  6911. this.rotationOffset = 0;
  6912. this.heightOffset = 4;
  6913. this.cameraAcceleration = 0.05;
  6914. this.maxCameraSpeed = 20;
  6915. }
  6916. FollowCamera.prototype.getRadians = function (degrees) {
  6917. return degrees * Math.PI / 180;
  6918. };
  6919. FollowCamera.prototype.follow = function (cameraTarget) {
  6920. if (!cameraTarget)
  6921. return;
  6922. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6923. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6924. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6925. var dx = targetX - this.position.x;
  6926. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6927. var dz = (targetZ) - this.position.z;
  6928. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6929. var vy = dy * this.cameraAcceleration;
  6930. var vz = dz * this.cameraAcceleration * 2;
  6931. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6932. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6933. }
  6934. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6935. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6936. }
  6937. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6938. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6939. }
  6940. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6941. this.setTarget(cameraTarget.position);
  6942. };
  6943. FollowCamera.prototype._update = function () {
  6944. _super.prototype._update.call(this);
  6945. this.follow(this.target);
  6946. };
  6947. return FollowCamera;
  6948. })(BABYLON.TargetCamera);
  6949. BABYLON.FollowCamera = FollowCamera;
  6950. })(BABYLON || (BABYLON = {}));
  6951. //# sourceMappingURL=babylon.followCamera.js.map
  6952. var BABYLON;
  6953. (function (BABYLON) {
  6954. var FreeCamera = (function (_super) {
  6955. __extends(FreeCamera, _super);
  6956. function FreeCamera(name, position, scene) {
  6957. _super.call(this, name, position, scene);
  6958. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6959. this.keysUp = [38];
  6960. this.keysDown = [40];
  6961. this.keysLeft = [37];
  6962. this.keysRight = [39];
  6963. this.checkCollisions = false;
  6964. this.applyGravity = false;
  6965. this.angularSensibility = 2000.0;
  6966. this._keys = [];
  6967. this._collider = new BABYLON.Collider();
  6968. this._needMoveForGravity = true;
  6969. this._oldPosition = BABYLON.Vector3.Zero();
  6970. this._diffPosition = BABYLON.Vector3.Zero();
  6971. this._newPosition = BABYLON.Vector3.Zero();
  6972. }
  6973. // Controls
  6974. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6975. var _this = this;
  6976. var previousPosition;
  6977. var engine = this.getEngine();
  6978. if (this._attachedElement) {
  6979. return;
  6980. }
  6981. this._attachedElement = element;
  6982. if (this._onMouseDown === undefined) {
  6983. this._onMouseDown = function (evt) {
  6984. previousPosition = {
  6985. x: evt.clientX,
  6986. y: evt.clientY
  6987. };
  6988. if (!noPreventDefault) {
  6989. evt.preventDefault();
  6990. }
  6991. };
  6992. this._onMouseUp = function (evt) {
  6993. previousPosition = null;
  6994. if (!noPreventDefault) {
  6995. evt.preventDefault();
  6996. }
  6997. };
  6998. this._onMouseOut = function (evt) {
  6999. previousPosition = null;
  7000. _this._keys = [];
  7001. if (!noPreventDefault) {
  7002. evt.preventDefault();
  7003. }
  7004. };
  7005. this._onMouseMove = function (evt) {
  7006. if (!previousPosition && !engine.isPointerLock) {
  7007. return;
  7008. }
  7009. var offsetX;
  7010. var offsetY;
  7011. if (!engine.isPointerLock) {
  7012. offsetX = evt.clientX - previousPosition.x;
  7013. offsetY = evt.clientY - previousPosition.y;
  7014. }
  7015. else {
  7016. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7017. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7018. }
  7019. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7020. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7021. previousPosition = {
  7022. x: evt.clientX,
  7023. y: evt.clientY
  7024. };
  7025. if (!noPreventDefault) {
  7026. evt.preventDefault();
  7027. }
  7028. };
  7029. this._onKeyDown = function (evt) {
  7030. 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) {
  7031. var index = _this._keys.indexOf(evt.keyCode);
  7032. if (index === -1) {
  7033. _this._keys.push(evt.keyCode);
  7034. }
  7035. if (!noPreventDefault) {
  7036. evt.preventDefault();
  7037. }
  7038. }
  7039. };
  7040. this._onKeyUp = function (evt) {
  7041. 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) {
  7042. var index = _this._keys.indexOf(evt.keyCode);
  7043. if (index >= 0) {
  7044. _this._keys.splice(index, 1);
  7045. }
  7046. if (!noPreventDefault) {
  7047. evt.preventDefault();
  7048. }
  7049. }
  7050. };
  7051. this._onLostFocus = function () {
  7052. _this._keys = [];
  7053. };
  7054. this._reset = function () {
  7055. _this._keys = [];
  7056. previousPosition = null;
  7057. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7058. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7059. };
  7060. }
  7061. element.addEventListener("mousedown", this._onMouseDown, false);
  7062. element.addEventListener("mouseup", this._onMouseUp, false);
  7063. element.addEventListener("mouseout", this._onMouseOut, false);
  7064. element.addEventListener("mousemove", this._onMouseMove, false);
  7065. BABYLON.Tools.RegisterTopRootEvents([
  7066. { name: "keydown", handler: this._onKeyDown },
  7067. { name: "keyup", handler: this._onKeyUp },
  7068. { name: "blur", handler: this._onLostFocus }
  7069. ]);
  7070. };
  7071. FreeCamera.prototype.detachControl = function (element) {
  7072. if (this._attachedElement != element) {
  7073. return;
  7074. }
  7075. element.removeEventListener("mousedown", this._onMouseDown);
  7076. element.removeEventListener("mouseup", this._onMouseUp);
  7077. element.removeEventListener("mouseout", this._onMouseOut);
  7078. element.removeEventListener("mousemove", this._onMouseMove);
  7079. BABYLON.Tools.UnregisterTopRootEvents([
  7080. { name: "keydown", handler: this._onKeyDown },
  7081. { name: "keyup", handler: this._onKeyUp },
  7082. { name: "blur", handler: this._onLostFocus }
  7083. ]);
  7084. this._attachedElement = null;
  7085. if (this._reset) {
  7086. this._reset();
  7087. }
  7088. };
  7089. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7090. var globalPosition;
  7091. if (this.parent) {
  7092. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7093. }
  7094. else {
  7095. globalPosition = this.position;
  7096. }
  7097. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7098. this._collider.radius = this.ellipsoid;
  7099. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7100. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7101. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7102. this.position.addInPlace(this._diffPosition);
  7103. if (this.onCollide) {
  7104. this.onCollide(this._collider.collidedMesh);
  7105. }
  7106. }
  7107. };
  7108. FreeCamera.prototype._checkInputs = function () {
  7109. if (!this._localDirection) {
  7110. this._localDirection = BABYLON.Vector3.Zero();
  7111. this._transformedDirection = BABYLON.Vector3.Zero();
  7112. }
  7113. for (var index = 0; index < this._keys.length; index++) {
  7114. var keyCode = this._keys[index];
  7115. var speed = this._computeLocalCameraSpeed();
  7116. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7117. this._localDirection.copyFromFloats(-speed, 0, 0);
  7118. }
  7119. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7120. this._localDirection.copyFromFloats(0, 0, speed);
  7121. }
  7122. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7123. this._localDirection.copyFromFloats(speed, 0, 0);
  7124. }
  7125. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7126. this._localDirection.copyFromFloats(0, 0, -speed);
  7127. }
  7128. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7129. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7130. this.cameraDirection.addInPlace(this._transformedDirection);
  7131. }
  7132. };
  7133. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7134. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7135. };
  7136. FreeCamera.prototype._updatePosition = function () {
  7137. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7138. this._collideWithWorld(this.cameraDirection);
  7139. if (this.applyGravity) {
  7140. var oldPosition = this.position;
  7141. this._collideWithWorld(this.getScene().gravity);
  7142. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7143. }
  7144. }
  7145. else {
  7146. this.position.addInPlace(this.cameraDirection);
  7147. }
  7148. };
  7149. FreeCamera.prototype._update = function () {
  7150. this._checkInputs();
  7151. _super.prototype._update.call(this);
  7152. };
  7153. return FreeCamera;
  7154. })(BABYLON.TargetCamera);
  7155. BABYLON.FreeCamera = FreeCamera;
  7156. })(BABYLON || (BABYLON = {}));
  7157. //# sourceMappingURL=babylon.freeCamera.js.map
  7158. var BABYLON;
  7159. (function (BABYLON) {
  7160. // We're mainly based on the logic defined into the FreeCamera code
  7161. var TouchCamera = (function (_super) {
  7162. __extends(TouchCamera, _super);
  7163. function TouchCamera(name, position, scene) {
  7164. _super.call(this, name, position, scene);
  7165. this._offsetX = null;
  7166. this._offsetY = null;
  7167. this._pointerCount = 0;
  7168. this._pointerPressed = [];
  7169. this.angularSensibility = 200000.0;
  7170. this.moveSensibility = 500.0;
  7171. }
  7172. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7173. var _this = this;
  7174. var previousPosition;
  7175. if (this._attachedCanvas) {
  7176. return;
  7177. }
  7178. this._attachedCanvas = canvas;
  7179. if (this._onPointerDown === undefined) {
  7180. this._onPointerDown = function (evt) {
  7181. if (!noPreventDefault) {
  7182. evt.preventDefault();
  7183. }
  7184. _this._pointerPressed.push(evt.pointerId);
  7185. if (_this._pointerPressed.length !== 1) {
  7186. return;
  7187. }
  7188. previousPosition = {
  7189. x: evt.clientX,
  7190. y: evt.clientY
  7191. };
  7192. };
  7193. this._onPointerUp = function (evt) {
  7194. if (!noPreventDefault) {
  7195. evt.preventDefault();
  7196. }
  7197. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7198. if (index === -1) {
  7199. return;
  7200. }
  7201. _this._pointerPressed.splice(index, 1);
  7202. if (index != 0) {
  7203. return;
  7204. }
  7205. previousPosition = null;
  7206. _this._offsetX = null;
  7207. _this._offsetY = null;
  7208. };
  7209. this._onPointerMove = function (evt) {
  7210. if (!noPreventDefault) {
  7211. evt.preventDefault();
  7212. }
  7213. if (!previousPosition) {
  7214. return;
  7215. }
  7216. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7217. if (index != 0) {
  7218. return;
  7219. }
  7220. _this._offsetX = evt.clientX - previousPosition.x;
  7221. _this._offsetY = -(evt.clientY - previousPosition.y);
  7222. };
  7223. this._onLostFocus = function () {
  7224. _this._offsetX = null;
  7225. _this._offsetY = null;
  7226. };
  7227. }
  7228. canvas.addEventListener("pointerdown", this._onPointerDown);
  7229. canvas.addEventListener("pointerup", this._onPointerUp);
  7230. canvas.addEventListener("pointerout", this._onPointerUp);
  7231. canvas.addEventListener("pointermove", this._onPointerMove);
  7232. BABYLON.Tools.RegisterTopRootEvents([
  7233. { name: "blur", handler: this._onLostFocus }
  7234. ]);
  7235. };
  7236. TouchCamera.prototype.detachControl = function (canvas) {
  7237. if (this._attachedCanvas != canvas) {
  7238. return;
  7239. }
  7240. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7241. canvas.removeEventListener("pointerup", this._onPointerUp);
  7242. canvas.removeEventListener("pointerout", this._onPointerUp);
  7243. canvas.removeEventListener("pointermove", this._onPointerMove);
  7244. BABYLON.Tools.UnregisterTopRootEvents([
  7245. { name: "blur", handler: this._onLostFocus }
  7246. ]);
  7247. this._attachedCanvas = null;
  7248. };
  7249. TouchCamera.prototype._checkInputs = function () {
  7250. if (!this._offsetX) {
  7251. return;
  7252. }
  7253. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7254. if (this._pointerPressed.length > 1) {
  7255. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7256. }
  7257. else {
  7258. var speed = this._computeLocalCameraSpeed();
  7259. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7260. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7261. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7262. }
  7263. };
  7264. return TouchCamera;
  7265. })(BABYLON.FreeCamera);
  7266. BABYLON.TouchCamera = TouchCamera;
  7267. })(BABYLON || (BABYLON = {}));
  7268. //# sourceMappingURL=babylon.touchCamera.js.map
  7269. var BABYLON;
  7270. (function (BABYLON) {
  7271. // We're mainly based on the logic defined into the FreeCamera code
  7272. var DeviceOrientationCamera = (function (_super) {
  7273. __extends(DeviceOrientationCamera, _super);
  7274. function DeviceOrientationCamera(name, position, scene) {
  7275. var _this = this;
  7276. _super.call(this, name, position, scene);
  7277. this._offsetX = null;
  7278. this._offsetY = null;
  7279. this._orientationGamma = 0;
  7280. this._orientationBeta = 0;
  7281. this._initialOrientationGamma = 0;
  7282. this._initialOrientationBeta = 0;
  7283. this.angularSensibility = 10000.0;
  7284. this.moveSensibility = 50.0;
  7285. window.addEventListener("resize", function () {
  7286. _this._initialOrientationGamma = null;
  7287. }, false);
  7288. }
  7289. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7290. var _this = this;
  7291. if (this._attachedCanvas) {
  7292. return;
  7293. }
  7294. this._attachedCanvas = canvas;
  7295. if (!this._orientationChanged) {
  7296. this._orientationChanged = function (evt) {
  7297. if (!_this._initialOrientationGamma) {
  7298. _this._initialOrientationGamma = evt.gamma;
  7299. _this._initialOrientationBeta = evt.beta;
  7300. }
  7301. _this._orientationGamma = evt.gamma;
  7302. _this._orientationBeta = evt.beta;
  7303. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7304. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7305. };
  7306. }
  7307. window.addEventListener("deviceorientation", this._orientationChanged);
  7308. };
  7309. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7310. if (this._attachedCanvas != canvas) {
  7311. return;
  7312. }
  7313. window.removeEventListener("deviceorientation", this._orientationChanged);
  7314. this._attachedCanvas = null;
  7315. this._orientationGamma = 0;
  7316. this._orientationBeta = 0;
  7317. this._initialOrientationGamma = 0;
  7318. this._initialOrientationBeta = 0;
  7319. };
  7320. DeviceOrientationCamera.prototype._checkInputs = function () {
  7321. if (!this._offsetX) {
  7322. return;
  7323. }
  7324. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7325. var speed = this._computeLocalCameraSpeed();
  7326. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7327. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7328. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7329. };
  7330. return DeviceOrientationCamera;
  7331. })(BABYLON.FreeCamera);
  7332. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7333. })(BABYLON || (BABYLON = {}));
  7334. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7335. var BABYLON;
  7336. (function (BABYLON) {
  7337. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7338. var ArcRotateCamera = (function (_super) {
  7339. __extends(ArcRotateCamera, _super);
  7340. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7341. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7342. this.alpha = alpha;
  7343. this.beta = beta;
  7344. this.radius = radius;
  7345. this.target = target;
  7346. this.inertialAlphaOffset = 0;
  7347. this.inertialBetaOffset = 0;
  7348. this.inertialRadiusOffset = 0;
  7349. this.lowerAlphaLimit = null;
  7350. this.upperAlphaLimit = null;
  7351. this.lowerBetaLimit = 0.01;
  7352. this.upperBetaLimit = Math.PI;
  7353. this.lowerRadiusLimit = null;
  7354. this.upperRadiusLimit = null;
  7355. this.angularSensibility = 1000.0;
  7356. this.wheelPrecision = 3.0;
  7357. this.keysUp = [38];
  7358. this.keysDown = [40];
  7359. this.keysLeft = [37];
  7360. this.keysRight = [39];
  7361. this.zoomOnFactor = 1;
  7362. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7363. this._keys = [];
  7364. this._viewMatrix = new BABYLON.Matrix();
  7365. this.checkCollisions = false;
  7366. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7367. this._collider = new BABYLON.Collider();
  7368. this._previousPosition = BABYLON.Vector3.Zero();
  7369. this._collisionVelocity = BABYLON.Vector3.Zero();
  7370. this._newPosition = BABYLON.Vector3.Zero();
  7371. // Pinch
  7372. // value for pinch step scaling
  7373. // set to 20 by default
  7374. this.pinchPrecision = 20;
  7375. this.getViewMatrix();
  7376. }
  7377. ArcRotateCamera.prototype._getTargetPosition = function () {
  7378. return this.target.position || this.target;
  7379. };
  7380. // Cache
  7381. ArcRotateCamera.prototype._initCache = function () {
  7382. _super.prototype._initCache.call(this);
  7383. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7384. this._cache.alpha = undefined;
  7385. this._cache.beta = undefined;
  7386. this._cache.radius = undefined;
  7387. this._cache.targetScreenOffset = undefined;
  7388. };
  7389. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7390. if (!ignoreParentClass) {
  7391. _super.prototype._updateCache.call(this);
  7392. }
  7393. this._cache.target.copyFrom(this._getTargetPosition());
  7394. this._cache.alpha = this.alpha;
  7395. this._cache.beta = this.beta;
  7396. this._cache.radius = this.radius;
  7397. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7398. };
  7399. // Synchronized
  7400. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7401. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7402. return false;
  7403. 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);
  7404. };
  7405. // Methods
  7406. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7407. var _this = this;
  7408. var previousPosition;
  7409. var pointerId;
  7410. // to know if pinch started
  7411. var pinchStarted = false;
  7412. // two pinch point on X
  7413. // that will use for find if user action is pinch open or pinch close
  7414. var pinchPointX1, pinchPointX2;
  7415. if (this._attachedElement) {
  7416. return;
  7417. }
  7418. this._attachedElement = element;
  7419. var engine = this.getEngine();
  7420. if (this._onPointerDown === undefined) {
  7421. this._onPointerDown = function (evt) {
  7422. if (pointerId) {
  7423. return;
  7424. }
  7425. pointerId = evt.pointerId;
  7426. previousPosition = {
  7427. x: evt.clientX,
  7428. y: evt.clientY
  7429. };
  7430. if (!noPreventDefault) {
  7431. evt.preventDefault();
  7432. }
  7433. };
  7434. this._onPointerUp = function (evt) {
  7435. previousPosition = null;
  7436. pointerId = null;
  7437. if (!noPreventDefault) {
  7438. evt.preventDefault();
  7439. }
  7440. };
  7441. this._onPointerMove = function (evt) {
  7442. if (!previousPosition) {
  7443. return;
  7444. }
  7445. if (pointerId !== evt.pointerId) {
  7446. return;
  7447. }
  7448. // return pinch is started
  7449. if (pinchStarted) {
  7450. return;
  7451. }
  7452. var offsetX = evt.clientX - previousPosition.x;
  7453. var offsetY = evt.clientY - previousPosition.y;
  7454. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7455. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7456. previousPosition = {
  7457. x: evt.clientX,
  7458. y: evt.clientY
  7459. };
  7460. if (!noPreventDefault) {
  7461. evt.preventDefault();
  7462. }
  7463. };
  7464. this._onMouseMove = function (evt) {
  7465. if (!engine.isPointerLock) {
  7466. return;
  7467. }
  7468. // return pinch is started
  7469. if (pinchStarted) {
  7470. return;
  7471. }
  7472. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7473. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7474. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7475. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7476. if (!noPreventDefault) {
  7477. evt.preventDefault();
  7478. }
  7479. };
  7480. this._wheel = function (event) {
  7481. var delta = 0;
  7482. if (event.wheelDelta) {
  7483. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7484. }
  7485. else if (event.detail) {
  7486. delta = -event.detail / _this.wheelPrecision;
  7487. }
  7488. if (delta)
  7489. _this.inertialRadiusOffset += delta;
  7490. if (event.preventDefault) {
  7491. if (!noPreventDefault) {
  7492. event.preventDefault();
  7493. }
  7494. }
  7495. };
  7496. this._onKeyDown = function (evt) {
  7497. 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) {
  7498. var index = _this._keys.indexOf(evt.keyCode);
  7499. if (index === -1) {
  7500. _this._keys.push(evt.keyCode);
  7501. }
  7502. if (evt.preventDefault) {
  7503. if (!noPreventDefault) {
  7504. evt.preventDefault();
  7505. }
  7506. }
  7507. }
  7508. };
  7509. this._onKeyUp = function (evt) {
  7510. 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) {
  7511. var index = _this._keys.indexOf(evt.keyCode);
  7512. if (index >= 0) {
  7513. _this._keys.splice(index, 1);
  7514. }
  7515. if (evt.preventDefault) {
  7516. if (!noPreventDefault) {
  7517. evt.preventDefault();
  7518. }
  7519. }
  7520. }
  7521. };
  7522. this._onLostFocus = function () {
  7523. _this._keys = [];
  7524. pointerId = null;
  7525. };
  7526. this._onGestureStart = function (e) {
  7527. if (window.MSGesture === undefined) {
  7528. return;
  7529. }
  7530. if (!_this._MSGestureHandler) {
  7531. _this._MSGestureHandler = new MSGesture();
  7532. _this._MSGestureHandler.target = element;
  7533. }
  7534. _this._MSGestureHandler.addPointer(e.pointerId);
  7535. };
  7536. this._onGesture = function (e) {
  7537. _this.radius *= e.scale;
  7538. if (e.preventDefault) {
  7539. if (!noPreventDefault) {
  7540. e.stopPropagation();
  7541. e.preventDefault();
  7542. }
  7543. }
  7544. };
  7545. this._reset = function () {
  7546. _this._keys = [];
  7547. _this.inertialAlphaOffset = 0;
  7548. _this.inertialBetaOffset = 0;
  7549. _this.inertialRadiusOffset = 0;
  7550. previousPosition = null;
  7551. pointerId = null;
  7552. };
  7553. this._touchStart = function (event) {
  7554. if (event.touches.length === 2) {
  7555. //-- start pinch if two fingers on the screen
  7556. pinchStarted = true;
  7557. _this._pinchStart(event);
  7558. }
  7559. };
  7560. this._touchMove = function (event) {
  7561. if (pinchStarted) {
  7562. //-- make scaling
  7563. _this._pinchMove(event);
  7564. }
  7565. };
  7566. this._touchEnd = function (event) {
  7567. if (pinchStarted) {
  7568. //-- end of pinch
  7569. _this._pinchEnd(event);
  7570. }
  7571. };
  7572. this._pinchStart = function (event) {
  7573. // save origin touch point
  7574. pinchPointX1 = event.touches[0].clientX;
  7575. pinchPointX2 = event.touches[1].clientX;
  7576. // block the camera
  7577. // if not it rotate around target during pinch
  7578. pinchStarted = true;
  7579. };
  7580. this._pinchMove = function (event) {
  7581. // variable for new camera's radius
  7582. var delta = 0;
  7583. // variables to know if pinch open or pinch close
  7584. var direction = 1;
  7585. var distanceXOrigine, distanceXNow;
  7586. if (event.touches.length !== 2)
  7587. return;
  7588. // calculate absolute distances of the two fingers
  7589. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7590. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7591. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7592. if (distanceXNow < distanceXOrigine) {
  7593. direction = -1;
  7594. }
  7595. // calculate new radius
  7596. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7597. // set new radius
  7598. _this.inertialRadiusOffset -= delta;
  7599. // save origin touch point
  7600. pinchPointX1 = event.touches[0].clientX;
  7601. pinchPointX2 = event.touches[1].clientX;
  7602. };
  7603. this._pinchEnd = function (event) {
  7604. // cancel pinch and deblock camera rotation
  7605. pinchStarted = false;
  7606. };
  7607. }
  7608. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7609. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7610. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7611. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7612. element.addEventListener("mousemove", this._onMouseMove, false);
  7613. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7614. element.addEventListener("MSGestureChange", this._onGesture, false);
  7615. element.addEventListener('mousewheel', this._wheel, false);
  7616. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7617. // pinch
  7618. element.addEventListener('touchstart', this._touchStart, false);
  7619. element.addEventListener('touchmove', this._touchMove, false);
  7620. element.addEventListener('touchend', this._touchEnd, false);
  7621. BABYLON.Tools.RegisterTopRootEvents([
  7622. { name: "keydown", handler: this._onKeyDown },
  7623. { name: "keyup", handler: this._onKeyUp },
  7624. { name: "blur", handler: this._onLostFocus }
  7625. ]);
  7626. };
  7627. ArcRotateCamera.prototype.detachControl = function (element) {
  7628. if (this._attachedElement != element) {
  7629. return;
  7630. }
  7631. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7632. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7633. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7634. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7635. element.removeEventListener("mousemove", this._onMouseMove);
  7636. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7637. element.removeEventListener("MSGestureChange", this._onGesture);
  7638. element.removeEventListener('mousewheel', this._wheel);
  7639. element.removeEventListener('DOMMouseScroll', this._wheel);
  7640. // pinch
  7641. element.removeEventListener('touchstart', this._touchStart);
  7642. element.removeEventListener('touchmove', this._touchMove);
  7643. element.removeEventListener('touchend', this._touchEnd);
  7644. BABYLON.Tools.UnregisterTopRootEvents([
  7645. { name: "keydown", handler: this._onKeyDown },
  7646. { name: "keyup", handler: this._onKeyUp },
  7647. { name: "blur", handler: this._onLostFocus }
  7648. ]);
  7649. this._MSGestureHandler = null;
  7650. this._attachedElement = null;
  7651. if (this._reset) {
  7652. this._reset();
  7653. }
  7654. };
  7655. ArcRotateCamera.prototype._update = function () {
  7656. for (var index = 0; index < this._keys.length; index++) {
  7657. var keyCode = this._keys[index];
  7658. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7659. this.inertialAlphaOffset -= 0.01;
  7660. }
  7661. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7662. this.inertialBetaOffset -= 0.01;
  7663. }
  7664. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7665. this.inertialAlphaOffset += 0.01;
  7666. }
  7667. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7668. this.inertialBetaOffset += 0.01;
  7669. }
  7670. }
  7671. // Inertia
  7672. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7673. this.alpha += this.inertialAlphaOffset;
  7674. this.beta += this.inertialBetaOffset;
  7675. this.radius -= this.inertialRadiusOffset;
  7676. this.inertialAlphaOffset *= this.inertia;
  7677. this.inertialBetaOffset *= this.inertia;
  7678. this.inertialRadiusOffset *= this.inertia;
  7679. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7680. this.inertialAlphaOffset = 0;
  7681. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7682. this.inertialBetaOffset = 0;
  7683. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7684. this.inertialRadiusOffset = 0;
  7685. }
  7686. // Limits
  7687. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7688. this.alpha = this.lowerAlphaLimit;
  7689. }
  7690. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7691. this.alpha = this.upperAlphaLimit;
  7692. }
  7693. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7694. this.beta = this.lowerBetaLimit;
  7695. }
  7696. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7697. this.beta = this.upperBetaLimit;
  7698. }
  7699. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7700. this.radius = this.lowerRadiusLimit;
  7701. }
  7702. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7703. this.radius = this.upperRadiusLimit;
  7704. }
  7705. };
  7706. ArcRotateCamera.prototype.setPosition = function (position) {
  7707. var radiusv3 = position.subtract(this._getTargetPosition());
  7708. this.radius = radiusv3.length();
  7709. // Alpha
  7710. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7711. if (radiusv3.z < 0) {
  7712. this.alpha = 2 * Math.PI - this.alpha;
  7713. }
  7714. // Beta
  7715. this.beta = Math.acos(radiusv3.y / this.radius);
  7716. };
  7717. ArcRotateCamera.prototype._getViewMatrix = function () {
  7718. // Compute
  7719. var cosa = Math.cos(this.alpha);
  7720. var sina = Math.sin(this.alpha);
  7721. var cosb = Math.cos(this.beta);
  7722. var sinb = Math.sin(this.beta);
  7723. var target = this._getTargetPosition();
  7724. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7725. if (this.checkCollisions) {
  7726. this._collider.radius = this.collisionRadius;
  7727. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7728. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7729. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7730. this.position.copyFrom(this._previousPosition);
  7731. this.alpha = this._previousAlpha;
  7732. this.beta = this._previousBeta;
  7733. this.radius = this._previousRadius;
  7734. if (this.onCollide) {
  7735. this.onCollide(this._collider.collidedMesh);
  7736. }
  7737. }
  7738. }
  7739. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7740. this._previousAlpha = this.alpha;
  7741. this._previousBeta = this.beta;
  7742. this._previousRadius = this.radius;
  7743. this._previousPosition.copyFrom(this.position);
  7744. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7745. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7746. return this._viewMatrix;
  7747. };
  7748. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7749. meshes = meshes || this.getScene().meshes;
  7750. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7751. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7752. this.radius = distance * this.zoomOnFactor;
  7753. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7754. };
  7755. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7756. var meshesOrMinMaxVector;
  7757. var distance;
  7758. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7759. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7760. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7761. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7762. }
  7763. else {
  7764. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7765. distance = meshesOrMinMaxVectorAndDistance.distance;
  7766. }
  7767. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7768. this.maxZ = distance * 2;
  7769. };
  7770. return ArcRotateCamera;
  7771. })(BABYLON.Camera);
  7772. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7773. })(BABYLON || (BABYLON = {}));
  7774. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7775. (function (BABYLON) {
  7776. /**
  7777. * Represents a scene to be rendered by the engine.
  7778. * @see http://doc.babylonjs.com/page.php?p=21911
  7779. */
  7780. var Scene = (function () {
  7781. /**
  7782. * @constructor
  7783. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7784. */
  7785. function Scene(engine) {
  7786. // Members
  7787. this.autoClear = true;
  7788. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7789. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7790. this.forceWireframe = false;
  7791. this.forcePointsCloud = false;
  7792. this.forceShowBoundingBoxes = false;
  7793. this.animationsEnabled = true;
  7794. 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
  7795. // Fog
  7796. /**
  7797. * is fog enabled on this scene.
  7798. * @type {boolean}
  7799. */
  7800. this.fogEnabled = true;
  7801. this.fogMode = Scene.FOGMODE_NONE;
  7802. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7803. this.fogDensity = 0.1;
  7804. this.fogStart = 0;
  7805. this.fogEnd = 1000.0;
  7806. // Lights
  7807. /**
  7808. * is shadow enabled on this scene.
  7809. * @type {boolean}
  7810. */
  7811. this.shadowsEnabled = true;
  7812. /**
  7813. * is light enabled on this scene.
  7814. * @type {boolean}
  7815. */
  7816. this.lightsEnabled = true;
  7817. /**
  7818. * All of the lights added to this scene.
  7819. * @see BABYLON.Light
  7820. * @type {BABYLON.Light[]}
  7821. */
  7822. this.lights = new Array();
  7823. // Cameras
  7824. /**
  7825. * All of the cameras added to this scene.
  7826. * @see BABYLON.Camera
  7827. * @type {BABYLON.Camera[]}
  7828. */
  7829. this.cameras = new Array();
  7830. this.activeCameras = new Array();
  7831. // Meshes
  7832. /**
  7833. * All of the (abstract) meshes added to this scene.
  7834. * @see BABYLON.AbstractMesh
  7835. * @type {BABYLON.AbstractMesh[]}
  7836. */
  7837. this.meshes = new Array();
  7838. // Geometries
  7839. this._geometries = new Array();
  7840. this.materials = new Array();
  7841. this.multiMaterials = new Array();
  7842. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7843. // Textures
  7844. this.texturesEnabled = true;
  7845. this.textures = new Array();
  7846. // Particles
  7847. this.particlesEnabled = true;
  7848. this.particleSystems = new Array();
  7849. // Sprites
  7850. this.spritesEnabled = true;
  7851. this.spriteManagers = new Array();
  7852. // Layers
  7853. this.layers = new Array();
  7854. // Skeletons
  7855. this.skeletonsEnabled = true;
  7856. this.skeletons = new Array();
  7857. // Lens flares
  7858. this.lensFlaresEnabled = true;
  7859. this.lensFlareSystems = new Array();
  7860. // Collisions
  7861. this.collisionsEnabled = true;
  7862. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7863. // Postprocesses
  7864. this.postProcessesEnabled = true;
  7865. // Customs render targets
  7866. this.renderTargetsEnabled = true;
  7867. this.dumpNextRenderTargets = false;
  7868. this.customRenderTargets = new Array();
  7869. // Imported meshes
  7870. this.importedMeshesFiles = new Array();
  7871. this._actionManagers = new Array();
  7872. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7873. // Procedural textures
  7874. this.proceduralTexturesEnabled = true;
  7875. this._proceduralTextures = new Array();
  7876. this.soundTracks = new Array();
  7877. this._audioEnabled = true;
  7878. this._totalVertices = 0;
  7879. this._activeVertices = 0;
  7880. this._activeParticles = 0;
  7881. this._lastFrameDuration = 0;
  7882. this._evaluateActiveMeshesDuration = 0;
  7883. this._renderTargetsDuration = 0;
  7884. this._particlesDuration = 0;
  7885. this._renderDuration = 0;
  7886. this._spritesDuration = 0;
  7887. this._animationRatio = 0;
  7888. this._renderId = 0;
  7889. this._executeWhenReadyTimeoutId = -1;
  7890. this._toBeDisposed = new BABYLON.SmartArray(256);
  7891. this._onReadyCallbacks = new Array();
  7892. this._pendingData = []; //ANY
  7893. this._onBeforeRenderCallbacks = new Array();
  7894. this._onAfterRenderCallbacks = new Array();
  7895. this._activeMeshes = new BABYLON.SmartArray(256);
  7896. this._processedMaterials = new BABYLON.SmartArray(256);
  7897. this._renderTargets = new BABYLON.SmartArray(256);
  7898. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7899. this._activeSkeletons = new BABYLON.SmartArray(32);
  7900. this._activeBones = 0;
  7901. this._activeAnimatables = new Array();
  7902. this._transformMatrix = BABYLON.Matrix.Zero();
  7903. this._scaledPosition = BABYLON.Vector3.Zero();
  7904. this._scaledVelocity = BABYLON.Vector3.Zero();
  7905. this._engine = engine;
  7906. engine.scenes.push(this);
  7907. this._renderingManager = new BABYLON.RenderingManager(this);
  7908. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7909. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7910. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7911. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7912. this.attachControl();
  7913. this._debugLayer = new BABYLON.DebugLayer(this);
  7914. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7915. //simplification queue
  7916. this.simplificationQueue = new BABYLON.SimplificationQueue();
  7917. }
  7918. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7919. get: function () {
  7920. return Scene._FOGMODE_NONE;
  7921. },
  7922. enumerable: true,
  7923. configurable: true
  7924. });
  7925. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7926. get: function () {
  7927. return Scene._FOGMODE_EXP;
  7928. },
  7929. enumerable: true,
  7930. configurable: true
  7931. });
  7932. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7933. get: function () {
  7934. return Scene._FOGMODE_EXP2;
  7935. },
  7936. enumerable: true,
  7937. configurable: true
  7938. });
  7939. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7940. get: function () {
  7941. return Scene._FOGMODE_LINEAR;
  7942. },
  7943. enumerable: true,
  7944. configurable: true
  7945. });
  7946. Object.defineProperty(Scene.prototype, "debugLayer", {
  7947. // Properties
  7948. get: function () {
  7949. return this._debugLayer;
  7950. },
  7951. enumerable: true,
  7952. configurable: true
  7953. });
  7954. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7955. /**
  7956. * The mesh that is currently under the pointer.
  7957. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7958. */
  7959. get: function () {
  7960. return this._meshUnderPointer;
  7961. },
  7962. enumerable: true,
  7963. configurable: true
  7964. });
  7965. Object.defineProperty(Scene.prototype, "pointerX", {
  7966. /**
  7967. * Current on-screen X position of the pointer
  7968. * @return {number} X position of the pointer
  7969. */
  7970. get: function () {
  7971. return this._pointerX;
  7972. },
  7973. enumerable: true,
  7974. configurable: true
  7975. });
  7976. Object.defineProperty(Scene.prototype, "pointerY", {
  7977. /**
  7978. * Current on-screen Y position of the pointer
  7979. * @return {number} Y position of the pointer
  7980. */
  7981. get: function () {
  7982. return this._pointerY;
  7983. },
  7984. enumerable: true,
  7985. configurable: true
  7986. });
  7987. Scene.prototype.getCachedMaterial = function () {
  7988. return this._cachedMaterial;
  7989. };
  7990. Scene.prototype.getBoundingBoxRenderer = function () {
  7991. return this._boundingBoxRenderer;
  7992. };
  7993. Scene.prototype.getOutlineRenderer = function () {
  7994. return this._outlineRenderer;
  7995. };
  7996. Scene.prototype.getEngine = function () {
  7997. return this._engine;
  7998. };
  7999. Scene.prototype.getTotalVertices = function () {
  8000. return this._totalVertices;
  8001. };
  8002. Scene.prototype.getActiveVertices = function () {
  8003. return this._activeVertices;
  8004. };
  8005. Scene.prototype.getActiveParticles = function () {
  8006. return this._activeParticles;
  8007. };
  8008. Scene.prototype.getActiveBones = function () {
  8009. return this._activeBones;
  8010. };
  8011. // Stats
  8012. Scene.prototype.getLastFrameDuration = function () {
  8013. return this._lastFrameDuration;
  8014. };
  8015. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8016. return this._evaluateActiveMeshesDuration;
  8017. };
  8018. Scene.prototype.getActiveMeshes = function () {
  8019. return this._activeMeshes;
  8020. };
  8021. Scene.prototype.getRenderTargetsDuration = function () {
  8022. return this._renderTargetsDuration;
  8023. };
  8024. Scene.prototype.getRenderDuration = function () {
  8025. return this._renderDuration;
  8026. };
  8027. Scene.prototype.getParticlesDuration = function () {
  8028. return this._particlesDuration;
  8029. };
  8030. Scene.prototype.getSpritesDuration = function () {
  8031. return this._spritesDuration;
  8032. };
  8033. Scene.prototype.getAnimationRatio = function () {
  8034. return this._animationRatio;
  8035. };
  8036. Scene.prototype.getRenderId = function () {
  8037. return this._renderId;
  8038. };
  8039. Scene.prototype.incrementRenderId = function () {
  8040. this._renderId++;
  8041. };
  8042. Scene.prototype._updatePointerPosition = function (evt) {
  8043. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8044. this._pointerX = evt.clientX - canvasRect.left;
  8045. this._pointerY = evt.clientY - canvasRect.top;
  8046. if (this.cameraToUseForPointers) {
  8047. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8048. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8049. }
  8050. };
  8051. // Pointers handling
  8052. Scene.prototype.attachControl = function () {
  8053. var _this = this;
  8054. this._onPointerMove = function (evt) {
  8055. var canvas = _this._engine.getRenderingCanvas();
  8056. _this._updatePointerPosition(evt);
  8057. 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);
  8058. if (pickResult.hit) {
  8059. _this._meshUnderPointer = pickResult.pickedMesh;
  8060. _this.setPointerOverMesh(pickResult.pickedMesh);
  8061. canvas.style.cursor = "pointer";
  8062. }
  8063. else {
  8064. _this.setPointerOverMesh(null);
  8065. canvas.style.cursor = "";
  8066. _this._meshUnderPointer = null;
  8067. }
  8068. };
  8069. this._onPointerDown = function (evt) {
  8070. var predicate = null;
  8071. if (!_this.onPointerDown) {
  8072. predicate = function (mesh) {
  8073. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8074. };
  8075. }
  8076. _this._updatePointerPosition(evt);
  8077. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8078. if (pickResult.hit) {
  8079. if (pickResult.pickedMesh.actionManager) {
  8080. switch (evt.button) {
  8081. case 0:
  8082. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8083. break;
  8084. case 1:
  8085. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8086. break;
  8087. case 2:
  8088. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8089. break;
  8090. }
  8091. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8092. }
  8093. }
  8094. if (_this.onPointerDown) {
  8095. _this.onPointerDown(evt, pickResult);
  8096. }
  8097. };
  8098. this._onKeyDown = function (evt) {
  8099. if (_this.actionManager) {
  8100. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8101. }
  8102. };
  8103. this._onKeyUp = function (evt) {
  8104. if (_this.actionManager) {
  8105. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8106. }
  8107. };
  8108. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8109. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8110. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8111. BABYLON.Tools.RegisterTopRootEvents([
  8112. { name: "keydown", handler: this._onKeyDown },
  8113. { name: "keyup", handler: this._onKeyUp }
  8114. ]);
  8115. };
  8116. Scene.prototype.detachControl = function () {
  8117. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8118. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8119. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8120. BABYLON.Tools.UnregisterTopRootEvents([
  8121. { name: "keydown", handler: this._onKeyDown },
  8122. { name: "keyup", handler: this._onKeyUp }
  8123. ]);
  8124. };
  8125. // Ready
  8126. Scene.prototype.isReady = function () {
  8127. if (this._pendingData.length > 0) {
  8128. return false;
  8129. }
  8130. for (var index = 0; index < this._geometries.length; index++) {
  8131. var geometry = this._geometries[index];
  8132. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8133. return false;
  8134. }
  8135. }
  8136. for (index = 0; index < this.meshes.length; index++) {
  8137. var mesh = this.meshes[index];
  8138. if (!mesh.isReady()) {
  8139. return false;
  8140. }
  8141. var mat = mesh.material;
  8142. if (mat) {
  8143. if (!mat.isReady(mesh)) {
  8144. return false;
  8145. }
  8146. }
  8147. }
  8148. return true;
  8149. };
  8150. Scene.prototype.resetCachedMaterial = function () {
  8151. this._cachedMaterial = null;
  8152. };
  8153. Scene.prototype.registerBeforeRender = function (func) {
  8154. this._onBeforeRenderCallbacks.push(func);
  8155. };
  8156. Scene.prototype.unregisterBeforeRender = function (func) {
  8157. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8158. if (index > -1) {
  8159. this._onBeforeRenderCallbacks.splice(index, 1);
  8160. }
  8161. };
  8162. Scene.prototype.registerAfterRender = function (func) {
  8163. this._onAfterRenderCallbacks.push(func);
  8164. };
  8165. Scene.prototype.unregisterAfterRender = function (func) {
  8166. var index = this._onAfterRenderCallbacks.indexOf(func);
  8167. if (index > -1) {
  8168. this._onAfterRenderCallbacks.splice(index, 1);
  8169. }
  8170. };
  8171. Scene.prototype._addPendingData = function (data) {
  8172. this._pendingData.push(data);
  8173. };
  8174. Scene.prototype._removePendingData = function (data) {
  8175. var index = this._pendingData.indexOf(data);
  8176. if (index !== -1) {
  8177. this._pendingData.splice(index, 1);
  8178. }
  8179. };
  8180. Scene.prototype.getWaitingItemsCount = function () {
  8181. return this._pendingData.length;
  8182. };
  8183. /**
  8184. * Registers a function to be executed when the scene is ready.
  8185. * @param {Function} func - the function to be executed.
  8186. */
  8187. Scene.prototype.executeWhenReady = function (func) {
  8188. var _this = this;
  8189. this._onReadyCallbacks.push(func);
  8190. if (this._executeWhenReadyTimeoutId !== -1) {
  8191. return;
  8192. }
  8193. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8194. _this._checkIsReady();
  8195. }, 150);
  8196. };
  8197. Scene.prototype._checkIsReady = function () {
  8198. var _this = this;
  8199. if (this.isReady()) {
  8200. this._onReadyCallbacks.forEach(function (func) {
  8201. func();
  8202. });
  8203. this._onReadyCallbacks = [];
  8204. this._executeWhenReadyTimeoutId = -1;
  8205. return;
  8206. }
  8207. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8208. _this._checkIsReady();
  8209. }, 150);
  8210. };
  8211. // Animations
  8212. /**
  8213. * Will start the animation sequence of a given target
  8214. * @param target - the target
  8215. * @param {number} from - from which frame should animation start
  8216. * @param {number} to - till which frame should animation run.
  8217. * @param {boolean} [loop] - should the animation loop
  8218. * @param {number} [speedRatio] - the speed in which to run the animation
  8219. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8220. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8221. * @return {BABYLON.Animatable} the animatable object created for this animation
  8222. * @see BABYLON.Animatable
  8223. * @see http://doc.babylonjs.com/page.php?p=22081
  8224. */
  8225. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8226. if (speedRatio === undefined) {
  8227. speedRatio = 1.0;
  8228. }
  8229. this.stopAnimation(target);
  8230. if (!animatable) {
  8231. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8232. }
  8233. // Local animations
  8234. if (target.animations) {
  8235. animatable.appendAnimations(target, target.animations);
  8236. }
  8237. // Children animations
  8238. if (target.getAnimatables) {
  8239. var animatables = target.getAnimatables();
  8240. for (var index = 0; index < animatables.length; index++) {
  8241. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8242. }
  8243. }
  8244. return animatable;
  8245. };
  8246. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8247. if (speedRatio === undefined) {
  8248. speedRatio = 1.0;
  8249. }
  8250. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8251. return animatable;
  8252. };
  8253. Scene.prototype.getAnimatableByTarget = function (target) {
  8254. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8255. if (this._activeAnimatables[index].target === target) {
  8256. return this._activeAnimatables[index];
  8257. }
  8258. }
  8259. return null;
  8260. };
  8261. /**
  8262. * Will stop the animation of the given target
  8263. * @param target - the target
  8264. * @see beginAnimation
  8265. */
  8266. Scene.prototype.stopAnimation = function (target) {
  8267. var animatable = this.getAnimatableByTarget(target);
  8268. if (animatable) {
  8269. animatable.stop();
  8270. }
  8271. };
  8272. Scene.prototype._animate = function () {
  8273. if (!this.animationsEnabled) {
  8274. return;
  8275. }
  8276. if (!this._animationStartDate) {
  8277. this._animationStartDate = BABYLON.Tools.Now;
  8278. }
  8279. // Getting time
  8280. var now = BABYLON.Tools.Now;
  8281. var delay = now - this._animationStartDate;
  8282. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8283. if (!this._activeAnimatables[index]._animate(delay)) {
  8284. this._activeAnimatables.splice(index, 1);
  8285. index--;
  8286. }
  8287. }
  8288. };
  8289. // Matrix
  8290. Scene.prototype.getViewMatrix = function () {
  8291. return this._viewMatrix;
  8292. };
  8293. Scene.prototype.getProjectionMatrix = function () {
  8294. return this._projectionMatrix;
  8295. };
  8296. Scene.prototype.getTransformMatrix = function () {
  8297. return this._transformMatrix;
  8298. };
  8299. Scene.prototype.setTransformMatrix = function (view, projection) {
  8300. this._viewMatrix = view;
  8301. this._projectionMatrix = projection;
  8302. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8303. };
  8304. // Methods
  8305. /**
  8306. * sets the active camera of the scene using its ID
  8307. * @param {string} id - the camera's ID
  8308. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8309. * @see activeCamera
  8310. */
  8311. Scene.prototype.setActiveCameraByID = function (id) {
  8312. var camera = this.getCameraByID(id);
  8313. if (camera) {
  8314. this.activeCamera = camera;
  8315. return camera;
  8316. }
  8317. return null;
  8318. };
  8319. /**
  8320. * sets the active camera of the scene using its name
  8321. * @param {string} name - the camera's name
  8322. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8323. * @see activeCamera
  8324. */
  8325. Scene.prototype.setActiveCameraByName = function (name) {
  8326. var camera = this.getCameraByName(name);
  8327. if (camera) {
  8328. this.activeCamera = camera;
  8329. return camera;
  8330. }
  8331. return null;
  8332. };
  8333. /**
  8334. * get a material using its id
  8335. * @param {string} the material's ID
  8336. * @return {BABYLON.Material|null} the material or null if none found.
  8337. */
  8338. Scene.prototype.getMaterialByID = function (id) {
  8339. for (var index = 0; index < this.materials.length; index++) {
  8340. if (this.materials[index].id === id) {
  8341. return this.materials[index];
  8342. }
  8343. }
  8344. return null;
  8345. };
  8346. /**
  8347. * get a material using its name
  8348. * @param {string} the material's name
  8349. * @return {BABYLON.Material|null} the material or null if none found.
  8350. */
  8351. Scene.prototype.getMaterialByName = function (name) {
  8352. for (var index = 0; index < this.materials.length; index++) {
  8353. if (this.materials[index].name === name) {
  8354. return this.materials[index];
  8355. }
  8356. }
  8357. return null;
  8358. };
  8359. Scene.prototype.getCameraByID = function (id) {
  8360. for (var index = 0; index < this.cameras.length; index++) {
  8361. if (this.cameras[index].id === id) {
  8362. return this.cameras[index];
  8363. }
  8364. }
  8365. return null;
  8366. };
  8367. /**
  8368. * get a camera using its name
  8369. * @param {string} the camera's name
  8370. * @return {BABYLON.Camera|null} the camera or null if none found.
  8371. */
  8372. Scene.prototype.getCameraByName = function (name) {
  8373. for (var index = 0; index < this.cameras.length; index++) {
  8374. if (this.cameras[index].name === name) {
  8375. return this.cameras[index];
  8376. }
  8377. }
  8378. return null;
  8379. };
  8380. /**
  8381. * get a light node using its name
  8382. * @param {string} the light's name
  8383. * @return {BABYLON.Light|null} the light or null if none found.
  8384. */
  8385. Scene.prototype.getLightByName = function (name) {
  8386. for (var index = 0; index < this.lights.length; index++) {
  8387. if (this.lights[index].name === name) {
  8388. return this.lights[index];
  8389. }
  8390. }
  8391. return null;
  8392. };
  8393. /**
  8394. * get a light node using its ID
  8395. * @param {string} the light's id
  8396. * @return {BABYLON.Light|null} the light or null if none found.
  8397. */
  8398. Scene.prototype.getLightByID = function (id) {
  8399. for (var index = 0; index < this.lights.length; index++) {
  8400. if (this.lights[index].id === id) {
  8401. return this.lights[index];
  8402. }
  8403. }
  8404. return null;
  8405. };
  8406. /**
  8407. * get a geometry using its ID
  8408. * @param {string} the geometry's id
  8409. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8410. */
  8411. Scene.prototype.getGeometryByID = function (id) {
  8412. for (var index = 0; index < this._geometries.length; index++) {
  8413. if (this._geometries[index].id === id) {
  8414. return this._geometries[index];
  8415. }
  8416. }
  8417. return null;
  8418. };
  8419. /**
  8420. * add a new geometry to this scene.
  8421. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8422. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8423. * @return {boolean} was the geometry added or not
  8424. */
  8425. Scene.prototype.pushGeometry = function (geometry, force) {
  8426. if (!force && this.getGeometryByID(geometry.id)) {
  8427. return false;
  8428. }
  8429. this._geometries.push(geometry);
  8430. return true;
  8431. };
  8432. Scene.prototype.getGeometries = function () {
  8433. return this._geometries;
  8434. };
  8435. /**
  8436. * Get a the first added mesh found of a given ID
  8437. * @param {string} id - the id to search for
  8438. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8439. */
  8440. Scene.prototype.getMeshByID = function (id) {
  8441. for (var index = 0; index < this.meshes.length; index++) {
  8442. if (this.meshes[index].id === id) {
  8443. return this.meshes[index];
  8444. }
  8445. }
  8446. return null;
  8447. };
  8448. /**
  8449. * Get a the last added mesh found of a given ID
  8450. * @param {string} id - the id to search for
  8451. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8452. */
  8453. Scene.prototype.getLastMeshByID = function (id) {
  8454. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8455. if (this.meshes[index].id === id) {
  8456. return this.meshes[index];
  8457. }
  8458. }
  8459. return null;
  8460. };
  8461. /**
  8462. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8463. * @param {string} id - the id to search for
  8464. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8465. */
  8466. Scene.prototype.getLastEntryByID = function (id) {
  8467. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8468. if (this.meshes[index].id === id) {
  8469. return this.meshes[index];
  8470. }
  8471. }
  8472. for (index = this.cameras.length - 1; index >= 0; index--) {
  8473. if (this.cameras[index].id === id) {
  8474. return this.cameras[index];
  8475. }
  8476. }
  8477. for (index = this.lights.length - 1; index >= 0; index--) {
  8478. if (this.lights[index].id === id) {
  8479. return this.lights[index];
  8480. }
  8481. }
  8482. return null;
  8483. };
  8484. Scene.prototype.getNodeByName = function (name) {
  8485. var mesh = this.getMeshByName(name);
  8486. if (mesh) {
  8487. return mesh;
  8488. }
  8489. var light = this.getLightByName(name);
  8490. if (light) {
  8491. return light;
  8492. }
  8493. return this.getCameraByName(name);
  8494. };
  8495. Scene.prototype.getMeshByName = function (name) {
  8496. for (var index = 0; index < this.meshes.length; index++) {
  8497. if (this.meshes[index].name === name) {
  8498. return this.meshes[index];
  8499. }
  8500. }
  8501. return null;
  8502. };
  8503. Scene.prototype.getSoundByName = function (name) {
  8504. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8505. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8506. return this.mainSoundTrack.soundCollection[index];
  8507. }
  8508. }
  8509. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8510. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8511. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8512. return this.soundTracks[sdIndex].soundCollection[index];
  8513. }
  8514. }
  8515. }
  8516. return null;
  8517. };
  8518. Scene.prototype.getLastSkeletonByID = function (id) {
  8519. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8520. if (this.skeletons[index].id === id) {
  8521. return this.skeletons[index];
  8522. }
  8523. }
  8524. return null;
  8525. };
  8526. Scene.prototype.getSkeletonById = function (id) {
  8527. for (var index = 0; index < this.skeletons.length; index++) {
  8528. if (this.skeletons[index].id === id) {
  8529. return this.skeletons[index];
  8530. }
  8531. }
  8532. return null;
  8533. };
  8534. Scene.prototype.getSkeletonByName = function (name) {
  8535. for (var index = 0; index < this.skeletons.length; index++) {
  8536. if (this.skeletons[index].name === name) {
  8537. return this.skeletons[index];
  8538. }
  8539. }
  8540. return null;
  8541. };
  8542. Scene.prototype.isActiveMesh = function (mesh) {
  8543. return (this._activeMeshes.indexOf(mesh) !== -1);
  8544. };
  8545. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8546. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8547. var material = subMesh.getMaterial();
  8548. if (mesh.showSubMeshesBoundingBox) {
  8549. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8550. }
  8551. if (material) {
  8552. // Render targets
  8553. if (material.getRenderTargetTextures) {
  8554. if (this._processedMaterials.indexOf(material) === -1) {
  8555. this._processedMaterials.push(material);
  8556. this._renderTargets.concat(material.getRenderTargetTextures());
  8557. }
  8558. }
  8559. // Dispatch
  8560. this._activeVertices += subMesh.indexCount;
  8561. this._renderingManager.dispatch(subMesh);
  8562. }
  8563. }
  8564. };
  8565. Scene.prototype._evaluateActiveMeshes = function () {
  8566. this.activeCamera._activeMeshes.reset();
  8567. this._activeMeshes.reset();
  8568. this._renderingManager.reset();
  8569. this._processedMaterials.reset();
  8570. this._activeParticleSystems.reset();
  8571. this._activeSkeletons.reset();
  8572. this._boundingBoxRenderer.reset();
  8573. if (!this._frustumPlanes) {
  8574. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8575. }
  8576. else {
  8577. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8578. }
  8579. // Meshes
  8580. var meshes;
  8581. var len;
  8582. if (this._selectionOctree) {
  8583. var selection = this._selectionOctree.select(this._frustumPlanes);
  8584. meshes = selection.data;
  8585. len = selection.length;
  8586. }
  8587. else {
  8588. len = this.meshes.length;
  8589. meshes = this.meshes;
  8590. }
  8591. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8592. var mesh = meshes[meshIndex];
  8593. if (mesh.isBlocked) {
  8594. continue;
  8595. }
  8596. this._totalVertices += mesh.getTotalVertices();
  8597. if (!mesh.isReady()) {
  8598. continue;
  8599. }
  8600. mesh.computeWorldMatrix();
  8601. // Intersections
  8602. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8603. this._meshesForIntersections.pushNoDuplicate(mesh);
  8604. }
  8605. // Switch to current LOD
  8606. var meshLOD = mesh.getLOD(this.activeCamera);
  8607. if (!meshLOD) {
  8608. continue;
  8609. }
  8610. mesh._preActivate();
  8611. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8612. this._activeMeshes.push(mesh);
  8613. this.activeCamera._activeMeshes.push(mesh);
  8614. mesh._activate(this._renderId);
  8615. this._activeMesh(meshLOD);
  8616. }
  8617. }
  8618. // Particle systems
  8619. var beforeParticlesDate = BABYLON.Tools.Now;
  8620. if (this.particlesEnabled) {
  8621. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8622. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8623. var particleSystem = this.particleSystems[particleIndex];
  8624. if (!particleSystem.isStarted()) {
  8625. continue;
  8626. }
  8627. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8628. this._activeParticleSystems.push(particleSystem);
  8629. particleSystem.animate();
  8630. }
  8631. }
  8632. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8633. }
  8634. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8635. };
  8636. Scene.prototype._activeMesh = function (mesh) {
  8637. if (mesh.skeleton && this.skeletonsEnabled) {
  8638. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8639. }
  8640. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8641. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8642. }
  8643. if (mesh && mesh.subMeshes) {
  8644. // Submeshes Octrees
  8645. var len;
  8646. var subMeshes;
  8647. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8648. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8649. len = intersections.length;
  8650. subMeshes = intersections.data;
  8651. }
  8652. else {
  8653. subMeshes = mesh.subMeshes;
  8654. len = subMeshes.length;
  8655. }
  8656. for (var subIndex = 0; subIndex < len; subIndex++) {
  8657. var subMesh = subMeshes[subIndex];
  8658. this._evaluateSubMesh(subMesh, mesh);
  8659. }
  8660. }
  8661. };
  8662. Scene.prototype.updateTransformMatrix = function (force) {
  8663. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8664. };
  8665. Scene.prototype._renderForCamera = function (camera) {
  8666. var engine = this._engine;
  8667. this.activeCamera = camera;
  8668. if (!this.activeCamera)
  8669. throw new Error("Active camera not set");
  8670. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8671. // Viewport
  8672. engine.setViewport(this.activeCamera.viewport);
  8673. // Camera
  8674. this._renderId++;
  8675. this.updateTransformMatrix();
  8676. if (this.beforeCameraRender) {
  8677. this.beforeCameraRender(this.activeCamera);
  8678. }
  8679. // Meshes
  8680. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8681. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8682. this._evaluateActiveMeshes();
  8683. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8684. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8685. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8686. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8687. skeleton.prepare();
  8688. }
  8689. // Render targets
  8690. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8691. if (this.renderTargetsEnabled) {
  8692. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8693. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8694. var renderTarget = this._renderTargets.data[renderIndex];
  8695. if (renderTarget._shouldRender()) {
  8696. this._renderId++;
  8697. renderTarget.render(false, this.dumpNextRenderTargets);
  8698. }
  8699. }
  8700. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8701. this._renderId++;
  8702. }
  8703. if (this._renderTargets.length > 0) {
  8704. engine.restoreDefaultFramebuffer();
  8705. }
  8706. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8707. // Prepare Frame
  8708. this.postProcessManager._prepareFrame();
  8709. var beforeRenderDate = BABYLON.Tools.Now;
  8710. // Backgrounds
  8711. if (this.layers.length) {
  8712. engine.setDepthBuffer(false);
  8713. var layerIndex;
  8714. var layer;
  8715. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8716. layer = this.layers[layerIndex];
  8717. if (layer.isBackground) {
  8718. layer.render();
  8719. }
  8720. }
  8721. engine.setDepthBuffer(true);
  8722. }
  8723. // Render
  8724. BABYLON.Tools.StartPerformanceCounter("Main render");
  8725. this._renderingManager.render(null, null, true, true);
  8726. BABYLON.Tools.EndPerformanceCounter("Main render");
  8727. // Bounding boxes
  8728. this._boundingBoxRenderer.render();
  8729. // Lens flares
  8730. if (this.lensFlaresEnabled) {
  8731. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8732. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8733. this.lensFlareSystems[lensFlareSystemIndex].render();
  8734. }
  8735. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8736. }
  8737. // Foregrounds
  8738. if (this.layers.length) {
  8739. engine.setDepthBuffer(false);
  8740. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8741. layer = this.layers[layerIndex];
  8742. if (!layer.isBackground) {
  8743. layer.render();
  8744. }
  8745. }
  8746. engine.setDepthBuffer(true);
  8747. }
  8748. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8749. // Finalize frame
  8750. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8751. // Update camera
  8752. this.activeCamera._updateFromScene();
  8753. // Reset some special arrays
  8754. this._renderTargets.reset();
  8755. if (this.afterCameraRender) {
  8756. this.afterCameraRender(this.activeCamera);
  8757. }
  8758. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8759. };
  8760. Scene.prototype._processSubCameras = function (camera) {
  8761. if (camera.subCameras.length === 0) {
  8762. this._renderForCamera(camera);
  8763. return;
  8764. }
  8765. for (var index = 0; index < camera.subCameras.length; index++) {
  8766. this._renderForCamera(camera.subCameras[index]);
  8767. }
  8768. this.activeCamera = camera;
  8769. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8770. // Update camera
  8771. this.activeCamera._updateFromScene();
  8772. };
  8773. Scene.prototype._checkIntersections = function () {
  8774. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8775. var sourceMesh = this._meshesForIntersections.data[index];
  8776. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8777. var action = sourceMesh.actionManager.actions[actionIndex];
  8778. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8779. var parameters = action.getTriggerParameter();
  8780. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8781. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8782. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8783. if (areIntersecting && currentIntersectionInProgress === -1) {
  8784. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8785. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8786. sourceMesh._intersectionsInProgress.push(otherMesh);
  8787. }
  8788. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8789. sourceMesh._intersectionsInProgress.push(otherMesh);
  8790. }
  8791. }
  8792. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8793. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8794. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8795. if (indexOfOther > -1) {
  8796. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8797. }
  8798. }
  8799. }
  8800. }
  8801. }
  8802. };
  8803. Scene.prototype.render = function () {
  8804. var startDate = BABYLON.Tools.Now;
  8805. this._particlesDuration = 0;
  8806. this._spritesDuration = 0;
  8807. this._activeParticles = 0;
  8808. this._renderDuration = 0;
  8809. this._renderTargetsDuration = 0;
  8810. this._evaluateActiveMeshesDuration = 0;
  8811. this._totalVertices = 0;
  8812. this._activeVertices = 0;
  8813. this._activeBones = 0;
  8814. this.getEngine().resetDrawCalls();
  8815. this._meshesForIntersections.reset();
  8816. this.resetCachedMaterial();
  8817. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8818. // Actions
  8819. if (this.actionManager) {
  8820. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8821. }
  8822. //Simplification Queue
  8823. if (!this.simplificationQueue.running) {
  8824. this.simplificationQueue.executeNext();
  8825. }
  8826. // Before render
  8827. if (this.beforeRender) {
  8828. this.beforeRender();
  8829. }
  8830. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8831. this._onBeforeRenderCallbacks[callbackIndex]();
  8832. }
  8833. // Animations
  8834. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8835. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8836. this._animate();
  8837. // Physics
  8838. if (this._physicsEngine) {
  8839. BABYLON.Tools.StartPerformanceCounter("Physics");
  8840. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8841. BABYLON.Tools.EndPerformanceCounter("Physics");
  8842. }
  8843. // Customs render targets
  8844. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8845. var engine = this.getEngine();
  8846. var currentActiveCamera = this.activeCamera;
  8847. if (this.renderTargetsEnabled) {
  8848. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8849. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8850. var renderTarget = this.customRenderTargets[customIndex];
  8851. if (renderTarget._shouldRender()) {
  8852. this._renderId++;
  8853. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8854. if (!this.activeCamera)
  8855. throw new Error("Active camera not set");
  8856. // Viewport
  8857. engine.setViewport(this.activeCamera.viewport);
  8858. // Camera
  8859. this.updateTransformMatrix();
  8860. renderTarget.render(false, this.dumpNextRenderTargets);
  8861. }
  8862. }
  8863. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8864. this._renderId++;
  8865. }
  8866. if (this.customRenderTargets.length > 0) {
  8867. engine.restoreDefaultFramebuffer();
  8868. }
  8869. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8870. this.activeCamera = currentActiveCamera;
  8871. // Procedural textures
  8872. if (this.proceduralTexturesEnabled) {
  8873. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8874. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8875. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8876. if (proceduralTexture._shouldRender()) {
  8877. proceduralTexture.render();
  8878. }
  8879. }
  8880. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8881. }
  8882. // Clear
  8883. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8884. // Shadows
  8885. if (this.shadowsEnabled) {
  8886. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8887. var light = this.lights[lightIndex];
  8888. var shadowGenerator = light.getShadowGenerator();
  8889. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8890. this._renderTargets.push(shadowGenerator.getShadowMap());
  8891. }
  8892. }
  8893. }
  8894. // Depth renderer
  8895. if (this._depthRenderer) {
  8896. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8897. }
  8898. // RenderPipeline
  8899. this.postProcessRenderPipelineManager.update();
  8900. // Multi-cameras?
  8901. if (this.activeCameras.length > 0) {
  8902. var currentRenderId = this._renderId;
  8903. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8904. this._renderId = currentRenderId;
  8905. this._processSubCameras(this.activeCameras[cameraIndex]);
  8906. }
  8907. }
  8908. else {
  8909. if (!this.activeCamera) {
  8910. throw new Error("No camera defined");
  8911. }
  8912. this._processSubCameras(this.activeCamera);
  8913. }
  8914. // Intersection checks
  8915. this._checkIntersections();
  8916. // Update the audio listener attached to the camera
  8917. this._updateAudioParameters();
  8918. // After render
  8919. if (this.afterRender) {
  8920. this.afterRender();
  8921. }
  8922. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8923. this._onAfterRenderCallbacks[callbackIndex]();
  8924. }
  8925. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8926. this._toBeDisposed.data[index].dispose();
  8927. this._toBeDisposed[index] = null;
  8928. }
  8929. this._toBeDisposed.reset();
  8930. if (this.dumpNextRenderTargets) {
  8931. this.dumpNextRenderTargets = false;
  8932. }
  8933. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8934. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8935. };
  8936. Scene.prototype._updateAudioParameters = function () {
  8937. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8938. return;
  8939. }
  8940. var listeningCamera;
  8941. var audioEngine = BABYLON.Engine.audioEngine;
  8942. if (this.activeCameras.length > 0) {
  8943. listeningCamera = this.activeCameras[0];
  8944. }
  8945. else {
  8946. listeningCamera = this.activeCamera;
  8947. }
  8948. if (listeningCamera && audioEngine.canUseWebAudio) {
  8949. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8950. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8951. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8952. cameraDirection.normalize();
  8953. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8954. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8955. var sound = this.mainSoundTrack.soundCollection[i];
  8956. if (sound.useCustomAttenuation) {
  8957. sound.updateDistanceFromListener();
  8958. }
  8959. }
  8960. for (i = 0; i < this.soundTracks.length; i++) {
  8961. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8962. sound = this.soundTracks[i].soundCollection[j];
  8963. if (sound.useCustomAttenuation) {
  8964. sound.updateDistanceFromListener();
  8965. }
  8966. }
  8967. }
  8968. }
  8969. };
  8970. Object.defineProperty(Scene.prototype, "audioEnabled", {
  8971. get: function () {
  8972. return this._audioEnabled;
  8973. },
  8974. set: function (value) {
  8975. this._audioEnabled = value;
  8976. if (this._audioEnabled) {
  8977. this._enableAudio();
  8978. }
  8979. else {
  8980. this._disableAudio();
  8981. }
  8982. },
  8983. enumerable: true,
  8984. configurable: true
  8985. });
  8986. Scene.prototype._disableAudio = function () {
  8987. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8988. this.mainSoundTrack.soundCollection[i].pause();
  8989. }
  8990. for (i = 0; i < this.soundTracks.length; i++) {
  8991. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8992. this.soundTracks[i].soundCollection[j].pause();
  8993. }
  8994. }
  8995. };
  8996. Scene.prototype._enableAudio = function () {
  8997. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8998. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  8999. this.mainSoundTrack.soundCollection[i].play();
  9000. }
  9001. }
  9002. for (i = 0; i < this.soundTracks.length; i++) {
  9003. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9004. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9005. this.soundTracks[i].soundCollection[j].play();
  9006. }
  9007. }
  9008. }
  9009. };
  9010. Scene.prototype.enableDepthRenderer = function () {
  9011. if (this._depthRenderer) {
  9012. return this._depthRenderer;
  9013. }
  9014. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9015. return this._depthRenderer;
  9016. };
  9017. Scene.prototype.disableDepthRenderer = function () {
  9018. if (!this._depthRenderer) {
  9019. return;
  9020. }
  9021. this._depthRenderer.dispose();
  9022. this._depthRenderer = null;
  9023. };
  9024. Scene.prototype.dispose = function () {
  9025. this.beforeRender = null;
  9026. this.afterRender = null;
  9027. this.skeletons = [];
  9028. this._boundingBoxRenderer.dispose();
  9029. if (this._depthRenderer) {
  9030. this._depthRenderer.dispose();
  9031. }
  9032. // Debug layer
  9033. this.debugLayer.hide();
  9034. // Events
  9035. if (this.onDispose) {
  9036. this.onDispose();
  9037. }
  9038. this._onBeforeRenderCallbacks = [];
  9039. this._onAfterRenderCallbacks = [];
  9040. this.detachControl();
  9041. // Release sounds & sounds tracks
  9042. this.disposeSounds();
  9043. // Detach cameras
  9044. var canvas = this._engine.getRenderingCanvas();
  9045. var index;
  9046. for (index = 0; index < this.cameras.length; index++) {
  9047. this.cameras[index].detachControl(canvas);
  9048. }
  9049. while (this.lights.length) {
  9050. this.lights[0].dispose();
  9051. }
  9052. while (this.meshes.length) {
  9053. this.meshes[0].dispose(true);
  9054. }
  9055. while (this.cameras.length) {
  9056. this.cameras[0].dispose();
  9057. }
  9058. while (this.materials.length) {
  9059. this.materials[0].dispose();
  9060. }
  9061. while (this.particleSystems.length) {
  9062. this.particleSystems[0].dispose();
  9063. }
  9064. while (this.spriteManagers.length) {
  9065. this.spriteManagers[0].dispose();
  9066. }
  9067. while (this.layers.length) {
  9068. this.layers[0].dispose();
  9069. }
  9070. while (this.textures.length) {
  9071. this.textures[0].dispose();
  9072. }
  9073. // Post-processes
  9074. this.postProcessManager.dispose();
  9075. // Physics
  9076. if (this._physicsEngine) {
  9077. this.disablePhysicsEngine();
  9078. }
  9079. // Remove from engine
  9080. index = this._engine.scenes.indexOf(this);
  9081. if (index > -1) {
  9082. this._engine.scenes.splice(index, 1);
  9083. }
  9084. this._engine.wipeCaches();
  9085. };
  9086. // Release sounds & sounds tracks
  9087. Scene.prototype.disposeSounds = function () {
  9088. this.mainSoundTrack.dispose();
  9089. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9090. this.soundTracks[scIndex].dispose();
  9091. }
  9092. };
  9093. // Collisions
  9094. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9095. if (excludedMesh === void 0) { excludedMesh = null; }
  9096. position.divideToRef(collider.radius, this._scaledPosition);
  9097. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9098. collider.retry = 0;
  9099. collider.initialVelocity = this._scaledVelocity;
  9100. collider.initialPosition = this._scaledPosition;
  9101. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9102. finalPosition.multiplyInPlace(collider.radius);
  9103. };
  9104. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9105. if (excludedMesh === void 0) { excludedMesh = null; }
  9106. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9107. if (collider.retry >= maximumRetry) {
  9108. finalPosition.copyFrom(position);
  9109. return;
  9110. }
  9111. collider._initialize(position, velocity, closeDistance);
  9112. for (var index = 0; index < this.meshes.length; index++) {
  9113. var mesh = this.meshes[index];
  9114. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9115. mesh._checkCollision(collider);
  9116. }
  9117. }
  9118. if (!collider.collisionFound) {
  9119. position.addToRef(velocity, finalPosition);
  9120. return;
  9121. }
  9122. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9123. collider._getResponse(position, velocity);
  9124. }
  9125. if (velocity.length() <= closeDistance) {
  9126. finalPosition.copyFrom(position);
  9127. return;
  9128. }
  9129. collider.retry++;
  9130. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9131. };
  9132. // Octrees
  9133. Scene.prototype.getWorldExtends = function () {
  9134. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9135. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9136. for (var index = 0; index < this.meshes.length; index++) {
  9137. var mesh = this.meshes[index];
  9138. mesh.computeWorldMatrix(true);
  9139. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9140. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9141. BABYLON.Tools.CheckExtends(minBox, min, max);
  9142. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9143. }
  9144. return {
  9145. min: min,
  9146. max: max
  9147. };
  9148. };
  9149. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9150. if (maxCapacity === void 0) { maxCapacity = 64; }
  9151. if (maxDepth === void 0) { maxDepth = 2; }
  9152. if (!this._selectionOctree) {
  9153. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9154. }
  9155. var worldExtends = this.getWorldExtends();
  9156. // Update octree
  9157. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9158. return this._selectionOctree;
  9159. };
  9160. // Picking
  9161. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9162. var engine = this._engine;
  9163. if (!camera) {
  9164. if (!this.activeCamera)
  9165. throw new Error("Active camera not set");
  9166. camera = this.activeCamera;
  9167. }
  9168. var cameraViewport = camera.viewport;
  9169. var viewport = cameraViewport.toGlobal(engine);
  9170. // Moving coordinates to local viewport world
  9171. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9172. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9173. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9174. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9175. };
  9176. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9177. var pickingInfo = null;
  9178. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9179. var mesh = this.meshes[meshIndex];
  9180. if (predicate) {
  9181. if (!predicate(mesh)) {
  9182. continue;
  9183. }
  9184. }
  9185. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9186. continue;
  9187. }
  9188. var world = mesh.getWorldMatrix();
  9189. var ray = rayFunction(world);
  9190. var result = mesh.intersects(ray, fastCheck);
  9191. if (!result || !result.hit)
  9192. continue;
  9193. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9194. continue;
  9195. pickingInfo = result;
  9196. if (fastCheck) {
  9197. break;
  9198. }
  9199. }
  9200. return pickingInfo || new BABYLON.PickingInfo();
  9201. };
  9202. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9203. var _this = this;
  9204. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9205. /// <param name="x">X position on screen</param>
  9206. /// <param name="y">Y position on screen</param>
  9207. /// <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>
  9208. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9209. /// <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>
  9210. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9211. };
  9212. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9213. var _this = this;
  9214. return this._internalPick(function (world) {
  9215. if (!_this._pickWithRayInverseMatrix) {
  9216. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9217. }
  9218. world.invertToRef(_this._pickWithRayInverseMatrix);
  9219. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9220. }, predicate, fastCheck);
  9221. };
  9222. Scene.prototype.setPointerOverMesh = function (mesh) {
  9223. if (this._pointerOverMesh === mesh) {
  9224. return;
  9225. }
  9226. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9227. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9228. }
  9229. this._pointerOverMesh = mesh;
  9230. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9231. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9232. }
  9233. };
  9234. Scene.prototype.getPointerOverMesh = function () {
  9235. return this._pointerOverMesh;
  9236. };
  9237. // Physics
  9238. Scene.prototype.getPhysicsEngine = function () {
  9239. return this._physicsEngine;
  9240. };
  9241. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9242. if (this._physicsEngine) {
  9243. return true;
  9244. }
  9245. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9246. if (!this._physicsEngine.isSupported()) {
  9247. this._physicsEngine = null;
  9248. return false;
  9249. }
  9250. this._physicsEngine._initialize(gravity);
  9251. return true;
  9252. };
  9253. Scene.prototype.disablePhysicsEngine = function () {
  9254. if (!this._physicsEngine) {
  9255. return;
  9256. }
  9257. this._physicsEngine.dispose();
  9258. this._physicsEngine = undefined;
  9259. };
  9260. Scene.prototype.isPhysicsEnabled = function () {
  9261. return this._physicsEngine !== undefined;
  9262. };
  9263. Scene.prototype.setGravity = function (gravity) {
  9264. if (!this._physicsEngine) {
  9265. return;
  9266. }
  9267. this._physicsEngine._setGravity(gravity);
  9268. };
  9269. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9270. if (parts.parts) {
  9271. options = parts;
  9272. parts = parts.parts;
  9273. }
  9274. if (!this._physicsEngine) {
  9275. return null;
  9276. }
  9277. for (var index = 0; index < parts.length; index++) {
  9278. var mesh = parts[index].mesh;
  9279. mesh._physicImpostor = parts[index].impostor;
  9280. mesh._physicsMass = options.mass / parts.length;
  9281. mesh._physicsFriction = options.friction;
  9282. mesh._physicRestitution = options.restitution;
  9283. }
  9284. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9285. };
  9286. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9287. for (var index = 0; index < compound.parts.length; index++) {
  9288. var mesh = compound.parts[index].mesh;
  9289. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9290. this._physicsEngine._unregisterMesh(mesh);
  9291. }
  9292. };
  9293. // Misc.
  9294. Scene.prototype.createDefaultCameraOrLight = function () {
  9295. // Light
  9296. if (this.lights.length === 0) {
  9297. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9298. }
  9299. // Camera
  9300. if (!this.activeCamera) {
  9301. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9302. // Compute position
  9303. var worldExtends = this.getWorldExtends();
  9304. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9305. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9306. camera.setTarget(worldCenter);
  9307. this.activeCamera = camera;
  9308. }
  9309. };
  9310. // Tags
  9311. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9312. if (tagsQuery === undefined) {
  9313. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9314. return list;
  9315. }
  9316. var listByTags = [];
  9317. forEach = forEach || (function (item) {
  9318. return;
  9319. });
  9320. for (var i in list) {
  9321. var item = list[i];
  9322. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9323. listByTags.push(item);
  9324. forEach(item);
  9325. }
  9326. }
  9327. return listByTags;
  9328. };
  9329. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9330. return this._getByTags(this.meshes, tagsQuery, forEach);
  9331. };
  9332. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9333. return this._getByTags(this.cameras, tagsQuery, forEach);
  9334. };
  9335. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9336. return this._getByTags(this.lights, tagsQuery, forEach);
  9337. };
  9338. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9339. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9340. };
  9341. // Audio
  9342. Scene.prototype.switchAudioModeForHeadphones = function () {
  9343. this.mainSoundTrack.switchPanningModelToHRTF();
  9344. for (var i = 0; i < this.soundTracks.length; i++) {
  9345. this.soundTracks[i].switchPanningModelToHRTF();
  9346. }
  9347. };
  9348. Scene.prototype.switchAudioModeForNormalSpeakers = function () {
  9349. this.mainSoundTrack.switchPanningModelToEqualPower();
  9350. for (var i = 0; i < this.soundTracks.length; i++) {
  9351. this.soundTracks[i].switchPanningModelToEqualPower();
  9352. }
  9353. };
  9354. // Statics
  9355. Scene._FOGMODE_NONE = 0;
  9356. Scene._FOGMODE_EXP = 1;
  9357. Scene._FOGMODE_EXP2 = 2;
  9358. Scene._FOGMODE_LINEAR = 3;
  9359. Scene.MinDeltaTime = 1.0;
  9360. Scene.MaxDeltaTime = 1000.0;
  9361. return Scene;
  9362. })();
  9363. BABYLON.Scene = Scene;
  9364. })(BABYLON || (BABYLON = {}));
  9365. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9366. (function (BABYLON) {
  9367. var VertexBuffer = (function () {
  9368. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9369. if (engine instanceof BABYLON.Mesh) {
  9370. this._engine = engine.getScene().getEngine();
  9371. }
  9372. else {
  9373. this._engine = engine;
  9374. }
  9375. this._updatable = updatable;
  9376. this._data = data;
  9377. if (!postponeInternalCreation) {
  9378. this.create();
  9379. }
  9380. this._kind = kind;
  9381. if (stride) {
  9382. this._strideSize = stride;
  9383. return;
  9384. }
  9385. switch (kind) {
  9386. case VertexBuffer.PositionKind:
  9387. this._strideSize = 3;
  9388. break;
  9389. case VertexBuffer.NormalKind:
  9390. this._strideSize = 3;
  9391. break;
  9392. case VertexBuffer.UVKind:
  9393. this._strideSize = 2;
  9394. break;
  9395. case VertexBuffer.UV2Kind:
  9396. this._strideSize = 2;
  9397. break;
  9398. case VertexBuffer.ColorKind:
  9399. this._strideSize = 4;
  9400. break;
  9401. case VertexBuffer.MatricesIndicesKind:
  9402. this._strideSize = 4;
  9403. break;
  9404. case VertexBuffer.MatricesWeightsKind:
  9405. this._strideSize = 4;
  9406. break;
  9407. }
  9408. }
  9409. // Properties
  9410. VertexBuffer.prototype.isUpdatable = function () {
  9411. return this._updatable;
  9412. };
  9413. VertexBuffer.prototype.getData = function () {
  9414. return this._data;
  9415. };
  9416. VertexBuffer.prototype.getBuffer = function () {
  9417. return this._buffer;
  9418. };
  9419. VertexBuffer.prototype.getStrideSize = function () {
  9420. return this._strideSize;
  9421. };
  9422. // Methods
  9423. VertexBuffer.prototype.create = function (data) {
  9424. if (!data && this._buffer) {
  9425. return; // nothing to do
  9426. }
  9427. data = data || this._data;
  9428. if (!this._buffer) {
  9429. if (this._updatable) {
  9430. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9431. }
  9432. else {
  9433. this._buffer = this._engine.createVertexBuffer(data);
  9434. }
  9435. }
  9436. if (this._updatable) {
  9437. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9438. this._data = data;
  9439. }
  9440. };
  9441. VertexBuffer.prototype.update = function (data) {
  9442. this.create(data);
  9443. };
  9444. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9445. if (!this._buffer) {
  9446. return;
  9447. }
  9448. if (this._updatable) {
  9449. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9450. this._data = null;
  9451. }
  9452. };
  9453. VertexBuffer.prototype.dispose = function () {
  9454. if (!this._buffer) {
  9455. return;
  9456. }
  9457. if (this._engine._releaseBuffer(this._buffer)) {
  9458. this._buffer = null;
  9459. }
  9460. };
  9461. Object.defineProperty(VertexBuffer, "PositionKind", {
  9462. get: function () {
  9463. return VertexBuffer._PositionKind;
  9464. },
  9465. enumerable: true,
  9466. configurable: true
  9467. });
  9468. Object.defineProperty(VertexBuffer, "NormalKind", {
  9469. get: function () {
  9470. return VertexBuffer._NormalKind;
  9471. },
  9472. enumerable: true,
  9473. configurable: true
  9474. });
  9475. Object.defineProperty(VertexBuffer, "UVKind", {
  9476. get: function () {
  9477. return VertexBuffer._UVKind;
  9478. },
  9479. enumerable: true,
  9480. configurable: true
  9481. });
  9482. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9483. get: function () {
  9484. return VertexBuffer._UV2Kind;
  9485. },
  9486. enumerable: true,
  9487. configurable: true
  9488. });
  9489. Object.defineProperty(VertexBuffer, "ColorKind", {
  9490. get: function () {
  9491. return VertexBuffer._ColorKind;
  9492. },
  9493. enumerable: true,
  9494. configurable: true
  9495. });
  9496. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9497. get: function () {
  9498. return VertexBuffer._MatricesIndicesKind;
  9499. },
  9500. enumerable: true,
  9501. configurable: true
  9502. });
  9503. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9504. get: function () {
  9505. return VertexBuffer._MatricesWeightsKind;
  9506. },
  9507. enumerable: true,
  9508. configurable: true
  9509. });
  9510. // Enums
  9511. VertexBuffer._PositionKind = "position";
  9512. VertexBuffer._NormalKind = "normal";
  9513. VertexBuffer._UVKind = "uv";
  9514. VertexBuffer._UV2Kind = "uv2";
  9515. VertexBuffer._ColorKind = "color";
  9516. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9517. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9518. return VertexBuffer;
  9519. })();
  9520. BABYLON.VertexBuffer = VertexBuffer;
  9521. })(BABYLON || (BABYLON = {}));
  9522. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9523. var BABYLON;
  9524. (function (BABYLON) {
  9525. var AbstractMesh = (function (_super) {
  9526. __extends(AbstractMesh, _super);
  9527. function AbstractMesh(name, scene) {
  9528. _super.call(this, name, scene);
  9529. // Properties
  9530. this.definedFacingForward = true; // orientation for POV movement & rotation
  9531. this.position = new BABYLON.Vector3(0, 0, 0);
  9532. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9533. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9534. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9535. this.visibility = 1.0;
  9536. this.alphaIndex = Number.MAX_VALUE;
  9537. this.infiniteDistance = false;
  9538. this.isVisible = true;
  9539. this.isPickable = true;
  9540. this.showBoundingBox = false;
  9541. this.showSubMeshesBoundingBox = false;
  9542. this.onDispose = null;
  9543. this.checkCollisions = false;
  9544. this.isBlocker = false;
  9545. this.renderingGroupId = 0;
  9546. this.receiveShadows = false;
  9547. this.renderOutline = false;
  9548. this.outlineColor = BABYLON.Color3.Red();
  9549. this.outlineWidth = 0.02;
  9550. this.renderOverlay = false;
  9551. this.overlayColor = BABYLON.Color3.Red();
  9552. this.overlayAlpha = 0.5;
  9553. this.hasVertexAlpha = false;
  9554. this.useVertexColors = true;
  9555. this.applyFog = true;
  9556. this.useOctreeForRenderingSelection = true;
  9557. this.useOctreeForPicking = true;
  9558. this.useOctreeForCollisions = true;
  9559. this.layerMask = 0xFFFFFFFF;
  9560. // Physics
  9561. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9562. // Collisions
  9563. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9564. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9565. this._collider = new BABYLON.Collider();
  9566. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9567. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9568. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9569. // Cache
  9570. this._localScaling = BABYLON.Matrix.Zero();
  9571. this._localRotation = BABYLON.Matrix.Zero();
  9572. this._localTranslation = BABYLON.Matrix.Zero();
  9573. this._localBillboard = BABYLON.Matrix.Zero();
  9574. this._localPivotScaling = BABYLON.Matrix.Zero();
  9575. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9576. this._localWorld = BABYLON.Matrix.Zero();
  9577. this._worldMatrix = BABYLON.Matrix.Zero();
  9578. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9579. this._absolutePosition = BABYLON.Vector3.Zero();
  9580. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9581. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9582. this._isDirty = false;
  9583. this._pivotMatrix = BABYLON.Matrix.Identity();
  9584. this._isDisposed = false;
  9585. this._renderId = 0;
  9586. this._intersectionsInProgress = new Array();
  9587. this._onAfterWorldMatrixUpdate = new Array();
  9588. scene.meshes.push(this);
  9589. }
  9590. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9591. get: function () {
  9592. return AbstractMesh._BILLBOARDMODE_NONE;
  9593. },
  9594. enumerable: true,
  9595. configurable: true
  9596. });
  9597. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9598. get: function () {
  9599. return AbstractMesh._BILLBOARDMODE_X;
  9600. },
  9601. enumerable: true,
  9602. configurable: true
  9603. });
  9604. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9605. get: function () {
  9606. return AbstractMesh._BILLBOARDMODE_Y;
  9607. },
  9608. enumerable: true,
  9609. configurable: true
  9610. });
  9611. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9612. get: function () {
  9613. return AbstractMesh._BILLBOARDMODE_Z;
  9614. },
  9615. enumerable: true,
  9616. configurable: true
  9617. });
  9618. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9619. get: function () {
  9620. return AbstractMesh._BILLBOARDMODE_ALL;
  9621. },
  9622. enumerable: true,
  9623. configurable: true
  9624. });
  9625. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9626. // Methods
  9627. get: function () {
  9628. return false;
  9629. },
  9630. enumerable: true,
  9631. configurable: true
  9632. });
  9633. AbstractMesh.prototype.getLOD = function (camera) {
  9634. return this;
  9635. };
  9636. AbstractMesh.prototype.getTotalVertices = function () {
  9637. return 0;
  9638. };
  9639. AbstractMesh.prototype.getIndices = function () {
  9640. return null;
  9641. };
  9642. AbstractMesh.prototype.getVerticesData = function (kind) {
  9643. return null;
  9644. };
  9645. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9646. return false;
  9647. };
  9648. AbstractMesh.prototype.getBoundingInfo = function () {
  9649. if (this._masterMesh) {
  9650. return this._masterMesh.getBoundingInfo();
  9651. }
  9652. if (!this._boundingInfo) {
  9653. this._updateBoundingInfo();
  9654. }
  9655. return this._boundingInfo;
  9656. };
  9657. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9658. get: function () {
  9659. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9660. },
  9661. enumerable: true,
  9662. configurable: true
  9663. });
  9664. AbstractMesh.prototype._preActivate = function () {
  9665. };
  9666. AbstractMesh.prototype._activate = function (renderId) {
  9667. this._renderId = renderId;
  9668. };
  9669. AbstractMesh.prototype.getWorldMatrix = function () {
  9670. if (this._masterMesh) {
  9671. return this._masterMesh.getWorldMatrix();
  9672. }
  9673. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9674. this.computeWorldMatrix();
  9675. }
  9676. return this._worldMatrix;
  9677. };
  9678. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9679. get: function () {
  9680. return this._worldMatrix;
  9681. },
  9682. enumerable: true,
  9683. configurable: true
  9684. });
  9685. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9686. get: function () {
  9687. return this._absolutePosition;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9693. if (!this.rotationQuaternion) {
  9694. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9695. this.rotation = BABYLON.Vector3.Zero();
  9696. }
  9697. if (!space || space == 0 /* LOCAL */) {
  9698. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9699. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9700. }
  9701. else {
  9702. if (this.parent) {
  9703. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9704. invertParentWorldMatrix.invert();
  9705. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9706. }
  9707. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9708. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9709. }
  9710. };
  9711. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9712. var displacementVector = axis.scale(distance);
  9713. if (!space || space == 0 /* LOCAL */) {
  9714. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9715. this.setPositionWithLocalVector(tempV3);
  9716. }
  9717. else {
  9718. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9719. }
  9720. };
  9721. AbstractMesh.prototype.getAbsolutePosition = function () {
  9722. this.computeWorldMatrix();
  9723. return this._absolutePosition;
  9724. };
  9725. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9726. if (!absolutePosition) {
  9727. return;
  9728. }
  9729. var absolutePositionX;
  9730. var absolutePositionY;
  9731. var absolutePositionZ;
  9732. if (absolutePosition.x === undefined) {
  9733. if (arguments.length < 3) {
  9734. return;
  9735. }
  9736. absolutePositionX = arguments[0];
  9737. absolutePositionY = arguments[1];
  9738. absolutePositionZ = arguments[2];
  9739. }
  9740. else {
  9741. absolutePositionX = absolutePosition.x;
  9742. absolutePositionY = absolutePosition.y;
  9743. absolutePositionZ = absolutePosition.z;
  9744. }
  9745. if (this.parent) {
  9746. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9747. invertParentWorldMatrix.invert();
  9748. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9749. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9750. }
  9751. else {
  9752. this.position.x = absolutePositionX;
  9753. this.position.y = absolutePositionY;
  9754. this.position.z = absolutePositionZ;
  9755. }
  9756. };
  9757. // ================================== Point of View Movement =================================
  9758. /**
  9759. * Perform relative position change from the point of view of behind the front of the mesh.
  9760. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9761. * Supports definition of mesh facing forward or backward.
  9762. * @param {number} amountRight
  9763. * @param {number} amountUp
  9764. * @param {number} amountForward
  9765. */
  9766. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9767. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9768. };
  9769. /**
  9770. * Calculate relative position change from the point of view of behind the front of the mesh.
  9771. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9772. * Supports definition of mesh facing forward or backward.
  9773. * @param {number} amountRight
  9774. * @param {number} amountUp
  9775. * @param {number} amountForward
  9776. */
  9777. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9778. var rotMatrix = new BABYLON.Matrix();
  9779. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9780. rotQuaternion.toRotationMatrix(rotMatrix);
  9781. var translationDelta = BABYLON.Vector3.Zero();
  9782. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9783. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9784. return translationDelta;
  9785. };
  9786. // ================================== Point of View Rotation =================================
  9787. /**
  9788. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9789. * Supports definition of mesh facing forward or backward.
  9790. * @param {number} flipBack
  9791. * @param {number} twirlClockwise
  9792. * @param {number} tiltRight
  9793. */
  9794. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9795. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9796. };
  9797. /**
  9798. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9799. * Supports definition of mesh facing forward or backward.
  9800. * @param {number} flipBack
  9801. * @param {number} twirlClockwise
  9802. * @param {number} tiltRight
  9803. */
  9804. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9805. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9806. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9807. };
  9808. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9809. this._pivotMatrix = matrix;
  9810. this._cache.pivotMatrixUpdated = true;
  9811. };
  9812. AbstractMesh.prototype.getPivotMatrix = function () {
  9813. return this._pivotMatrix;
  9814. };
  9815. AbstractMesh.prototype._isSynchronized = function () {
  9816. if (this._isDirty) {
  9817. return false;
  9818. }
  9819. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9820. return false;
  9821. if (this._cache.pivotMatrixUpdated) {
  9822. return false;
  9823. }
  9824. if (this.infiniteDistance) {
  9825. return false;
  9826. }
  9827. if (!this._cache.position.equals(this.position))
  9828. return false;
  9829. if (this.rotationQuaternion) {
  9830. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9831. return false;
  9832. }
  9833. else {
  9834. if (!this._cache.rotation.equals(this.rotation))
  9835. return false;
  9836. }
  9837. if (!this._cache.scaling.equals(this.scaling))
  9838. return false;
  9839. return true;
  9840. };
  9841. AbstractMesh.prototype._initCache = function () {
  9842. _super.prototype._initCache.call(this);
  9843. this._cache.localMatrixUpdated = false;
  9844. this._cache.position = BABYLON.Vector3.Zero();
  9845. this._cache.scaling = BABYLON.Vector3.Zero();
  9846. this._cache.rotation = BABYLON.Vector3.Zero();
  9847. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9848. };
  9849. AbstractMesh.prototype.markAsDirty = function (property) {
  9850. if (property === "rotation") {
  9851. this.rotationQuaternion = null;
  9852. }
  9853. this._currentRenderId = Number.MAX_VALUE;
  9854. this._isDirty = true;
  9855. };
  9856. AbstractMesh.prototype._updateBoundingInfo = function () {
  9857. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9858. this._boundingInfo._update(this.worldMatrixFromCache);
  9859. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9860. };
  9861. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9862. if (!this.subMeshes) {
  9863. return;
  9864. }
  9865. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9866. var subMesh = this.subMeshes[subIndex];
  9867. subMesh.updateBoundingInfo(matrix);
  9868. }
  9869. };
  9870. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9871. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9872. return this._worldMatrix;
  9873. }
  9874. this._cache.position.copyFrom(this.position);
  9875. this._cache.scaling.copyFrom(this.scaling);
  9876. this._cache.pivotMatrixUpdated = false;
  9877. this._currentRenderId = this.getScene().getRenderId();
  9878. this._isDirty = false;
  9879. // Scaling
  9880. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9881. // Rotation
  9882. if (this.rotationQuaternion) {
  9883. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9884. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9885. }
  9886. else {
  9887. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9888. this._cache.rotation.copyFrom(this.rotation);
  9889. }
  9890. // Translation
  9891. if (this.infiniteDistance && !this.parent) {
  9892. var camera = this.getScene().activeCamera;
  9893. var cameraWorldMatrix = camera.getWorldMatrix();
  9894. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9895. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9896. }
  9897. else {
  9898. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9899. }
  9900. // Composing transformations
  9901. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9902. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9903. // Billboarding
  9904. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9905. var localPosition = this.position.clone();
  9906. var zero = this.getScene().activeCamera.position.clone();
  9907. if (this.parent && this.parent.position) {
  9908. localPosition.addInPlace(this.parent.position);
  9909. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9910. }
  9911. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9912. zero = this.getScene().activeCamera.position;
  9913. }
  9914. else {
  9915. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9916. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9917. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9918. zero.y = localPosition.y + 0.001;
  9919. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9920. zero.z = localPosition.z + 0.001;
  9921. }
  9922. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9923. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9924. this._localBillboard.invert();
  9925. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9926. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9927. }
  9928. // Local world
  9929. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9930. // Parent
  9931. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9932. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9933. }
  9934. else {
  9935. this._worldMatrix.copyFrom(this._localWorld);
  9936. }
  9937. // Bounding info
  9938. this._updateBoundingInfo();
  9939. // Absolute position
  9940. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9941. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9942. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9943. }
  9944. return this._worldMatrix;
  9945. };
  9946. /**
  9947. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9948. * @param func: callback function to add
  9949. */
  9950. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9951. this._onAfterWorldMatrixUpdate.push(func);
  9952. };
  9953. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9954. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9955. if (index > -1) {
  9956. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9957. }
  9958. };
  9959. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9960. this.computeWorldMatrix();
  9961. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9962. };
  9963. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9964. this.computeWorldMatrix();
  9965. var invLocalWorldMatrix = this._localWorld.clone();
  9966. invLocalWorldMatrix.invert();
  9967. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9968. };
  9969. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9970. this.computeWorldMatrix();
  9971. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9972. };
  9973. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9974. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9975. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9976. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9977. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9978. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9979. /// <returns>Mesh oriented towards targetMesh</returns>
  9980. yawCor = yawCor || 0; // default to zero if undefined
  9981. pitchCor = pitchCor || 0;
  9982. rollCor = rollCor || 0;
  9983. var dv = targetPoint.subtract(this.position);
  9984. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9985. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9986. var pitch = Math.atan2(dv.y, len);
  9987. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9988. };
  9989. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9990. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9991. return false;
  9992. }
  9993. return true;
  9994. };
  9995. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9996. if (!camera) {
  9997. camera = this.getScene().activeCamera;
  9998. }
  9999. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10000. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10001. return false;
  10002. }
  10003. return true;
  10004. };
  10005. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10006. if (!this._boundingInfo || !mesh._boundingInfo) {
  10007. return false;
  10008. }
  10009. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10010. };
  10011. AbstractMesh.prototype.intersectsPoint = function (point) {
  10012. if (!this._boundingInfo) {
  10013. return false;
  10014. }
  10015. return this._boundingInfo.intersectsPoint(point);
  10016. };
  10017. // Physics
  10018. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10019. var physicsEngine = this.getScene().getPhysicsEngine();
  10020. if (!physicsEngine) {
  10021. return;
  10022. }
  10023. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10024. if (impostor.impostor) {
  10025. // Old API
  10026. options = impostor;
  10027. impostor = impostor.impostor;
  10028. }
  10029. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10030. physicsEngine._unregisterMesh(this);
  10031. return;
  10032. }
  10033. if (!options) {
  10034. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10035. }
  10036. else {
  10037. if (!options.mass && options.mass !== 0)
  10038. options.mass = 0;
  10039. if (!options.friction && options.friction !== 0)
  10040. options.friction = 0.2;
  10041. if (!options.restitution && options.restitution !== 0)
  10042. options.restitution = 0.2;
  10043. }
  10044. this._physicImpostor = impostor;
  10045. this._physicsMass = options.mass;
  10046. this._physicsFriction = options.friction;
  10047. this._physicRestitution = options.restitution;
  10048. return physicsEngine._registerMesh(this, impostor, options);
  10049. };
  10050. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10051. if (!this._physicImpostor) {
  10052. return BABYLON.PhysicsEngine.NoImpostor;
  10053. }
  10054. return this._physicImpostor;
  10055. };
  10056. AbstractMesh.prototype.getPhysicsMass = function () {
  10057. if (!this._physicsMass) {
  10058. return 0;
  10059. }
  10060. return this._physicsMass;
  10061. };
  10062. AbstractMesh.prototype.getPhysicsFriction = function () {
  10063. if (!this._physicsFriction) {
  10064. return 0;
  10065. }
  10066. return this._physicsFriction;
  10067. };
  10068. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10069. if (!this._physicRestitution) {
  10070. return 0;
  10071. }
  10072. return this._physicRestitution;
  10073. };
  10074. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10075. if (!camera) {
  10076. camera = this.getScene().activeCamera;
  10077. }
  10078. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10079. };
  10080. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10081. if (!camera) {
  10082. camera = this.getScene().activeCamera;
  10083. }
  10084. return this.absolutePosition.subtract(camera.position).length();
  10085. };
  10086. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10087. if (!this._physicImpostor) {
  10088. return;
  10089. }
  10090. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10091. };
  10092. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10093. if (!this._physicImpostor) {
  10094. return;
  10095. }
  10096. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10097. };
  10098. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10099. if (!this._physicImpostor) {
  10100. return;
  10101. }
  10102. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10103. };
  10104. // Collisions
  10105. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10106. var globalPosition = this.getAbsolutePosition();
  10107. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10108. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10109. this._collider.radius = this.ellipsoid;
  10110. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10111. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10112. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10113. this.position.addInPlace(this._diffPositionForCollisions);
  10114. }
  10115. };
  10116. // Submeshes octree
  10117. /**
  10118. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10119. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10120. */
  10121. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10122. if (maxCapacity === void 0) { maxCapacity = 64; }
  10123. if (maxDepth === void 0) { maxDepth = 2; }
  10124. if (!this._submeshesOctree) {
  10125. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10126. }
  10127. this.computeWorldMatrix(true);
  10128. // Update octree
  10129. var bbox = this.getBoundingInfo().boundingBox;
  10130. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10131. return this._submeshesOctree;
  10132. };
  10133. // Collisions
  10134. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10135. this._generatePointsArray();
  10136. // Transformation
  10137. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10138. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10139. subMesh._lastColliderWorldVertices = [];
  10140. subMesh._trianglePlanes = [];
  10141. var start = subMesh.verticesStart;
  10142. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10143. for (var i = start; i < end; i++) {
  10144. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10145. }
  10146. }
  10147. // Collide
  10148. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10149. };
  10150. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10151. var subMeshes;
  10152. var len;
  10153. // Octrees
  10154. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10155. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10156. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10157. len = intersections.length;
  10158. subMeshes = intersections.data;
  10159. }
  10160. else {
  10161. subMeshes = this.subMeshes;
  10162. len = subMeshes.length;
  10163. }
  10164. for (var index = 0; index < len; index++) {
  10165. var subMesh = subMeshes[index];
  10166. // Bounding test
  10167. if (len > 1 && !subMesh._checkCollision(collider))
  10168. continue;
  10169. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10170. }
  10171. };
  10172. AbstractMesh.prototype._checkCollision = function (collider) {
  10173. // Bounding box test
  10174. if (!this._boundingInfo._checkCollision(collider))
  10175. return;
  10176. // Transformation matrix
  10177. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10178. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10179. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10180. };
  10181. // Picking
  10182. AbstractMesh.prototype._generatePointsArray = function () {
  10183. return false;
  10184. };
  10185. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10186. var pickingInfo = new BABYLON.PickingInfo();
  10187. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10188. return pickingInfo;
  10189. }
  10190. if (!this._generatePointsArray()) {
  10191. return pickingInfo;
  10192. }
  10193. var intersectInfo = null;
  10194. // Octrees
  10195. var subMeshes;
  10196. var len;
  10197. if (this._submeshesOctree && this.useOctreeForPicking) {
  10198. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10199. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10200. len = intersections.length;
  10201. subMeshes = intersections.data;
  10202. }
  10203. else {
  10204. subMeshes = this.subMeshes;
  10205. len = subMeshes.length;
  10206. }
  10207. for (var index = 0; index < len; index++) {
  10208. var subMesh = subMeshes[index];
  10209. // Bounding test
  10210. if (len > 1 && !subMesh.canIntersects(ray))
  10211. continue;
  10212. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10213. if (currentIntersectInfo) {
  10214. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10215. intersectInfo = currentIntersectInfo;
  10216. intersectInfo.subMeshId = index;
  10217. if (fastCheck) {
  10218. break;
  10219. }
  10220. }
  10221. }
  10222. }
  10223. if (intersectInfo) {
  10224. // Get picked point
  10225. var world = this.getWorldMatrix();
  10226. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10227. var direction = ray.direction.clone();
  10228. direction = direction.scale(intersectInfo.distance);
  10229. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10230. var pickedPoint = worldOrigin.add(worldDirection);
  10231. // Return result
  10232. pickingInfo.hit = true;
  10233. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10234. pickingInfo.pickedPoint = pickedPoint;
  10235. pickingInfo.pickedMesh = this;
  10236. pickingInfo.bu = intersectInfo.bu;
  10237. pickingInfo.bv = intersectInfo.bv;
  10238. pickingInfo.faceId = intersectInfo.faceId;
  10239. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10240. return pickingInfo;
  10241. }
  10242. return pickingInfo;
  10243. };
  10244. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10245. return null;
  10246. };
  10247. AbstractMesh.prototype.releaseSubMeshes = function () {
  10248. if (this.subMeshes) {
  10249. while (this.subMeshes.length) {
  10250. this.subMeshes[0].dispose();
  10251. }
  10252. }
  10253. else {
  10254. this.subMeshes = new Array();
  10255. }
  10256. };
  10257. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10258. // Physics
  10259. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10260. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10261. }
  10262. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10263. var other = this._intersectionsInProgress[index];
  10264. var pos = other._intersectionsInProgress.indexOf(this);
  10265. other._intersectionsInProgress.splice(pos, 1);
  10266. }
  10267. this._intersectionsInProgress = [];
  10268. // SubMeshes
  10269. this.releaseSubMeshes();
  10270. // Remove from scene
  10271. var index = this.getScene().meshes.indexOf(this);
  10272. if (index != -1) {
  10273. // Remove from the scene if mesh found
  10274. this.getScene().meshes.splice(index, 1);
  10275. }
  10276. if (!doNotRecurse) {
  10277. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10278. if (this.getScene().particleSystems[index].emitter == this) {
  10279. this.getScene().particleSystems[index].dispose();
  10280. index--;
  10281. }
  10282. }
  10283. // Children
  10284. var objects = this.getScene().meshes.slice(0);
  10285. for (index = 0; index < objects.length; index++) {
  10286. if (objects[index].parent == this) {
  10287. objects[index].dispose();
  10288. }
  10289. }
  10290. }
  10291. else {
  10292. for (index = 0; index < this.getScene().meshes.length; index++) {
  10293. var obj = this.getScene().meshes[index];
  10294. if (obj.parent === this) {
  10295. obj.parent = null;
  10296. obj.computeWorldMatrix(true);
  10297. }
  10298. }
  10299. }
  10300. this._onAfterWorldMatrixUpdate = [];
  10301. this._isDisposed = true;
  10302. // Callback
  10303. if (this.onDispose) {
  10304. this.onDispose();
  10305. }
  10306. };
  10307. // Statics
  10308. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10309. AbstractMesh._BILLBOARDMODE_X = 1;
  10310. AbstractMesh._BILLBOARDMODE_Y = 2;
  10311. AbstractMesh._BILLBOARDMODE_Z = 4;
  10312. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10313. return AbstractMesh;
  10314. })(BABYLON.Node);
  10315. BABYLON.AbstractMesh = AbstractMesh;
  10316. })(BABYLON || (BABYLON = {}));
  10317. //# sourceMappingURL=babylon.abstractMesh.js.map
  10318. var BABYLON;
  10319. (function (BABYLON) {
  10320. var _InstancesBatch = (function () {
  10321. function _InstancesBatch() {
  10322. this.mustReturn = false;
  10323. this.visibleInstances = new Array();
  10324. this.renderSelf = new Array();
  10325. }
  10326. return _InstancesBatch;
  10327. })();
  10328. BABYLON._InstancesBatch = _InstancesBatch;
  10329. var Mesh = (function (_super) {
  10330. __extends(Mesh, _super);
  10331. /**
  10332. * @constructor
  10333. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10334. * @param {Scene} scene - The scene to add this mesh to.
  10335. * @param {Node} parent - The parent of this mesh, if it has one
  10336. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10337. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10338. * When false, achieved by calling a clone(), also passing False.
  10339. * This will make creation of children, recursive.
  10340. */
  10341. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10342. if (parent === void 0) { parent = null; }
  10343. _super.call(this, name, scene);
  10344. // Members
  10345. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10346. this.instances = new Array();
  10347. this._LODLevels = new Array();
  10348. this._onBeforeRenderCallbacks = new Array();
  10349. this._onAfterRenderCallbacks = new Array();
  10350. this._visibleInstances = {};
  10351. this._renderIdForInstances = new Array();
  10352. this._batchCache = new _InstancesBatch();
  10353. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10354. if (source) {
  10355. // Geometry
  10356. if (source._geometry) {
  10357. source._geometry.applyToMesh(this);
  10358. }
  10359. // Deep copy
  10360. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10361. // Material
  10362. this.material = source.material;
  10363. if (!doNotCloneChildren) {
  10364. for (var index = 0; index < scene.meshes.length; index++) {
  10365. var mesh = scene.meshes[index];
  10366. if (mesh.parent === source) {
  10367. // doNotCloneChildren is always going to be False
  10368. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10369. }
  10370. }
  10371. }
  10372. for (index = 0; index < scene.particleSystems.length; index++) {
  10373. var system = scene.particleSystems[index];
  10374. if (system.emitter === source) {
  10375. system.clone(system.name, this);
  10376. }
  10377. }
  10378. this.computeWorldMatrix(true);
  10379. }
  10380. // Parent
  10381. if (parent !== null) {
  10382. this.parent = parent;
  10383. }
  10384. }
  10385. Object.defineProperty(Mesh, "FRONTSIDE", {
  10386. get: function () {
  10387. return Mesh._FRONTSIDE;
  10388. },
  10389. enumerable: true,
  10390. configurable: true
  10391. });
  10392. Object.defineProperty(Mesh, "BACKSIDE", {
  10393. get: function () {
  10394. return Mesh._BACKSIDE;
  10395. },
  10396. enumerable: true,
  10397. configurable: true
  10398. });
  10399. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10400. get: function () {
  10401. return Mesh._DOUBLESIDE;
  10402. },
  10403. enumerable: true,
  10404. configurable: true
  10405. });
  10406. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10407. get: function () {
  10408. return Mesh._DEFAULTSIDE;
  10409. },
  10410. enumerable: true,
  10411. configurable: true
  10412. });
  10413. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10414. // Methods
  10415. get: function () {
  10416. return this._LODLevels.length > 0;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Mesh.prototype._sortLODLevels = function () {
  10422. this._LODLevels.sort(function (a, b) {
  10423. if (a.distance < b.distance) {
  10424. return 1;
  10425. }
  10426. if (a.distance > b.distance) {
  10427. return -1;
  10428. }
  10429. return 0;
  10430. });
  10431. };
  10432. /**
  10433. * Add a mesh as LOD level triggered at the given distance.
  10434. * @param {number} distance - the distance from the center of the object to show this level
  10435. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10436. * @return {BABYLON.Mesh} this mesh (for chaining)
  10437. */
  10438. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10439. if (mesh && mesh._masterMesh) {
  10440. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10441. return this;
  10442. }
  10443. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10444. this._LODLevels.push(level);
  10445. if (mesh) {
  10446. mesh._masterMesh = this;
  10447. }
  10448. this._sortLODLevels();
  10449. return this;
  10450. };
  10451. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10452. for (var index = 0; index < this._LODLevels.length; index++) {
  10453. var level = this._LODLevels[index];
  10454. if (level.distance === distance) {
  10455. return level.mesh;
  10456. }
  10457. }
  10458. return null;
  10459. };
  10460. /**
  10461. * Remove a mesh from the LOD array
  10462. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10463. * @return {BABYLON.Mesh} this mesh (for chaining)
  10464. */
  10465. Mesh.prototype.removeLODLevel = function (mesh) {
  10466. for (var index = 0; index < this._LODLevels.length; index++) {
  10467. if (this._LODLevels[index].mesh === mesh) {
  10468. this._LODLevels.splice(index, 1);
  10469. if (mesh) {
  10470. mesh._masterMesh = null;
  10471. }
  10472. }
  10473. }
  10474. this._sortLODLevels();
  10475. return this;
  10476. };
  10477. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10478. if (!this._LODLevels || this._LODLevels.length === 0) {
  10479. return this;
  10480. }
  10481. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10482. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10483. return this;
  10484. }
  10485. for (var index = 0; index < this._LODLevels.length; index++) {
  10486. var level = this._LODLevels[index];
  10487. if (level.distance < distanceToCamera) {
  10488. if (level.mesh) {
  10489. level.mesh._preActivate();
  10490. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10491. }
  10492. return level.mesh;
  10493. }
  10494. }
  10495. return this;
  10496. };
  10497. Object.defineProperty(Mesh.prototype, "geometry", {
  10498. get: function () {
  10499. return this._geometry;
  10500. },
  10501. enumerable: true,
  10502. configurable: true
  10503. });
  10504. Mesh.prototype.getTotalVertices = function () {
  10505. if (!this._geometry) {
  10506. return 0;
  10507. }
  10508. return this._geometry.getTotalVertices();
  10509. };
  10510. Mesh.prototype.getVerticesData = function (kind) {
  10511. if (!this._geometry) {
  10512. return null;
  10513. }
  10514. return this._geometry.getVerticesData(kind);
  10515. };
  10516. Mesh.prototype.getVertexBuffer = function (kind) {
  10517. if (!this._geometry) {
  10518. return undefined;
  10519. }
  10520. return this._geometry.getVertexBuffer(kind);
  10521. };
  10522. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10523. if (!this._geometry) {
  10524. if (this._delayInfo) {
  10525. return this._delayInfo.indexOf(kind) !== -1;
  10526. }
  10527. return false;
  10528. }
  10529. return this._geometry.isVerticesDataPresent(kind);
  10530. };
  10531. Mesh.prototype.getVerticesDataKinds = function () {
  10532. if (!this._geometry) {
  10533. var result = [];
  10534. if (this._delayInfo) {
  10535. for (var kind in this._delayInfo) {
  10536. result.push(kind);
  10537. }
  10538. }
  10539. return result;
  10540. }
  10541. return this._geometry.getVerticesDataKinds();
  10542. };
  10543. Mesh.prototype.getTotalIndices = function () {
  10544. if (!this._geometry) {
  10545. return 0;
  10546. }
  10547. return this._geometry.getTotalIndices();
  10548. };
  10549. Mesh.prototype.getIndices = function () {
  10550. if (!this._geometry) {
  10551. return [];
  10552. }
  10553. return this._geometry.getIndices();
  10554. };
  10555. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10556. get: function () {
  10557. return this._masterMesh !== null && this._masterMesh !== undefined;
  10558. },
  10559. enumerable: true,
  10560. configurable: true
  10561. });
  10562. Mesh.prototype.isReady = function () {
  10563. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10564. return false;
  10565. }
  10566. return _super.prototype.isReady.call(this);
  10567. };
  10568. Mesh.prototype.isDisposed = function () {
  10569. return this._isDisposed;
  10570. };
  10571. // Methods
  10572. Mesh.prototype._preActivate = function () {
  10573. var sceneRenderId = this.getScene().getRenderId();
  10574. if (this._preActivateId === sceneRenderId) {
  10575. return;
  10576. }
  10577. this._preActivateId = sceneRenderId;
  10578. this._visibleInstances = null;
  10579. };
  10580. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10581. if (!this._visibleInstances) {
  10582. this._visibleInstances = {};
  10583. this._visibleInstances.defaultRenderId = renderId;
  10584. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10585. }
  10586. if (!this._visibleInstances[renderId]) {
  10587. this._visibleInstances[renderId] = new Array();
  10588. }
  10589. this._visibleInstances[renderId].push(instance);
  10590. };
  10591. Mesh.prototype.refreshBoundingInfo = function () {
  10592. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10593. if (data) {
  10594. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10595. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10596. }
  10597. if (this.subMeshes) {
  10598. for (var index = 0; index < this.subMeshes.length; index++) {
  10599. this.subMeshes[index].refreshBoundingInfo();
  10600. }
  10601. }
  10602. this._updateBoundingInfo();
  10603. };
  10604. Mesh.prototype._createGlobalSubMesh = function () {
  10605. var totalVertices = this.getTotalVertices();
  10606. if (!totalVertices || !this.getIndices()) {
  10607. return null;
  10608. }
  10609. this.releaseSubMeshes();
  10610. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10611. };
  10612. Mesh.prototype.subdivide = function (count) {
  10613. if (count < 1) {
  10614. return;
  10615. }
  10616. var totalIndices = this.getTotalIndices();
  10617. var subdivisionSize = (totalIndices / count) | 0;
  10618. var offset = 0;
  10619. while (subdivisionSize % 3 !== 0) {
  10620. subdivisionSize++;
  10621. }
  10622. this.releaseSubMeshes();
  10623. for (var index = 0; index < count; index++) {
  10624. if (offset >= totalIndices) {
  10625. break;
  10626. }
  10627. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10628. offset += subdivisionSize;
  10629. }
  10630. this.synchronizeInstances();
  10631. };
  10632. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10633. if (kind instanceof Array) {
  10634. var temp = data;
  10635. data = kind;
  10636. kind = temp;
  10637. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10638. }
  10639. if (!this._geometry) {
  10640. var vertexData = new BABYLON.VertexData();
  10641. vertexData.set(data, kind);
  10642. var scene = this.getScene();
  10643. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10644. }
  10645. else {
  10646. this._geometry.setVerticesData(kind, data, updatable, stride);
  10647. }
  10648. };
  10649. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10650. if (!this._geometry) {
  10651. return;
  10652. }
  10653. if (!makeItUnique) {
  10654. this._geometry.updateVerticesData(kind, data, updateExtends);
  10655. }
  10656. else {
  10657. this.makeGeometryUnique();
  10658. this.updateVerticesData(kind, data, updateExtends, false);
  10659. }
  10660. };
  10661. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10662. if (!this._geometry) {
  10663. return;
  10664. }
  10665. if (!makeItUnique) {
  10666. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10667. }
  10668. else {
  10669. this.makeGeometryUnique();
  10670. this.updateVerticesDataDirectly(kind, data, offset, false);
  10671. }
  10672. };
  10673. Mesh.prototype.makeGeometryUnique = function () {
  10674. if (!this._geometry) {
  10675. return;
  10676. }
  10677. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10678. geometry.applyToMesh(this);
  10679. };
  10680. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10681. if (!this._geometry) {
  10682. var vertexData = new BABYLON.VertexData();
  10683. vertexData.indices = indices;
  10684. var scene = this.getScene();
  10685. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10686. }
  10687. else {
  10688. this._geometry.setIndices(indices, totalVertices);
  10689. }
  10690. };
  10691. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10692. var engine = this.getScene().getEngine();
  10693. // Wireframe
  10694. var indexToBind;
  10695. switch (fillMode) {
  10696. case BABYLON.Material.PointFillMode:
  10697. indexToBind = null;
  10698. break;
  10699. case BABYLON.Material.WireFrameFillMode:
  10700. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10701. break;
  10702. default:
  10703. case BABYLON.Material.TriangleFillMode:
  10704. indexToBind = this._geometry.getIndexBuffer();
  10705. break;
  10706. }
  10707. // VBOs
  10708. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10709. };
  10710. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10711. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10712. return;
  10713. }
  10714. var engine = this.getScene().getEngine();
  10715. switch (fillMode) {
  10716. case BABYLON.Material.PointFillMode:
  10717. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10718. break;
  10719. case BABYLON.Material.WireFrameFillMode:
  10720. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10721. break;
  10722. default:
  10723. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10724. }
  10725. };
  10726. Mesh.prototype.registerBeforeRender = function (func) {
  10727. this._onBeforeRenderCallbacks.push(func);
  10728. };
  10729. Mesh.prototype.unregisterBeforeRender = function (func) {
  10730. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10731. if (index > -1) {
  10732. this._onBeforeRenderCallbacks.splice(index, 1);
  10733. }
  10734. };
  10735. Mesh.prototype.registerAfterRender = function (func) {
  10736. this._onAfterRenderCallbacks.push(func);
  10737. };
  10738. Mesh.prototype.unregisterAfterRender = function (func) {
  10739. var index = this._onAfterRenderCallbacks.indexOf(func);
  10740. if (index > -1) {
  10741. this._onAfterRenderCallbacks.splice(index, 1);
  10742. }
  10743. };
  10744. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10745. var scene = this.getScene();
  10746. this._batchCache.mustReturn = false;
  10747. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10748. this._batchCache.visibleInstances[subMeshId] = null;
  10749. if (this._visibleInstances) {
  10750. var currentRenderId = scene.getRenderId();
  10751. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10752. var selfRenderId = this._renderId;
  10753. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10754. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10755. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10756. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10757. }
  10758. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10759. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10760. this._batchCache.mustReturn = true;
  10761. return this._batchCache;
  10762. }
  10763. if (currentRenderId !== selfRenderId) {
  10764. this._batchCache.renderSelf[subMeshId] = false;
  10765. }
  10766. }
  10767. this._renderIdForInstances[subMeshId] = currentRenderId;
  10768. }
  10769. return this._batchCache;
  10770. };
  10771. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10772. var visibleInstances = batch.visibleInstances[subMesh._id];
  10773. var matricesCount = visibleInstances.length + 1;
  10774. var bufferSize = matricesCount * 16 * 4;
  10775. while (this._instancesBufferSize < bufferSize) {
  10776. this._instancesBufferSize *= 2;
  10777. }
  10778. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10779. if (this._worldMatricesInstancesBuffer) {
  10780. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10781. }
  10782. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10783. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10784. }
  10785. var offset = 0;
  10786. var instancesCount = 0;
  10787. var world = this.getWorldMatrix();
  10788. if (batch.renderSelf[subMesh._id]) {
  10789. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10790. offset += 16;
  10791. instancesCount++;
  10792. }
  10793. if (visibleInstances) {
  10794. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10795. var instance = visibleInstances[instanceIndex];
  10796. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10797. offset += 16;
  10798. instancesCount++;
  10799. }
  10800. }
  10801. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10802. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10803. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10804. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10805. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10806. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10807. this._draw(subMesh, fillMode, instancesCount);
  10808. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10809. };
  10810. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10811. var scene = this.getScene();
  10812. var engine = scene.getEngine();
  10813. if (hardwareInstancedRendering) {
  10814. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10815. }
  10816. else {
  10817. if (batch.renderSelf[subMesh._id]) {
  10818. // Draw
  10819. if (onBeforeDraw) {
  10820. onBeforeDraw(false, this.getWorldMatrix());
  10821. }
  10822. this._draw(subMesh, fillMode);
  10823. }
  10824. if (batch.visibleInstances[subMesh._id]) {
  10825. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10826. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10827. // World
  10828. var world = instance.getWorldMatrix();
  10829. if (onBeforeDraw) {
  10830. onBeforeDraw(true, world);
  10831. }
  10832. // Draw
  10833. this._draw(subMesh, fillMode);
  10834. }
  10835. }
  10836. }
  10837. };
  10838. Mesh.prototype.render = function (subMesh) {
  10839. var scene = this.getScene();
  10840. // Managing instances
  10841. var batch = this._getInstancesRenderList(subMesh._id);
  10842. if (batch.mustReturn) {
  10843. return;
  10844. }
  10845. // Checking geometry state
  10846. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10847. return;
  10848. }
  10849. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10850. this._onBeforeRenderCallbacks[callbackIndex](this);
  10851. }
  10852. var engine = scene.getEngine();
  10853. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10854. // Material
  10855. var effectiveMaterial = subMesh.getMaterial();
  10856. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10857. return;
  10858. }
  10859. // Outline - step 1
  10860. var savedDepthWrite = engine.getDepthWrite();
  10861. if (this.renderOutline) {
  10862. engine.setDepthWrite(false);
  10863. scene.getOutlineRenderer().render(subMesh, batch);
  10864. engine.setDepthWrite(savedDepthWrite);
  10865. }
  10866. effectiveMaterial._preBind();
  10867. var effect = effectiveMaterial.getEffect();
  10868. // Bind
  10869. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10870. this._bind(subMesh, effect, fillMode);
  10871. var world = this.getWorldMatrix();
  10872. effectiveMaterial.bind(world, this);
  10873. // Draw
  10874. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10875. if (isInstance) {
  10876. effectiveMaterial.bindOnlyWorldMatrix(world);
  10877. }
  10878. });
  10879. // Unbind
  10880. effectiveMaterial.unbind();
  10881. // Outline - step 2
  10882. if (this.renderOutline && savedDepthWrite) {
  10883. engine.setDepthWrite(true);
  10884. engine.setColorWrite(false);
  10885. scene.getOutlineRenderer().render(subMesh, batch);
  10886. engine.setColorWrite(true);
  10887. }
  10888. // Overlay
  10889. if (this.renderOverlay) {
  10890. var currentMode = engine.getAlphaMode();
  10891. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10892. scene.getOutlineRenderer().render(subMesh, batch, true);
  10893. engine.setAlphaMode(currentMode);
  10894. }
  10895. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10896. this._onAfterRenderCallbacks[callbackIndex](this);
  10897. }
  10898. };
  10899. Mesh.prototype.getEmittedParticleSystems = function () {
  10900. var results = new Array();
  10901. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10902. var particleSystem = this.getScene().particleSystems[index];
  10903. if (particleSystem.emitter === this) {
  10904. results.push(particleSystem);
  10905. }
  10906. }
  10907. return results;
  10908. };
  10909. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10910. var results = new Array();
  10911. var descendants = this.getDescendants();
  10912. descendants.push(this);
  10913. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10914. var particleSystem = this.getScene().particleSystems[index];
  10915. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10916. results.push(particleSystem);
  10917. }
  10918. }
  10919. return results;
  10920. };
  10921. Mesh.prototype.getChildren = function () {
  10922. var results = [];
  10923. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10924. var mesh = this.getScene().meshes[index];
  10925. if (mesh.parent === this) {
  10926. results.push(mesh);
  10927. }
  10928. }
  10929. return results;
  10930. };
  10931. Mesh.prototype._checkDelayState = function () {
  10932. var _this = this;
  10933. var that = this;
  10934. var scene = this.getScene();
  10935. if (this._geometry) {
  10936. this._geometry.load(scene);
  10937. }
  10938. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10939. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10940. scene._addPendingData(that);
  10941. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10942. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10943. if (data instanceof ArrayBuffer) {
  10944. _this._delayLoadingFunction(data, _this);
  10945. }
  10946. else {
  10947. _this._delayLoadingFunction(JSON.parse(data), _this);
  10948. }
  10949. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10950. scene._removePendingData(_this);
  10951. }, function () {
  10952. }, scene.database, getBinaryData);
  10953. }
  10954. };
  10955. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10956. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10957. return false;
  10958. }
  10959. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10960. return false;
  10961. }
  10962. this._checkDelayState();
  10963. return true;
  10964. };
  10965. Mesh.prototype.setMaterialByID = function (id) {
  10966. var materials = this.getScene().materials;
  10967. for (var index = 0; index < materials.length; index++) {
  10968. if (materials[index].id === id) {
  10969. this.material = materials[index];
  10970. return;
  10971. }
  10972. }
  10973. // Multi
  10974. var multiMaterials = this.getScene().multiMaterials;
  10975. for (index = 0; index < multiMaterials.length; index++) {
  10976. if (multiMaterials[index].id === id) {
  10977. this.material = multiMaterials[index];
  10978. return;
  10979. }
  10980. }
  10981. };
  10982. Mesh.prototype.getAnimatables = function () {
  10983. var results = [];
  10984. if (this.material) {
  10985. results.push(this.material);
  10986. }
  10987. if (this.skeleton) {
  10988. results.push(this.skeleton);
  10989. }
  10990. return results;
  10991. };
  10992. // Geometry
  10993. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10994. // Position
  10995. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10996. return;
  10997. }
  10998. this._resetPointsArrayCache();
  10999. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11000. var temp = [];
  11001. for (var index = 0; index < data.length; index += 3) {
  11002. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11003. }
  11004. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11005. // Normals
  11006. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11007. return;
  11008. }
  11009. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11010. for (index = 0; index < data.length; index += 3) {
  11011. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11012. }
  11013. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11014. };
  11015. // Cache
  11016. Mesh.prototype._resetPointsArrayCache = function () {
  11017. this._positions = null;
  11018. };
  11019. Mesh.prototype._generatePointsArray = function () {
  11020. if (this._positions)
  11021. return true;
  11022. this._positions = [];
  11023. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11024. if (!data) {
  11025. return false;
  11026. }
  11027. for (var index = 0; index < data.length; index += 3) {
  11028. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11029. }
  11030. return true;
  11031. };
  11032. // Clone
  11033. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11034. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11035. };
  11036. // Dispose
  11037. Mesh.prototype.dispose = function (doNotRecurse) {
  11038. if (this._geometry) {
  11039. this._geometry.releaseForMesh(this, true);
  11040. }
  11041. // Instances
  11042. if (this._worldMatricesInstancesBuffer) {
  11043. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11044. this._worldMatricesInstancesBuffer = null;
  11045. }
  11046. while (this.instances.length) {
  11047. this.instances[0].dispose();
  11048. }
  11049. _super.prototype.dispose.call(this, doNotRecurse);
  11050. };
  11051. // Geometric tools
  11052. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11053. var _this = this;
  11054. var scene = this.getScene();
  11055. var onload = function (img) {
  11056. // Getting height map data
  11057. var canvas = document.createElement("canvas");
  11058. var context = canvas.getContext("2d");
  11059. var heightMapWidth = img.width;
  11060. var heightMapHeight = img.height;
  11061. canvas.width = heightMapWidth;
  11062. canvas.height = heightMapHeight;
  11063. context.drawImage(img, 0, 0);
  11064. // Create VertexData from map data
  11065. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11066. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11067. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11068. //execute success callback, if set
  11069. if (onSuccess) {
  11070. onSuccess(_this);
  11071. }
  11072. };
  11073. BABYLON.Tools.LoadImage(url, onload, function () {
  11074. }, scene.database);
  11075. };
  11076. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11077. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11078. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11079. return;
  11080. }
  11081. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11082. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11083. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11084. var position = BABYLON.Vector3.Zero();
  11085. var normal = BABYLON.Vector3.Zero();
  11086. var uv = BABYLON.Vector2.Zero();
  11087. for (var index = 0; index < positions.length; index += 3) {
  11088. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11089. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11090. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11091. // Compute height
  11092. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11093. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11094. var pos = (u + v * heightMapWidth) * 4;
  11095. var r = buffer[pos] / 255.0;
  11096. var g = buffer[pos + 1] / 255.0;
  11097. var b = buffer[pos + 2] / 255.0;
  11098. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11099. normal.normalize();
  11100. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11101. position = position.add(normal);
  11102. position.toArray(positions, index);
  11103. }
  11104. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11105. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11106. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11107. };
  11108. Mesh.prototype.convertToFlatShadedMesh = function () {
  11109. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11110. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11111. var kinds = this.getVerticesDataKinds();
  11112. var vbs = [];
  11113. var data = [];
  11114. var newdata = [];
  11115. var updatableNormals = false;
  11116. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11117. var kind = kinds[kindIndex];
  11118. var vertexBuffer = this.getVertexBuffer(kind);
  11119. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11120. updatableNormals = vertexBuffer.isUpdatable();
  11121. kinds.splice(kindIndex, 1);
  11122. kindIndex--;
  11123. continue;
  11124. }
  11125. vbs[kind] = vertexBuffer;
  11126. data[kind] = vbs[kind].getData();
  11127. newdata[kind] = [];
  11128. }
  11129. // Save previous submeshes
  11130. var previousSubmeshes = this.subMeshes.slice(0);
  11131. var indices = this.getIndices();
  11132. var totalIndices = this.getTotalIndices();
  11133. for (var index = 0; index < totalIndices; index++) {
  11134. var vertexIndex = indices[index];
  11135. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11136. kind = kinds[kindIndex];
  11137. var stride = vbs[kind].getStrideSize();
  11138. for (var offset = 0; offset < stride; offset++) {
  11139. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11140. }
  11141. }
  11142. }
  11143. // Updating faces & normal
  11144. var normals = [];
  11145. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11146. for (index = 0; index < totalIndices; index += 3) {
  11147. indices[index] = index;
  11148. indices[index + 1] = index + 1;
  11149. indices[index + 2] = index + 2;
  11150. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11151. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11152. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11153. var p1p2 = p1.subtract(p2);
  11154. var p3p2 = p3.subtract(p2);
  11155. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11156. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11157. normals.push(normal.x);
  11158. normals.push(normal.y);
  11159. normals.push(normal.z);
  11160. }
  11161. }
  11162. this.setIndices(indices);
  11163. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11164. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11165. kind = kinds[kindIndex];
  11166. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11167. }
  11168. // Updating submeshes
  11169. this.releaseSubMeshes();
  11170. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11171. var previousOne = previousSubmeshes[submeshIndex];
  11172. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11173. }
  11174. this.synchronizeInstances();
  11175. };
  11176. // Instances
  11177. Mesh.prototype.createInstance = function (name) {
  11178. return new BABYLON.InstancedMesh(name, this);
  11179. };
  11180. Mesh.prototype.synchronizeInstances = function () {
  11181. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11182. var instance = this.instances[instanceIndex];
  11183. instance._syncSubMeshes();
  11184. }
  11185. };
  11186. /**
  11187. * Simplify the mesh according to the given array of settings.
  11188. * Function will return immediately and will simplify async.
  11189. * @param settings a collection of simplification settings.
  11190. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11191. * @param type the type of simplification to run.
  11192. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11193. */
  11194. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11195. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11196. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11197. this.getScene().simplificationQueue.addTask({
  11198. settings: settings,
  11199. parallelProcessing: parallelProcessing,
  11200. mesh: this,
  11201. simplificationType: simplificationType,
  11202. successCallback: successCallback
  11203. });
  11204. };
  11205. // Statics
  11206. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11207. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11208. var ribbon = new Mesh(name, scene);
  11209. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11210. vertexData.applyToMesh(ribbon, updatable);
  11211. return ribbon;
  11212. };
  11213. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11214. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11215. var box = new Mesh(name, scene);
  11216. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11217. vertexData.applyToMesh(box, updatable);
  11218. return box;
  11219. };
  11220. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11221. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11222. var sphere = new Mesh(name, scene);
  11223. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11224. vertexData.applyToMesh(sphere, updatable);
  11225. return sphere;
  11226. };
  11227. // Cylinder and cone (Code inspired by SharpDX.org)
  11228. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11229. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11230. // subdivisions is a new parameter, we need to support old signature
  11231. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11232. if (scene !== undefined) {
  11233. updatable = scene;
  11234. }
  11235. scene = subdivisions;
  11236. subdivisions = 1;
  11237. }
  11238. var cylinder = new Mesh(name, scene);
  11239. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11240. vertexData.applyToMesh(cylinder, updatable);
  11241. return cylinder;
  11242. };
  11243. // Torus (Code from SharpDX.org)
  11244. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11245. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11246. var torus = new Mesh(name, scene);
  11247. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11248. vertexData.applyToMesh(torus, updatable);
  11249. return torus;
  11250. };
  11251. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11252. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11253. var torusKnot = new Mesh(name, scene);
  11254. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11255. vertexData.applyToMesh(torusKnot, updatable);
  11256. return torusKnot;
  11257. };
  11258. // Lines
  11259. Mesh.CreateLines = function (name, points, scene, updatable) {
  11260. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11261. var vertexData = BABYLON.VertexData.CreateLines(points);
  11262. vertexData.applyToMesh(lines, updatable);
  11263. return lines;
  11264. };
  11265. // Extrusion
  11266. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11267. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11268. scale = scale || 1;
  11269. rotation = rotation || 0;
  11270. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11271. return extruded;
  11272. };
  11273. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotateFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11274. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11275. ribbonCloseArray = ribbonCloseArray || false;
  11276. ribbonClosePath = ribbonClosePath || false;
  11277. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotateFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11278. return extrudedCustom;
  11279. };
  11280. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11281. var path3D = new BABYLON.Path3D(curve);
  11282. var tangents = path3D.getTangents();
  11283. var normals = path3D.getNormals();
  11284. var binormals = path3D.getBinormals();
  11285. var distances = path3D.getDistances();
  11286. var shapePaths = new Array();
  11287. var angle = 0;
  11288. var returnScale = function (i, distance) {
  11289. return scale;
  11290. };
  11291. var returnRotation = function (i, distance) {
  11292. return rotation;
  11293. };
  11294. var rotate = custom ? rotateFunction : returnRotation;
  11295. var scl = custom ? scaleFunction : returnScale;
  11296. for (var i = 0; i < curve.length; i++) {
  11297. var shapePath = new Array();
  11298. var angleStep = rotate(i, distances[i]);
  11299. var scaleRatio = scl(i, distances[i]);
  11300. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11301. for (var p = 0; p < shape.length; p++) {
  11302. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11303. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11304. shapePath.push(rotated);
  11305. }
  11306. shapePaths.push(shapePath);
  11307. angle += angleStep;
  11308. }
  11309. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11310. return extrudedGeneric;
  11311. };
  11312. // Plane & ground
  11313. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11314. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11315. var plane = new Mesh(name, scene);
  11316. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11317. vertexData.applyToMesh(plane, updatable);
  11318. return plane;
  11319. };
  11320. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11321. var ground = new BABYLON.GroundMesh(name, scene);
  11322. ground._setReady(false);
  11323. ground._subdivisions = subdivisions;
  11324. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11325. vertexData.applyToMesh(ground, updatable);
  11326. ground._setReady(true);
  11327. return ground;
  11328. };
  11329. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11330. var tiledGround = new Mesh(name, scene);
  11331. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11332. vertexData.applyToMesh(tiledGround, updatable);
  11333. return tiledGround;
  11334. };
  11335. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11336. var ground = new BABYLON.GroundMesh(name, scene);
  11337. ground._subdivisions = subdivisions;
  11338. ground._setReady(false);
  11339. var onload = function (img) {
  11340. // Getting height map data
  11341. var canvas = document.createElement("canvas");
  11342. var context = canvas.getContext("2d");
  11343. var heightMapWidth = img.width;
  11344. var heightMapHeight = img.height;
  11345. canvas.width = heightMapWidth;
  11346. canvas.height = heightMapHeight;
  11347. context.drawImage(img, 0, 0);
  11348. // Create VertexData from map data
  11349. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11350. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11351. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11352. vertexData.applyToMesh(ground, updatable);
  11353. ground._setReady(true);
  11354. //execute ready callback, if set
  11355. if (onReady) {
  11356. onReady(ground);
  11357. }
  11358. };
  11359. BABYLON.Tools.LoadImage(url, onload, function () {
  11360. }, scene.database);
  11361. return ground;
  11362. };
  11363. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11364. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11365. var path3D = new BABYLON.Path3D(path);
  11366. var tangents = path3D.getTangents();
  11367. var normals = path3D.getNormals();
  11368. var distances = path3D.getDistances();
  11369. var pi2 = Math.PI * 2;
  11370. var step = pi2 / tesselation;
  11371. var returnRadius = function (i, distance) { return radius; };
  11372. var radiusFunctionFinal = radiusFunction || returnRadius;
  11373. var circlePaths = [];
  11374. var circlePath;
  11375. var rad;
  11376. var normal;
  11377. var rotated;
  11378. var rotationMatrix;
  11379. for (var i = 0; i < path.length; i++) {
  11380. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11381. circlePath = []; // current circle array
  11382. normal = normals[i]; // current normal
  11383. for (var ang = 0; ang < pi2; ang += step) {
  11384. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11385. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11386. circlePath.push(rotated);
  11387. }
  11388. circlePaths.push(circlePath);
  11389. }
  11390. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11391. return tube;
  11392. };
  11393. // Tools
  11394. Mesh.MinMax = function (meshes) {
  11395. var minVector = null;
  11396. var maxVector = null;
  11397. for (var i in meshes) {
  11398. var mesh = meshes[i];
  11399. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11400. if (!minVector) {
  11401. minVector = boundingBox.minimumWorld;
  11402. maxVector = boundingBox.maximumWorld;
  11403. continue;
  11404. }
  11405. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11406. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11407. }
  11408. return {
  11409. min: minVector,
  11410. max: maxVector
  11411. };
  11412. };
  11413. Mesh.Center = function (meshesOrMinMaxVector) {
  11414. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11415. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11416. };
  11417. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11418. if (disposeSource === void 0) { disposeSource = true; }
  11419. var source = meshes[0];
  11420. var material = source.material;
  11421. var scene = source.getScene();
  11422. if (!allow32BitsIndices) {
  11423. var totalVertices = 0;
  11424. for (var index = 0; index < meshes.length; index++) {
  11425. totalVertices += meshes[index].getTotalVertices();
  11426. if (totalVertices > 65536) {
  11427. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11428. return null;
  11429. }
  11430. }
  11431. }
  11432. // Merge
  11433. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11434. vertexData.transform(source.getWorldMatrix());
  11435. for (index = 1; index < meshes.length; index++) {
  11436. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11437. otherVertexData.transform(meshes[index].getWorldMatrix());
  11438. vertexData.merge(otherVertexData);
  11439. }
  11440. var newMesh = new Mesh(source.name + "_merged", scene);
  11441. vertexData.applyToMesh(newMesh);
  11442. // Setting properties
  11443. newMesh.material = material;
  11444. newMesh.checkCollisions = source.checkCollisions;
  11445. // Cleaning
  11446. if (disposeSource) {
  11447. for (index = 0; index < meshes.length; index++) {
  11448. meshes[index].dispose();
  11449. }
  11450. }
  11451. return newMesh;
  11452. };
  11453. // Consts
  11454. Mesh._FRONTSIDE = 0;
  11455. Mesh._BACKSIDE = 1;
  11456. Mesh._DOUBLESIDE = 2;
  11457. Mesh._DEFAULTSIDE = 0;
  11458. return Mesh;
  11459. })(BABYLON.AbstractMesh);
  11460. BABYLON.Mesh = Mesh;
  11461. })(BABYLON || (BABYLON = {}));
  11462. //# sourceMappingURL=babylon.mesh.js.map
  11463. var BABYLON;
  11464. (function (BABYLON) {
  11465. var GroundMesh = (function (_super) {
  11466. __extends(GroundMesh, _super);
  11467. function GroundMesh(name, scene) {
  11468. _super.call(this, name, scene);
  11469. this.generateOctree = false;
  11470. this._worldInverse = new BABYLON.Matrix();
  11471. }
  11472. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11473. get: function () {
  11474. return this._subdivisions;
  11475. },
  11476. enumerable: true,
  11477. configurable: true
  11478. });
  11479. GroundMesh.prototype.optimize = function (chunksCount) {
  11480. this.subdivide(this._subdivisions);
  11481. this.createOrUpdateSubmeshesOctree(32);
  11482. };
  11483. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11484. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11485. this.getWorldMatrix().invertToRef(this._worldInverse);
  11486. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11487. var pickInfo = this.intersects(ray);
  11488. if (pickInfo.hit) {
  11489. return pickInfo.pickedPoint.y;
  11490. }
  11491. return 0;
  11492. };
  11493. return GroundMesh;
  11494. })(BABYLON.Mesh);
  11495. BABYLON.GroundMesh = GroundMesh;
  11496. })(BABYLON || (BABYLON = {}));
  11497. //# sourceMappingURL=babylon.groundMesh.js.map
  11498. var BABYLON;
  11499. (function (BABYLON) {
  11500. /**
  11501. * Creates an instance based on a source mesh.
  11502. */
  11503. var InstancedMesh = (function (_super) {
  11504. __extends(InstancedMesh, _super);
  11505. function InstancedMesh(name, source) {
  11506. _super.call(this, name, source.getScene());
  11507. source.instances.push(this);
  11508. this._sourceMesh = source;
  11509. this.position.copyFrom(source.position);
  11510. this.rotation.copyFrom(source.rotation);
  11511. this.scaling.copyFrom(source.scaling);
  11512. if (source.rotationQuaternion) {
  11513. this.rotationQuaternion = source.rotationQuaternion.clone();
  11514. }
  11515. this.infiniteDistance = source.infiniteDistance;
  11516. this.setPivotMatrix(source.getPivotMatrix());
  11517. this.refreshBoundingInfo();
  11518. this._syncSubMeshes();
  11519. }
  11520. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11521. // Methods
  11522. get: function () {
  11523. return this._sourceMesh.receiveShadows;
  11524. },
  11525. enumerable: true,
  11526. configurable: true
  11527. });
  11528. Object.defineProperty(InstancedMesh.prototype, "material", {
  11529. get: function () {
  11530. return this._sourceMesh.material;
  11531. },
  11532. enumerable: true,
  11533. configurable: true
  11534. });
  11535. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11536. get: function () {
  11537. return this._sourceMesh.visibility;
  11538. },
  11539. enumerable: true,
  11540. configurable: true
  11541. });
  11542. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11543. get: function () {
  11544. return this._sourceMesh.skeleton;
  11545. },
  11546. enumerable: true,
  11547. configurable: true
  11548. });
  11549. InstancedMesh.prototype.getTotalVertices = function () {
  11550. return this._sourceMesh.getTotalVertices();
  11551. };
  11552. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11553. get: function () {
  11554. return this._sourceMesh;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. InstancedMesh.prototype.getVerticesData = function (kind) {
  11560. return this._sourceMesh.getVerticesData(kind);
  11561. };
  11562. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11563. return this._sourceMesh.isVerticesDataPresent(kind);
  11564. };
  11565. InstancedMesh.prototype.getIndices = function () {
  11566. return this._sourceMesh.getIndices();
  11567. };
  11568. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11569. get: function () {
  11570. return this._sourceMesh._positions;
  11571. },
  11572. enumerable: true,
  11573. configurable: true
  11574. });
  11575. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11576. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11577. if (data) {
  11578. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11579. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11580. }
  11581. this._updateBoundingInfo();
  11582. };
  11583. InstancedMesh.prototype._preActivate = function () {
  11584. if (this._currentLOD) {
  11585. this._currentLOD._preActivate();
  11586. }
  11587. };
  11588. InstancedMesh.prototype._activate = function (renderId) {
  11589. if (this._currentLOD) {
  11590. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11591. }
  11592. };
  11593. InstancedMesh.prototype.getLOD = function (camera) {
  11594. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11595. if (this._currentLOD === this.sourceMesh) {
  11596. return this;
  11597. }
  11598. return this._currentLOD;
  11599. };
  11600. InstancedMesh.prototype._syncSubMeshes = function () {
  11601. this.releaseSubMeshes();
  11602. if (this._sourceMesh.subMeshes) {
  11603. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11604. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11605. }
  11606. }
  11607. };
  11608. InstancedMesh.prototype._generatePointsArray = function () {
  11609. return this._sourceMesh._generatePointsArray();
  11610. };
  11611. // Clone
  11612. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11613. var result = this._sourceMesh.createInstance(name);
  11614. // Deep copy
  11615. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11616. // Bounding info
  11617. this.refreshBoundingInfo();
  11618. // Parent
  11619. if (newParent) {
  11620. result.parent = newParent;
  11621. }
  11622. if (!doNotCloneChildren) {
  11623. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11624. var mesh = this.getScene().meshes[index];
  11625. if (mesh.parent === this) {
  11626. mesh.clone(mesh.name, result);
  11627. }
  11628. }
  11629. }
  11630. result.computeWorldMatrix(true);
  11631. return result;
  11632. };
  11633. // Dispoe
  11634. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11635. // Remove from mesh
  11636. var index = this._sourceMesh.instances.indexOf(this);
  11637. this._sourceMesh.instances.splice(index, 1);
  11638. _super.prototype.dispose.call(this, doNotRecurse);
  11639. };
  11640. return InstancedMesh;
  11641. })(BABYLON.AbstractMesh);
  11642. BABYLON.InstancedMesh = InstancedMesh;
  11643. })(BABYLON || (BABYLON = {}));
  11644. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11645. (function (BABYLON) {
  11646. var SubMesh = (function () {
  11647. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11648. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11649. this.materialIndex = materialIndex;
  11650. this.verticesStart = verticesStart;
  11651. this.verticesCount = verticesCount;
  11652. this.indexStart = indexStart;
  11653. this.indexCount = indexCount;
  11654. this._renderId = 0;
  11655. this._mesh = mesh;
  11656. this._renderingMesh = renderingMesh || mesh;
  11657. mesh.subMeshes.push(this);
  11658. this._id = mesh.subMeshes.length - 1;
  11659. if (createBoundingBox) {
  11660. this.refreshBoundingInfo();
  11661. }
  11662. }
  11663. SubMesh.prototype.getBoundingInfo = function () {
  11664. return this._boundingInfo;
  11665. };
  11666. SubMesh.prototype.getMesh = function () {
  11667. return this._mesh;
  11668. };
  11669. SubMesh.prototype.getRenderingMesh = function () {
  11670. return this._renderingMesh;
  11671. };
  11672. SubMesh.prototype.getMaterial = function () {
  11673. var rootMaterial = this._renderingMesh.material;
  11674. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11675. var multiMaterial = rootMaterial;
  11676. return multiMaterial.getSubMaterial(this.materialIndex);
  11677. }
  11678. if (!rootMaterial) {
  11679. return this._mesh.getScene().defaultMaterial;
  11680. }
  11681. return rootMaterial;
  11682. };
  11683. // Methods
  11684. SubMesh.prototype.refreshBoundingInfo = function () {
  11685. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11686. if (!data) {
  11687. this._boundingInfo = this._mesh._boundingInfo;
  11688. return;
  11689. }
  11690. var indices = this._renderingMesh.getIndices();
  11691. var extend;
  11692. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11693. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11694. }
  11695. else {
  11696. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11697. }
  11698. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11699. };
  11700. SubMesh.prototype._checkCollision = function (collider) {
  11701. return this._boundingInfo._checkCollision(collider);
  11702. };
  11703. SubMesh.prototype.updateBoundingInfo = function (world) {
  11704. if (!this._boundingInfo) {
  11705. this.refreshBoundingInfo();
  11706. }
  11707. this._boundingInfo._update(world);
  11708. };
  11709. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11710. return this._boundingInfo.isInFrustum(frustumPlanes);
  11711. };
  11712. SubMesh.prototype.render = function () {
  11713. this._renderingMesh.render(this);
  11714. };
  11715. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11716. if (!this._linesIndexBuffer) {
  11717. var linesIndices = [];
  11718. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11719. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11720. }
  11721. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11722. this.linesIndexCount = linesIndices.length;
  11723. }
  11724. return this._linesIndexBuffer;
  11725. };
  11726. SubMesh.prototype.canIntersects = function (ray) {
  11727. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11728. };
  11729. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11730. var intersectInfo = null;
  11731. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11732. var p0 = positions[indices[index]];
  11733. var p1 = positions[indices[index + 1]];
  11734. var p2 = positions[indices[index + 2]];
  11735. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11736. if (currentIntersectInfo) {
  11737. if (currentIntersectInfo.distance < 0) {
  11738. continue;
  11739. }
  11740. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11741. intersectInfo = currentIntersectInfo;
  11742. intersectInfo.faceId = index / 3;
  11743. if (fastCheck) {
  11744. break;
  11745. }
  11746. }
  11747. }
  11748. }
  11749. return intersectInfo;
  11750. };
  11751. // Clone
  11752. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11753. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11754. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11755. return result;
  11756. };
  11757. // Dispose
  11758. SubMesh.prototype.dispose = function () {
  11759. if (this._linesIndexBuffer) {
  11760. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11761. this._linesIndexBuffer = null;
  11762. }
  11763. // Remove from mesh
  11764. var index = this._mesh.subMeshes.indexOf(this);
  11765. this._mesh.subMeshes.splice(index, 1);
  11766. };
  11767. // Statics
  11768. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11769. var minVertexIndex = Number.MAX_VALUE;
  11770. var maxVertexIndex = -Number.MAX_VALUE;
  11771. renderingMesh = renderingMesh || mesh;
  11772. var indices = renderingMesh.getIndices();
  11773. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11774. var vertexIndex = indices[index];
  11775. if (vertexIndex < minVertexIndex)
  11776. minVertexIndex = vertexIndex;
  11777. if (vertexIndex > maxVertexIndex)
  11778. maxVertexIndex = vertexIndex;
  11779. }
  11780. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11781. };
  11782. return SubMesh;
  11783. })();
  11784. BABYLON.SubMesh = SubMesh;
  11785. })(BABYLON || (BABYLON = {}));
  11786. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11787. (function (BABYLON) {
  11788. var BaseTexture = (function () {
  11789. function BaseTexture(scene) {
  11790. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11791. this.hasAlpha = false;
  11792. this.getAlphaFromRGB = false;
  11793. this.level = 1;
  11794. this.isCube = false;
  11795. this.isRenderTarget = false;
  11796. this.animations = new Array();
  11797. this.coordinatesIndex = 0;
  11798. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11799. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11800. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11801. this.anisotropicFilteringLevel = 4;
  11802. this._scene = scene;
  11803. this._scene.textures.push(this);
  11804. }
  11805. BaseTexture.prototype.getScene = function () {
  11806. return this._scene;
  11807. };
  11808. BaseTexture.prototype.getTextureMatrix = function () {
  11809. return null;
  11810. };
  11811. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11812. return null;
  11813. };
  11814. BaseTexture.prototype.getInternalTexture = function () {
  11815. return this._texture;
  11816. };
  11817. BaseTexture.prototype.isReady = function () {
  11818. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11819. return true;
  11820. }
  11821. if (this._texture) {
  11822. return this._texture.isReady;
  11823. }
  11824. return false;
  11825. };
  11826. BaseTexture.prototype.getSize = function () {
  11827. if (this._texture._width) {
  11828. return { width: this._texture._width, height: this._texture._height };
  11829. }
  11830. if (this._texture._size) {
  11831. return { width: this._texture._size, height: this._texture._size };
  11832. }
  11833. return { width: 0, height: 0 };
  11834. };
  11835. BaseTexture.prototype.getBaseSize = function () {
  11836. if (!this.isReady())
  11837. return { width: 0, height: 0 };
  11838. if (this._texture._size) {
  11839. return { width: this._texture._size, height: this._texture._size };
  11840. }
  11841. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11842. };
  11843. BaseTexture.prototype.scale = function (ratio) {
  11844. };
  11845. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11846. get: function () {
  11847. return false;
  11848. },
  11849. enumerable: true,
  11850. configurable: true
  11851. });
  11852. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11853. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11854. for (var index = 0; index < texturesCache.length; index++) {
  11855. var texturesCacheEntry = texturesCache[index];
  11856. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11857. texturesCache.splice(index, 1);
  11858. return;
  11859. }
  11860. }
  11861. };
  11862. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11863. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11864. for (var index = 0; index < texturesCache.length; index++) {
  11865. var texturesCacheEntry = texturesCache[index];
  11866. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11867. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11868. texturesCacheEntry.references++;
  11869. return texturesCacheEntry;
  11870. }
  11871. }
  11872. }
  11873. return null;
  11874. };
  11875. BaseTexture.prototype.delayLoad = function () {
  11876. };
  11877. BaseTexture.prototype.releaseInternalTexture = function () {
  11878. if (!this._texture) {
  11879. return;
  11880. }
  11881. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11882. this._texture.references--;
  11883. // Final reference ?
  11884. if (this._texture.references === 0) {
  11885. var index = texturesCache.indexOf(this._texture);
  11886. texturesCache.splice(index, 1);
  11887. this._scene.getEngine()._releaseTexture(this._texture);
  11888. delete this._texture;
  11889. }
  11890. };
  11891. BaseTexture.prototype.clone = function () {
  11892. return null;
  11893. };
  11894. BaseTexture.prototype.dispose = function () {
  11895. // Remove from scene
  11896. var index = this._scene.textures.indexOf(this);
  11897. if (index >= 0) {
  11898. this._scene.textures.splice(index, 1);
  11899. }
  11900. if (this._texture === undefined) {
  11901. return;
  11902. }
  11903. this.releaseInternalTexture();
  11904. // Callback
  11905. if (this.onDispose) {
  11906. this.onDispose();
  11907. }
  11908. };
  11909. return BaseTexture;
  11910. })();
  11911. BABYLON.BaseTexture = BaseTexture;
  11912. })(BABYLON || (BABYLON = {}));
  11913. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11914. (function (BABYLON) {
  11915. var RenderingGroup = (function () {
  11916. function RenderingGroup(index, scene) {
  11917. this.index = index;
  11918. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11919. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11920. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11921. this._scene = scene;
  11922. }
  11923. RenderingGroup.prototype.render = function (customRenderFunction) {
  11924. if (customRenderFunction) {
  11925. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11926. return true;
  11927. }
  11928. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11929. return false;
  11930. }
  11931. var engine = this._scene.getEngine();
  11932. // Opaque
  11933. var subIndex;
  11934. var submesh;
  11935. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11936. submesh = this._opaqueSubMeshes.data[subIndex];
  11937. submesh.render();
  11938. }
  11939. // Alpha test
  11940. engine.setAlphaTesting(true);
  11941. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11942. submesh = this._alphaTestSubMeshes.data[subIndex];
  11943. submesh.render();
  11944. }
  11945. engine.setAlphaTesting(false);
  11946. // Transparent
  11947. if (this._transparentSubMeshes.length) {
  11948. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11949. submesh = this._transparentSubMeshes.data[subIndex];
  11950. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11951. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11952. }
  11953. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11954. sortedArray.sort(function (a, b) {
  11955. // Alpha index first
  11956. if (a._alphaIndex > b._alphaIndex) {
  11957. return 1;
  11958. }
  11959. if (a._alphaIndex < b._alphaIndex) {
  11960. return -1;
  11961. }
  11962. // Then distance to camera
  11963. if (a._distanceToCamera < b._distanceToCamera) {
  11964. return 1;
  11965. }
  11966. if (a._distanceToCamera > b._distanceToCamera) {
  11967. return -1;
  11968. }
  11969. return 0;
  11970. });
  11971. // Rendering
  11972. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11973. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11974. submesh = sortedArray[subIndex];
  11975. submesh.render();
  11976. }
  11977. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11978. }
  11979. return true;
  11980. };
  11981. RenderingGroup.prototype.prepare = function () {
  11982. this._opaqueSubMeshes.reset();
  11983. this._transparentSubMeshes.reset();
  11984. this._alphaTestSubMeshes.reset();
  11985. };
  11986. RenderingGroup.prototype.dispatch = function (subMesh) {
  11987. var material = subMesh.getMaterial();
  11988. var mesh = subMesh.getMesh();
  11989. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11990. this._transparentSubMeshes.push(subMesh);
  11991. }
  11992. else if (material.needAlphaTesting()) {
  11993. this._alphaTestSubMeshes.push(subMesh);
  11994. }
  11995. else {
  11996. this._opaqueSubMeshes.push(subMesh); // Opaque
  11997. }
  11998. };
  11999. return RenderingGroup;
  12000. })();
  12001. BABYLON.RenderingGroup = RenderingGroup;
  12002. })(BABYLON || (BABYLON = {}));
  12003. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12004. (function (BABYLON) {
  12005. var RenderingManager = (function () {
  12006. function RenderingManager(scene) {
  12007. this._renderingGroups = new Array();
  12008. this._scene = scene;
  12009. }
  12010. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12011. if (this._scene._activeParticleSystems.length === 0) {
  12012. return;
  12013. }
  12014. // Particles
  12015. var beforeParticlesDate = BABYLON.Tools.Now;
  12016. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12017. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12018. if (particleSystem.renderingGroupId !== index) {
  12019. continue;
  12020. }
  12021. this._clearDepthBuffer();
  12022. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12023. this._scene._activeParticles += particleSystem.render();
  12024. }
  12025. }
  12026. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12027. };
  12028. RenderingManager.prototype._renderSprites = function (index) {
  12029. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12030. return;
  12031. }
  12032. // Sprites
  12033. var beforeSpritessDate = BABYLON.Tools.Now;
  12034. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12035. var spriteManager = this._scene.spriteManagers[id];
  12036. if (spriteManager.renderingGroupId === index) {
  12037. this._clearDepthBuffer();
  12038. spriteManager.render();
  12039. }
  12040. }
  12041. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12042. };
  12043. RenderingManager.prototype._clearDepthBuffer = function () {
  12044. if (this._depthBufferAlreadyCleaned) {
  12045. return;
  12046. }
  12047. this._scene.getEngine().clear(0, false, true);
  12048. this._depthBufferAlreadyCleaned = true;
  12049. };
  12050. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12051. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12052. this._depthBufferAlreadyCleaned = false;
  12053. var renderingGroup = this._renderingGroups[index];
  12054. var needToStepBack = false;
  12055. if (renderingGroup) {
  12056. this._clearDepthBuffer();
  12057. if (!renderingGroup.render(customRenderFunction)) {
  12058. this._renderingGroups.splice(index, 1);
  12059. needToStepBack = true;
  12060. }
  12061. }
  12062. if (renderSprites) {
  12063. this._renderSprites(index);
  12064. }
  12065. if (renderParticles) {
  12066. this._renderParticles(index, activeMeshes);
  12067. }
  12068. if (needToStepBack) {
  12069. index--;
  12070. }
  12071. }
  12072. };
  12073. RenderingManager.prototype.reset = function () {
  12074. for (var index in this._renderingGroups) {
  12075. var renderingGroup = this._renderingGroups[index];
  12076. renderingGroup.prepare();
  12077. }
  12078. };
  12079. RenderingManager.prototype.dispatch = function (subMesh) {
  12080. var mesh = subMesh.getMesh();
  12081. var renderingGroupId = mesh.renderingGroupId || 0;
  12082. if (!this._renderingGroups[renderingGroupId]) {
  12083. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12084. }
  12085. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12086. };
  12087. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12088. return RenderingManager;
  12089. })();
  12090. BABYLON.RenderingManager = RenderingManager;
  12091. })(BABYLON || (BABYLON = {}));
  12092. //# sourceMappingURL=babylon.renderingManager.js.map
  12093. var BABYLON;
  12094. (function (BABYLON) {
  12095. var Texture = (function (_super) {
  12096. __extends(Texture, _super);
  12097. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12098. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12099. if (onLoad === void 0) { onLoad = null; }
  12100. if (onError === void 0) { onError = null; }
  12101. if (buffer === void 0) { buffer = null; }
  12102. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12103. _super.call(this, scene);
  12104. this.uOffset = 0;
  12105. this.vOffset = 0;
  12106. this.uScale = 1.0;
  12107. this.vScale = 1.0;
  12108. this.uAng = 0;
  12109. this.vAng = 0;
  12110. this.wAng = 0;
  12111. this.name = url;
  12112. this.url = url;
  12113. this._noMipmap = noMipmap;
  12114. this._invertY = invertY;
  12115. this._samplingMode = samplingMode;
  12116. this._buffer = buffer;
  12117. this._deleteBuffer = deleteBuffer;
  12118. if (!url) {
  12119. return;
  12120. }
  12121. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12122. if (!this._texture) {
  12123. if (!scene.useDelayedTextureLoading) {
  12124. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12125. if (deleteBuffer) {
  12126. delete this._buffer;
  12127. }
  12128. }
  12129. else {
  12130. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12131. }
  12132. }
  12133. }
  12134. Texture.prototype.delayLoad = function () {
  12135. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12136. return;
  12137. }
  12138. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12139. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12140. if (!this._texture) {
  12141. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12142. if (this._deleteBuffer) {
  12143. delete this._buffer;
  12144. }
  12145. }
  12146. };
  12147. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12148. x -= this.uOffset + 0.5;
  12149. y -= this.vOffset + 0.5;
  12150. z -= 0.5;
  12151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12152. t.x *= this.uScale;
  12153. t.y *= this.vScale;
  12154. t.x += 0.5;
  12155. t.y += 0.5;
  12156. t.z += 0.5;
  12157. };
  12158. Texture.prototype.getTextureMatrix = function () {
  12159. 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) {
  12160. return this._cachedTextureMatrix;
  12161. }
  12162. this._cachedUOffset = this.uOffset;
  12163. this._cachedVOffset = this.vOffset;
  12164. this._cachedUScale = this.uScale;
  12165. this._cachedVScale = this.vScale;
  12166. this._cachedUAng = this.uAng;
  12167. this._cachedVAng = this.vAng;
  12168. this._cachedWAng = this.wAng;
  12169. if (!this._cachedTextureMatrix) {
  12170. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12171. this._rowGenerationMatrix = new BABYLON.Matrix();
  12172. this._t0 = BABYLON.Vector3.Zero();
  12173. this._t1 = BABYLON.Vector3.Zero();
  12174. this._t2 = BABYLON.Vector3.Zero();
  12175. }
  12176. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12177. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12178. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12179. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12180. this._t1.subtractInPlace(this._t0);
  12181. this._t2.subtractInPlace(this._t0);
  12182. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12183. this._cachedTextureMatrix.m[0] = this._t1.x;
  12184. this._cachedTextureMatrix.m[1] = this._t1.y;
  12185. this._cachedTextureMatrix.m[2] = this._t1.z;
  12186. this._cachedTextureMatrix.m[4] = this._t2.x;
  12187. this._cachedTextureMatrix.m[5] = this._t2.y;
  12188. this._cachedTextureMatrix.m[6] = this._t2.z;
  12189. this._cachedTextureMatrix.m[8] = this._t0.x;
  12190. this._cachedTextureMatrix.m[9] = this._t0.y;
  12191. this._cachedTextureMatrix.m[10] = this._t0.z;
  12192. return this._cachedTextureMatrix;
  12193. };
  12194. Texture.prototype.getReflectionTextureMatrix = function () {
  12195. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12196. return this._cachedTextureMatrix;
  12197. }
  12198. if (!this._cachedTextureMatrix) {
  12199. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12200. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12201. }
  12202. this._cachedCoordinatesMode = this.coordinatesMode;
  12203. switch (this.coordinatesMode) {
  12204. case BABYLON.Texture.SPHERICAL_MODE:
  12205. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12206. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12207. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12208. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12209. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12210. break;
  12211. case BABYLON.Texture.PLANAR_MODE:
  12212. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12213. this._cachedTextureMatrix[0] = this.uScale;
  12214. this._cachedTextureMatrix[5] = this.vScale;
  12215. this._cachedTextureMatrix[12] = this.uOffset;
  12216. this._cachedTextureMatrix[13] = this.vOffset;
  12217. break;
  12218. case BABYLON.Texture.PROJECTION_MODE:
  12219. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12220. this._projectionModeMatrix.m[0] = 0.5;
  12221. this._projectionModeMatrix.m[5] = -0.5;
  12222. this._projectionModeMatrix.m[10] = 0.0;
  12223. this._projectionModeMatrix.m[12] = 0.5;
  12224. this._projectionModeMatrix.m[13] = 0.5;
  12225. this._projectionModeMatrix.m[14] = 1.0;
  12226. this._projectionModeMatrix.m[15] = 1.0;
  12227. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12228. break;
  12229. default:
  12230. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12231. break;
  12232. }
  12233. return this._cachedTextureMatrix;
  12234. };
  12235. Texture.prototype.clone = function () {
  12236. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12237. // Base texture
  12238. newTexture.hasAlpha = this.hasAlpha;
  12239. newTexture.level = this.level;
  12240. newTexture.wrapU = this.wrapU;
  12241. newTexture.wrapV = this.wrapV;
  12242. newTexture.coordinatesIndex = this.coordinatesIndex;
  12243. newTexture.coordinatesMode = this.coordinatesMode;
  12244. // Texture
  12245. newTexture.uOffset = this.uOffset;
  12246. newTexture.vOffset = this.vOffset;
  12247. newTexture.uScale = this.uScale;
  12248. newTexture.vScale = this.vScale;
  12249. newTexture.uAng = this.uAng;
  12250. newTexture.vAng = this.vAng;
  12251. newTexture.wAng = this.wAng;
  12252. return newTexture;
  12253. };
  12254. // Statics
  12255. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12256. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12257. if (onLoad === void 0) { onLoad = null; }
  12258. if (onError === void 0) { onError = null; }
  12259. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12260. };
  12261. // Constants
  12262. Texture.NEAREST_SAMPLINGMODE = 1;
  12263. Texture.BILINEAR_SAMPLINGMODE = 2;
  12264. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12265. Texture.EXPLICIT_MODE = 0;
  12266. Texture.SPHERICAL_MODE = 1;
  12267. Texture.PLANAR_MODE = 2;
  12268. Texture.CUBIC_MODE = 3;
  12269. Texture.PROJECTION_MODE = 4;
  12270. Texture.SKYBOX_MODE = 5;
  12271. Texture.CLAMP_ADDRESSMODE = 0;
  12272. Texture.WRAP_ADDRESSMODE = 1;
  12273. Texture.MIRROR_ADDRESSMODE = 2;
  12274. return Texture;
  12275. })(BABYLON.BaseTexture);
  12276. BABYLON.Texture = Texture;
  12277. })(BABYLON || (BABYLON = {}));
  12278. //# sourceMappingURL=babylon.texture.js.map
  12279. var BABYLON;
  12280. (function (BABYLON) {
  12281. var CubeTexture = (function (_super) {
  12282. __extends(CubeTexture, _super);
  12283. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12284. _super.call(this, scene);
  12285. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12286. this.name = rootUrl;
  12287. this.url = rootUrl;
  12288. this._noMipmap = noMipmap;
  12289. this.hasAlpha = false;
  12290. this._texture = this._getFromCache(rootUrl, noMipmap);
  12291. if (!extensions) {
  12292. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12293. }
  12294. this._extensions = extensions;
  12295. if (!this._texture) {
  12296. if (!scene.useDelayedTextureLoading) {
  12297. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12298. }
  12299. else {
  12300. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12301. }
  12302. }
  12303. this.isCube = true;
  12304. this._textureMatrix = BABYLON.Matrix.Identity();
  12305. }
  12306. CubeTexture.prototype.clone = function () {
  12307. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12308. // Base texture
  12309. newTexture.level = this.level;
  12310. newTexture.wrapU = this.wrapU;
  12311. newTexture.wrapV = this.wrapV;
  12312. newTexture.coordinatesIndex = this.coordinatesIndex;
  12313. newTexture.coordinatesMode = this.coordinatesMode;
  12314. return newTexture;
  12315. };
  12316. // Methods
  12317. CubeTexture.prototype.delayLoad = function () {
  12318. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12319. return;
  12320. }
  12321. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12322. this._texture = this._getFromCache(this.url, this._noMipmap);
  12323. if (!this._texture) {
  12324. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12325. }
  12326. };
  12327. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12328. return this._textureMatrix;
  12329. };
  12330. return CubeTexture;
  12331. })(BABYLON.BaseTexture);
  12332. BABYLON.CubeTexture = CubeTexture;
  12333. })(BABYLON || (BABYLON = {}));
  12334. //# sourceMappingURL=babylon.cubeTexture.js.map
  12335. var BABYLON;
  12336. (function (BABYLON) {
  12337. var RenderTargetTexture = (function (_super) {
  12338. __extends(RenderTargetTexture, _super);
  12339. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12340. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12341. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12342. _super.call(this, null, scene, !generateMipMaps);
  12343. this.renderList = new Array();
  12344. this.renderParticles = true;
  12345. this.renderSprites = false;
  12346. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12347. this._currentRefreshId = -1;
  12348. this._refreshRate = 1;
  12349. this.name = name;
  12350. this.isRenderTarget = true;
  12351. this._size = size;
  12352. this._generateMipMaps = generateMipMaps;
  12353. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12354. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12355. // Rendering groups
  12356. this._renderingManager = new BABYLON.RenderingManager(scene);
  12357. }
  12358. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12359. this._currentRefreshId = -1;
  12360. };
  12361. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12362. get: function () {
  12363. return this._refreshRate;
  12364. },
  12365. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12366. set: function (value) {
  12367. this._refreshRate = value;
  12368. this.resetRefreshCounter();
  12369. },
  12370. enumerable: true,
  12371. configurable: true
  12372. });
  12373. RenderTargetTexture.prototype._shouldRender = function () {
  12374. if (this._currentRefreshId === -1) {
  12375. this._currentRefreshId = 1;
  12376. return true;
  12377. }
  12378. if (this.refreshRate === this._currentRefreshId) {
  12379. this._currentRefreshId = 1;
  12380. return true;
  12381. }
  12382. this._currentRefreshId++;
  12383. return false;
  12384. };
  12385. RenderTargetTexture.prototype.isReady = function () {
  12386. if (!this.getScene().renderTargetsEnabled) {
  12387. return false;
  12388. }
  12389. return _super.prototype.isReady.call(this);
  12390. };
  12391. RenderTargetTexture.prototype.getRenderSize = function () {
  12392. return this._size;
  12393. };
  12394. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12395. get: function () {
  12396. return true;
  12397. },
  12398. enumerable: true,
  12399. configurable: true
  12400. });
  12401. RenderTargetTexture.prototype.scale = function (ratio) {
  12402. var newSize = this._size * ratio;
  12403. this.resize(newSize, this._generateMipMaps);
  12404. };
  12405. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12406. this.releaseInternalTexture();
  12407. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12408. };
  12409. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12410. var scene = this.getScene();
  12411. var engine = scene.getEngine();
  12412. if (this._waitingRenderList) {
  12413. this.renderList = [];
  12414. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12415. var id = this._waitingRenderList[index];
  12416. this.renderList.push(scene.getMeshByID(id));
  12417. }
  12418. delete this._waitingRenderList;
  12419. }
  12420. if (this.renderList && this.renderList.length === 0) {
  12421. return;
  12422. }
  12423. // Bind
  12424. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12425. engine.bindFramebuffer(this._texture);
  12426. }
  12427. this._renderingManager.reset();
  12428. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12429. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12430. var mesh = currentRenderList[meshIndex];
  12431. if (mesh) {
  12432. if (!mesh.isReady()) {
  12433. // Reset _currentRefreshId
  12434. this.resetRefreshCounter();
  12435. continue;
  12436. }
  12437. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12438. mesh._activate(scene.getRenderId());
  12439. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12440. var subMesh = mesh.subMeshes[subIndex];
  12441. scene._activeVertices += subMesh.indexCount;
  12442. this._renderingManager.dispatch(subMesh);
  12443. }
  12444. }
  12445. }
  12446. }
  12447. if (this.onBeforeRender) {
  12448. this.onBeforeRender();
  12449. }
  12450. // Clear
  12451. if (this.onClear) {
  12452. this.onClear(engine);
  12453. }
  12454. else {
  12455. engine.clear(scene.clearColor, true, true);
  12456. }
  12457. if (!this._doNotChangeAspectRatio) {
  12458. scene.updateTransformMatrix(true);
  12459. }
  12460. // Render
  12461. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12462. if (useCameraPostProcess) {
  12463. scene.postProcessManager._finalizeFrame(false, this._texture);
  12464. }
  12465. if (!this._doNotChangeAspectRatio) {
  12466. scene.updateTransformMatrix(true);
  12467. }
  12468. if (this.onAfterRender) {
  12469. this.onAfterRender();
  12470. }
  12471. // Dump ?
  12472. if (dumpForDebug) {
  12473. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12474. }
  12475. // Unbind
  12476. engine.unBindFramebuffer(this._texture);
  12477. if (this.onAfterUnbind) {
  12478. this.onAfterUnbind();
  12479. }
  12480. };
  12481. RenderTargetTexture.prototype.clone = function () {
  12482. var textureSize = this.getSize();
  12483. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12484. // Base texture
  12485. newTexture.hasAlpha = this.hasAlpha;
  12486. newTexture.level = this.level;
  12487. // RenderTarget Texture
  12488. newTexture.coordinatesMode = this.coordinatesMode;
  12489. newTexture.renderList = this.renderList.slice(0);
  12490. return newTexture;
  12491. };
  12492. return RenderTargetTexture;
  12493. })(BABYLON.Texture);
  12494. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12495. })(BABYLON || (BABYLON = {}));
  12496. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12497. var BABYLON;
  12498. (function (BABYLON) {
  12499. var ProceduralTexture = (function (_super) {
  12500. __extends(ProceduralTexture, _super);
  12501. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12502. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12503. _super.call(this, null, scene, !generateMipMaps);
  12504. this._currentRefreshId = -1;
  12505. this._refreshRate = 1;
  12506. this._vertexDeclaration = [2];
  12507. this._vertexStrideSize = 2 * 4;
  12508. this._uniforms = new Array();
  12509. this._samplers = new Array();
  12510. this._textures = new Array();
  12511. this._floats = new Array();
  12512. this._floatsArrays = {};
  12513. this._colors3 = new Array();
  12514. this._colors4 = new Array();
  12515. this._vectors2 = new Array();
  12516. this._vectors3 = new Array();
  12517. this._matrices = new Array();
  12518. this._fallbackTextureUsed = false;
  12519. scene._proceduralTextures.push(this);
  12520. this.name = name;
  12521. this.isRenderTarget = true;
  12522. this._size = size;
  12523. this._generateMipMaps = generateMipMaps;
  12524. this.setFragment(fragment);
  12525. this._fallbackTexture = fallbackTexture;
  12526. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12527. // VBO
  12528. var vertices = [];
  12529. vertices.push(1, 1);
  12530. vertices.push(-1, 1);
  12531. vertices.push(-1, -1);
  12532. vertices.push(1, -1);
  12533. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12534. // Indices
  12535. var indices = [];
  12536. indices.push(0);
  12537. indices.push(1);
  12538. indices.push(2);
  12539. indices.push(0);
  12540. indices.push(2);
  12541. indices.push(3);
  12542. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12543. }
  12544. ProceduralTexture.prototype.reset = function () {
  12545. if (this._effect === undefined) {
  12546. return;
  12547. }
  12548. var engine = this.getScene().getEngine();
  12549. engine._releaseEffect(this._effect);
  12550. };
  12551. ProceduralTexture.prototype.isReady = function () {
  12552. var _this = this;
  12553. var engine = this.getScene().getEngine();
  12554. var shaders;
  12555. if (!this._fragment) {
  12556. return false;
  12557. }
  12558. if (this._fallbackTextureUsed) {
  12559. return true;
  12560. }
  12561. if (this._fragment.fragmentElement !== undefined) {
  12562. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12563. }
  12564. else {
  12565. shaders = { vertex: "procedural", fragment: this._fragment };
  12566. }
  12567. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12568. _this.releaseInternalTexture();
  12569. if (_this._fallbackTexture) {
  12570. _this._texture = _this._fallbackTexture._texture;
  12571. _this._texture.references++;
  12572. }
  12573. _this._fallbackTextureUsed = true;
  12574. });
  12575. return this._effect.isReady();
  12576. };
  12577. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12578. this._currentRefreshId = -1;
  12579. };
  12580. ProceduralTexture.prototype.setFragment = function (fragment) {
  12581. this._fragment = fragment;
  12582. };
  12583. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12584. get: function () {
  12585. return this._refreshRate;
  12586. },
  12587. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12588. set: function (value) {
  12589. this._refreshRate = value;
  12590. this.resetRefreshCounter();
  12591. },
  12592. enumerable: true,
  12593. configurable: true
  12594. });
  12595. ProceduralTexture.prototype._shouldRender = function () {
  12596. if (!this.isReady() || !this._texture) {
  12597. return false;
  12598. }
  12599. if (this._fallbackTextureUsed) {
  12600. return false;
  12601. }
  12602. if (this._currentRefreshId === -1) {
  12603. this._currentRefreshId = 1;
  12604. return true;
  12605. }
  12606. if (this.refreshRate === this._currentRefreshId) {
  12607. this._currentRefreshId = 1;
  12608. return true;
  12609. }
  12610. this._currentRefreshId++;
  12611. return false;
  12612. };
  12613. ProceduralTexture.prototype.getRenderSize = function () {
  12614. return this._size;
  12615. };
  12616. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12617. if (this._fallbackTextureUsed) {
  12618. return;
  12619. }
  12620. this.releaseInternalTexture();
  12621. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12622. };
  12623. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12624. if (this._uniforms.indexOf(uniformName) === -1) {
  12625. this._uniforms.push(uniformName);
  12626. }
  12627. };
  12628. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12629. if (this._samplers.indexOf(name) === -1) {
  12630. this._samplers.push(name);
  12631. }
  12632. this._textures[name] = texture;
  12633. return this;
  12634. };
  12635. ProceduralTexture.prototype.setFloat = function (name, value) {
  12636. this._checkUniform(name);
  12637. this._floats[name] = value;
  12638. return this;
  12639. };
  12640. ProceduralTexture.prototype.setFloats = function (name, value) {
  12641. this._checkUniform(name);
  12642. this._floatsArrays[name] = value;
  12643. return this;
  12644. };
  12645. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12646. this._checkUniform(name);
  12647. this._colors3[name] = value;
  12648. return this;
  12649. };
  12650. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12651. this._checkUniform(name);
  12652. this._colors4[name] = value;
  12653. return this;
  12654. };
  12655. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12656. this._checkUniform(name);
  12657. this._vectors2[name] = value;
  12658. return this;
  12659. };
  12660. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12661. this._checkUniform(name);
  12662. this._vectors3[name] = value;
  12663. return this;
  12664. };
  12665. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12666. this._checkUniform(name);
  12667. this._matrices[name] = value;
  12668. return this;
  12669. };
  12670. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12671. var scene = this.getScene();
  12672. var engine = scene.getEngine();
  12673. engine.bindFramebuffer(this._texture);
  12674. // Clear
  12675. engine.clear(scene.clearColor, true, true);
  12676. // Render
  12677. engine.enableEffect(this._effect);
  12678. engine.setState(false);
  12679. for (var name in this._textures) {
  12680. this._effect.setTexture(name, this._textures[name]);
  12681. }
  12682. for (name in this._floats) {
  12683. this._effect.setFloat(name, this._floats[name]);
  12684. }
  12685. for (name in this._floatsArrays) {
  12686. this._effect.setArray(name, this._floatsArrays[name]);
  12687. }
  12688. for (name in this._colors3) {
  12689. this._effect.setColor3(name, this._colors3[name]);
  12690. }
  12691. for (name in this._colors4) {
  12692. var color = this._colors4[name];
  12693. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12694. }
  12695. for (name in this._vectors2) {
  12696. this._effect.setVector2(name, this._vectors2[name]);
  12697. }
  12698. for (name in this._vectors3) {
  12699. this._effect.setVector3(name, this._vectors3[name]);
  12700. }
  12701. for (name in this._matrices) {
  12702. this._effect.setMatrix(name, this._matrices[name]);
  12703. }
  12704. // VBOs
  12705. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12706. // Draw order
  12707. engine.draw(true, 0, 6);
  12708. // Unbind
  12709. engine.unBindFramebuffer(this._texture);
  12710. };
  12711. ProceduralTexture.prototype.clone = function () {
  12712. var textureSize = this.getSize();
  12713. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12714. // Base texture
  12715. newTexture.hasAlpha = this.hasAlpha;
  12716. newTexture.level = this.level;
  12717. // RenderTarget Texture
  12718. newTexture.coordinatesMode = this.coordinatesMode;
  12719. return newTexture;
  12720. };
  12721. ProceduralTexture.prototype.dispose = function () {
  12722. var index = this.getScene()._proceduralTextures.indexOf(this);
  12723. if (index >= 0) {
  12724. this.getScene()._proceduralTextures.splice(index, 1);
  12725. }
  12726. _super.prototype.dispose.call(this);
  12727. };
  12728. return ProceduralTexture;
  12729. })(BABYLON.Texture);
  12730. BABYLON.ProceduralTexture = ProceduralTexture;
  12731. })(BABYLON || (BABYLON = {}));
  12732. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12733. var BABYLON;
  12734. (function (BABYLON) {
  12735. var WoodProceduralTexture = (function (_super) {
  12736. __extends(WoodProceduralTexture, _super);
  12737. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12738. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12739. this._ampScale = 100.0;
  12740. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12741. this.updateShaderUniforms();
  12742. this.refreshRate = 0;
  12743. }
  12744. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12745. this.setFloat("ampScale", this._ampScale);
  12746. this.setColor3("woodColor", this._woodColor);
  12747. };
  12748. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12749. get: function () {
  12750. return this._ampScale;
  12751. },
  12752. set: function (value) {
  12753. this._ampScale = value;
  12754. this.updateShaderUniforms();
  12755. },
  12756. enumerable: true,
  12757. configurable: true
  12758. });
  12759. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12760. get: function () {
  12761. return this._woodColor;
  12762. },
  12763. set: function (value) {
  12764. this._woodColor = value;
  12765. this.updateShaderUniforms();
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. return WoodProceduralTexture;
  12771. })(BABYLON.ProceduralTexture);
  12772. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12773. var FireProceduralTexture = (function (_super) {
  12774. __extends(FireProceduralTexture, _super);
  12775. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12776. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12777. this._time = 0.0;
  12778. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12779. this._shift = 1.6;
  12780. this._autoGenerateTime = true;
  12781. this._alphaThreshold = 0.5;
  12782. this._fireColors = FireProceduralTexture.RedFireColors;
  12783. this.updateShaderUniforms();
  12784. this.refreshRate = 1;
  12785. }
  12786. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12787. this.setFloat("time", this._time);
  12788. this.setVector2("speed", this._speed);
  12789. this.setFloat("shift", this._shift);
  12790. this.setColor3("c1", this._fireColors[0]);
  12791. this.setColor3("c2", this._fireColors[1]);
  12792. this.setColor3("c3", this._fireColors[2]);
  12793. this.setColor3("c4", this._fireColors[3]);
  12794. this.setColor3("c5", this._fireColors[4]);
  12795. this.setColor3("c6", this._fireColors[5]);
  12796. this.setFloat("alphaThreshold", this._alphaThreshold);
  12797. };
  12798. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12799. if (this._autoGenerateTime) {
  12800. this._time += this.getScene().getAnimationRatio() * 0.03;
  12801. this.updateShaderUniforms();
  12802. }
  12803. _super.prototype.render.call(this, useCameraPostProcess);
  12804. };
  12805. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12806. get: function () {
  12807. return [
  12808. new BABYLON.Color3(0.5, 0.0, 1.0),
  12809. new BABYLON.Color3(0.9, 0.0, 1.0),
  12810. new BABYLON.Color3(0.2, 0.0, 1.0),
  12811. new BABYLON.Color3(1.0, 0.9, 1.0),
  12812. new BABYLON.Color3(0.1, 0.1, 1.0),
  12813. new BABYLON.Color3(0.9, 0.9, 1.0)
  12814. ];
  12815. },
  12816. enumerable: true,
  12817. configurable: true
  12818. });
  12819. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12820. get: function () {
  12821. return [
  12822. new BABYLON.Color3(0.5, 1.0, 0.0),
  12823. new BABYLON.Color3(0.5, 1.0, 0.0),
  12824. new BABYLON.Color3(0.3, 0.4, 0.0),
  12825. new BABYLON.Color3(0.5, 1.0, 0.0),
  12826. new BABYLON.Color3(0.2, 0.0, 0.0),
  12827. new BABYLON.Color3(0.5, 1.0, 0.0)
  12828. ];
  12829. },
  12830. enumerable: true,
  12831. configurable: true
  12832. });
  12833. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12834. get: function () {
  12835. return [
  12836. new BABYLON.Color3(0.5, 0.0, 0.1),
  12837. new BABYLON.Color3(0.9, 0.0, 0.0),
  12838. new BABYLON.Color3(0.2, 0.0, 0.0),
  12839. new BABYLON.Color3(1.0, 0.9, 0.0),
  12840. new BABYLON.Color3(0.1, 0.1, 0.1),
  12841. new BABYLON.Color3(0.9, 0.9, 0.9)
  12842. ];
  12843. },
  12844. enumerable: true,
  12845. configurable: true
  12846. });
  12847. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12848. get: function () {
  12849. return [
  12850. new BABYLON.Color3(0.1, 0.0, 0.5),
  12851. new BABYLON.Color3(0.0, 0.0, 0.5),
  12852. new BABYLON.Color3(0.1, 0.0, 0.2),
  12853. new BABYLON.Color3(0.0, 0.0, 1.0),
  12854. new BABYLON.Color3(0.1, 0.2, 0.3),
  12855. new BABYLON.Color3(0.0, 0.2, 0.9)
  12856. ];
  12857. },
  12858. enumerable: true,
  12859. configurable: true
  12860. });
  12861. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12862. get: function () {
  12863. return this._fireColors;
  12864. },
  12865. set: function (value) {
  12866. this._fireColors = value;
  12867. this.updateShaderUniforms();
  12868. },
  12869. enumerable: true,
  12870. configurable: true
  12871. });
  12872. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12873. get: function () {
  12874. return this._time;
  12875. },
  12876. set: function (value) {
  12877. this._time = value;
  12878. this.updateShaderUniforms();
  12879. },
  12880. enumerable: true,
  12881. configurable: true
  12882. });
  12883. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12884. get: function () {
  12885. return this._speed;
  12886. },
  12887. set: function (value) {
  12888. this._speed = value;
  12889. this.updateShaderUniforms();
  12890. },
  12891. enumerable: true,
  12892. configurable: true
  12893. });
  12894. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12895. get: function () {
  12896. return this._shift;
  12897. },
  12898. set: function (value) {
  12899. this._shift = value;
  12900. this.updateShaderUniforms();
  12901. },
  12902. enumerable: true,
  12903. configurable: true
  12904. });
  12905. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12906. get: function () {
  12907. return this._alphaThreshold;
  12908. },
  12909. set: function (value) {
  12910. this._alphaThreshold = value;
  12911. this.updateShaderUniforms();
  12912. },
  12913. enumerable: true,
  12914. configurable: true
  12915. });
  12916. return FireProceduralTexture;
  12917. })(BABYLON.ProceduralTexture);
  12918. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12919. var CloudProceduralTexture = (function (_super) {
  12920. __extends(CloudProceduralTexture, _super);
  12921. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12922. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12923. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12924. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12925. this.updateShaderUniforms();
  12926. this.refreshRate = 0;
  12927. }
  12928. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12929. this.setColor3("skyColor", this._skyColor);
  12930. this.setColor3("cloudColor", this._cloudColor);
  12931. };
  12932. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12933. get: function () {
  12934. return this._skyColor;
  12935. },
  12936. set: function (value) {
  12937. this._skyColor = value;
  12938. this.updateShaderUniforms();
  12939. },
  12940. enumerable: true,
  12941. configurable: true
  12942. });
  12943. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12944. get: function () {
  12945. return this._cloudColor;
  12946. },
  12947. set: function (value) {
  12948. this._cloudColor = value;
  12949. this.updateShaderUniforms();
  12950. },
  12951. enumerable: true,
  12952. configurable: true
  12953. });
  12954. return CloudProceduralTexture;
  12955. })(BABYLON.ProceduralTexture);
  12956. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12957. var GrassProceduralTexture = (function (_super) {
  12958. __extends(GrassProceduralTexture, _super);
  12959. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12960. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12961. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12962. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12963. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12964. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12965. this._grassColors = [
  12966. new BABYLON.Color3(0.29, 0.38, 0.02),
  12967. new BABYLON.Color3(0.36, 0.49, 0.09),
  12968. new BABYLON.Color3(0.51, 0.6, 0.28)
  12969. ];
  12970. this.updateShaderUniforms();
  12971. this.refreshRate = 0;
  12972. }
  12973. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12974. this.setColor3("herb1Color", this._grassColors[0]);
  12975. this.setColor3("herb2Color", this._grassColors[1]);
  12976. this.setColor3("herb3Color", this._grassColors[2]);
  12977. this.setColor3("groundColor", this._groundColor);
  12978. };
  12979. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12980. get: function () {
  12981. return this._grassColors;
  12982. },
  12983. set: function (value) {
  12984. this._grassColors = value;
  12985. this.updateShaderUniforms();
  12986. },
  12987. enumerable: true,
  12988. configurable: true
  12989. });
  12990. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12991. get: function () {
  12992. return this._groundColor;
  12993. },
  12994. set: function (value) {
  12995. this.groundColor = value;
  12996. this.updateShaderUniforms();
  12997. },
  12998. enumerable: true,
  12999. configurable: true
  13000. });
  13001. return GrassProceduralTexture;
  13002. })(BABYLON.ProceduralTexture);
  13003. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13004. var RoadProceduralTexture = (function (_super) {
  13005. __extends(RoadProceduralTexture, _super);
  13006. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13007. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13008. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13009. this.updateShaderUniforms();
  13010. this.refreshRate = 0;
  13011. }
  13012. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13013. this.setColor3("roadColor", this._roadColor);
  13014. };
  13015. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13016. get: function () {
  13017. return this._roadColor;
  13018. },
  13019. set: function (value) {
  13020. this._roadColor = value;
  13021. this.updateShaderUniforms();
  13022. },
  13023. enumerable: true,
  13024. configurable: true
  13025. });
  13026. return RoadProceduralTexture;
  13027. })(BABYLON.ProceduralTexture);
  13028. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13029. var BrickProceduralTexture = (function (_super) {
  13030. __extends(BrickProceduralTexture, _super);
  13031. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13032. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13033. this._numberOfBricksHeight = 15;
  13034. this._numberOfBricksWidth = 5;
  13035. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13036. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13037. this.updateShaderUniforms();
  13038. this.refreshRate = 0;
  13039. }
  13040. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13041. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13042. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13043. this.setColor3("brickColor", this._brickColor);
  13044. this.setColor3("jointColor", this._jointColor);
  13045. };
  13046. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13047. get: function () {
  13048. return this._numberOfBricksHeight;
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13054. set: function (value) {
  13055. this._numberOfBricksHeight = value;
  13056. this.updateShaderUniforms();
  13057. },
  13058. enumerable: true,
  13059. configurable: true
  13060. });
  13061. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13062. get: function () {
  13063. return this._numberOfBricksWidth;
  13064. },
  13065. set: function (value) {
  13066. this._numberOfBricksHeight = value;
  13067. this.updateShaderUniforms();
  13068. },
  13069. enumerable: true,
  13070. configurable: true
  13071. });
  13072. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13073. get: function () {
  13074. return this._jointColor;
  13075. },
  13076. set: function (value) {
  13077. this._jointColor = value;
  13078. this.updateShaderUniforms();
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13084. get: function () {
  13085. return this._brickColor;
  13086. },
  13087. set: function (value) {
  13088. this._brickColor = value;
  13089. this.updateShaderUniforms();
  13090. },
  13091. enumerable: true,
  13092. configurable: true
  13093. });
  13094. return BrickProceduralTexture;
  13095. })(BABYLON.ProceduralTexture);
  13096. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13097. var MarbleProceduralTexture = (function (_super) {
  13098. __extends(MarbleProceduralTexture, _super);
  13099. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13100. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13101. this._numberOfTilesHeight = 3;
  13102. this._numberOfTilesWidth = 3;
  13103. this._amplitude = 9.0;
  13104. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13105. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13106. this.updateShaderUniforms();
  13107. this.refreshRate = 0;
  13108. }
  13109. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13110. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13111. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13112. this.setFloat("amplitude", this._amplitude);
  13113. this.setColor3("marbleColor", this._marbleColor);
  13114. this.setColor3("jointColor", this._jointColor);
  13115. };
  13116. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13117. get: function () {
  13118. return this._numberOfTilesHeight;
  13119. },
  13120. set: function (value) {
  13121. this._numberOfTilesHeight = value;
  13122. this.updateShaderUniforms();
  13123. },
  13124. enumerable: true,
  13125. configurable: true
  13126. });
  13127. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13128. get: function () {
  13129. return this._numberOfTilesWidth;
  13130. },
  13131. set: function (value) {
  13132. this._numberOfTilesWidth = value;
  13133. this.updateShaderUniforms();
  13134. },
  13135. enumerable: true,
  13136. configurable: true
  13137. });
  13138. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13139. get: function () {
  13140. return this._jointColor;
  13141. },
  13142. set: function (value) {
  13143. this._jointColor = value;
  13144. this.updateShaderUniforms();
  13145. },
  13146. enumerable: true,
  13147. configurable: true
  13148. });
  13149. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13150. get: function () {
  13151. return this._marbleColor;
  13152. },
  13153. set: function (value) {
  13154. this._marbleColor = value;
  13155. this.updateShaderUniforms();
  13156. },
  13157. enumerable: true,
  13158. configurable: true
  13159. });
  13160. return MarbleProceduralTexture;
  13161. })(BABYLON.ProceduralTexture);
  13162. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13163. })(BABYLON || (BABYLON = {}));
  13164. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13165. var BABYLON;
  13166. (function (BABYLON) {
  13167. var CustomProceduralTexture = (function (_super) {
  13168. __extends(CustomProceduralTexture, _super);
  13169. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13170. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13171. this._animate = true;
  13172. this._time = 0;
  13173. this._texturePath = texturePath;
  13174. //Try to load json
  13175. this.loadJson(texturePath);
  13176. this.refreshRate = 1;
  13177. }
  13178. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13179. var _this = this;
  13180. var that = this;
  13181. function noConfigFile() {
  13182. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13183. try {
  13184. that.setFragment(that._texturePath);
  13185. }
  13186. catch (ex) {
  13187. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13188. }
  13189. }
  13190. var configFileUrl = jsonUrl + "/config.json";
  13191. var xhr = new XMLHttpRequest();
  13192. xhr.open("GET", configFileUrl, true);
  13193. xhr.addEventListener("load", function () {
  13194. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13195. try {
  13196. _this._config = JSON.parse(xhr.response);
  13197. _this.updateShaderUniforms();
  13198. _this.updateTextures();
  13199. _this.setFragment(_this._texturePath + "/custom");
  13200. _this._animate = _this._config.animate;
  13201. _this.refreshRate = _this._config.refreshrate;
  13202. }
  13203. catch (ex) {
  13204. noConfigFile();
  13205. }
  13206. }
  13207. else {
  13208. noConfigFile();
  13209. }
  13210. }, false);
  13211. xhr.addEventListener("error", function () {
  13212. noConfigFile();
  13213. }, false);
  13214. try {
  13215. xhr.send();
  13216. }
  13217. catch (ex) {
  13218. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13219. }
  13220. };
  13221. CustomProceduralTexture.prototype.isReady = function () {
  13222. if (!_super.prototype.isReady.call(this)) {
  13223. return false;
  13224. }
  13225. for (var name in this._textures) {
  13226. var texture = this._textures[name];
  13227. if (!texture.isReady()) {
  13228. return false;
  13229. }
  13230. }
  13231. return true;
  13232. };
  13233. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13234. if (this._animate) {
  13235. this._time += this.getScene().getAnimationRatio() * 0.03;
  13236. this.updateShaderUniforms();
  13237. }
  13238. _super.prototype.render.call(this, useCameraPostProcess);
  13239. };
  13240. CustomProceduralTexture.prototype.updateTextures = function () {
  13241. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13242. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13243. }
  13244. };
  13245. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13246. if (this._config) {
  13247. for (var j = 0; j < this._config.uniforms.length; j++) {
  13248. var uniform = this._config.uniforms[j];
  13249. switch (uniform.type) {
  13250. case "float":
  13251. this.setFloat(uniform.name, uniform.value);
  13252. break;
  13253. case "color3":
  13254. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13255. break;
  13256. case "color4":
  13257. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13258. break;
  13259. case "vector2":
  13260. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13261. break;
  13262. case "vector3":
  13263. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13264. break;
  13265. }
  13266. }
  13267. }
  13268. this.setFloat("time", this._time);
  13269. };
  13270. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13271. get: function () {
  13272. return this._animate;
  13273. },
  13274. set: function (value) {
  13275. this._animate = value;
  13276. },
  13277. enumerable: true,
  13278. configurable: true
  13279. });
  13280. return CustomProceduralTexture;
  13281. })(BABYLON.ProceduralTexture);
  13282. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13283. })(BABYLON || (BABYLON = {}));
  13284. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13285. var BABYLON;
  13286. (function (BABYLON) {
  13287. var MirrorTexture = (function (_super) {
  13288. __extends(MirrorTexture, _super);
  13289. function MirrorTexture(name, size, scene, generateMipMaps) {
  13290. var _this = this;
  13291. _super.call(this, name, size, scene, generateMipMaps, true);
  13292. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13293. this._transformMatrix = BABYLON.Matrix.Zero();
  13294. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13295. this.onBeforeRender = function () {
  13296. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13297. _this._savedViewMatrix = scene.getViewMatrix();
  13298. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13299. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13300. scene.clipPlane = _this.mirrorPlane;
  13301. scene.getEngine().cullBackFaces = false;
  13302. };
  13303. this.onAfterRender = function () {
  13304. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13305. scene.getEngine().cullBackFaces = true;
  13306. delete scene.clipPlane;
  13307. };
  13308. }
  13309. MirrorTexture.prototype.clone = function () {
  13310. var textureSize = this.getSize();
  13311. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13312. // Base texture
  13313. newTexture.hasAlpha = this.hasAlpha;
  13314. newTexture.level = this.level;
  13315. // Mirror Texture
  13316. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13317. newTexture.renderList = this.renderList.slice(0);
  13318. return newTexture;
  13319. };
  13320. return MirrorTexture;
  13321. })(BABYLON.RenderTargetTexture);
  13322. BABYLON.MirrorTexture = MirrorTexture;
  13323. })(BABYLON || (BABYLON = {}));
  13324. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13325. var BABYLON;
  13326. (function (BABYLON) {
  13327. var DynamicTexture = (function (_super) {
  13328. __extends(DynamicTexture, _super);
  13329. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13331. _super.call(this, null, scene, !generateMipMaps);
  13332. this.name = name;
  13333. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13334. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13335. this._generateMipMaps = generateMipMaps;
  13336. if (options.getContext) {
  13337. this._canvas = options;
  13338. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13339. }
  13340. else {
  13341. this._canvas = document.createElement("canvas");
  13342. if (options.width) {
  13343. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13344. }
  13345. else {
  13346. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13347. }
  13348. }
  13349. var textureSize = this.getSize();
  13350. this._canvas.width = textureSize.width;
  13351. this._canvas.height = textureSize.height;
  13352. this._context = this._canvas.getContext("2d");
  13353. }
  13354. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13355. get: function () {
  13356. return true;
  13357. },
  13358. enumerable: true,
  13359. configurable: true
  13360. });
  13361. DynamicTexture.prototype.scale = function (ratio) {
  13362. var textureSize = this.getSize();
  13363. textureSize.width *= ratio;
  13364. textureSize.height *= ratio;
  13365. this._canvas.width = textureSize.width;
  13366. this._canvas.height = textureSize.height;
  13367. this.releaseInternalTexture();
  13368. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13369. };
  13370. DynamicTexture.prototype.getContext = function () {
  13371. return this._context;
  13372. };
  13373. DynamicTexture.prototype.clear = function () {
  13374. var size = this.getSize();
  13375. this._context.fillRect(0, 0, size.width, size.height);
  13376. };
  13377. DynamicTexture.prototype.update = function (invertY) {
  13378. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13379. };
  13380. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13381. if (update === void 0) { update = true; }
  13382. var size = this.getSize();
  13383. if (clearColor) {
  13384. this._context.fillStyle = clearColor;
  13385. this._context.fillRect(0, 0, size.width, size.height);
  13386. }
  13387. this._context.font = font;
  13388. if (x === null) {
  13389. var textSize = this._context.measureText(text);
  13390. x = (size.width - textSize.width) / 2;
  13391. }
  13392. this._context.fillStyle = color;
  13393. this._context.fillText(text, x, y);
  13394. if (update) {
  13395. this.update(invertY);
  13396. }
  13397. };
  13398. DynamicTexture.prototype.clone = function () {
  13399. var textureSize = this.getSize();
  13400. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13401. // Base texture
  13402. newTexture.hasAlpha = this.hasAlpha;
  13403. newTexture.level = this.level;
  13404. // Dynamic Texture
  13405. newTexture.wrapU = this.wrapU;
  13406. newTexture.wrapV = this.wrapV;
  13407. return newTexture;
  13408. };
  13409. return DynamicTexture;
  13410. })(BABYLON.Texture);
  13411. BABYLON.DynamicTexture = DynamicTexture;
  13412. })(BABYLON || (BABYLON = {}));
  13413. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13414. var BABYLON;
  13415. (function (BABYLON) {
  13416. var VideoTexture = (function (_super) {
  13417. __extends(VideoTexture, _super);
  13418. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13419. var _this = this;
  13420. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13421. _super.call(this, null, scene, !generateMipMaps, invertY);
  13422. this._autoLaunch = true;
  13423. this.name = name;
  13424. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13425. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13426. var requiredWidth = size.width || size;
  13427. var requiredHeight = size.height || size;
  13428. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13429. var textureSize = this.getSize();
  13430. this.video = document.createElement("video");
  13431. this.video.width = textureSize.width;
  13432. this.video.height = textureSize.height;
  13433. this.video.autoplay = false;
  13434. this.video.loop = true;
  13435. this.video.addEventListener("canplaythrough", function () {
  13436. if (_this._texture) {
  13437. _this._texture.isReady = true;
  13438. }
  13439. });
  13440. urls.forEach(function (url) {
  13441. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13442. var source = document.createElement("source");
  13443. source.src = url;
  13444. _this.video.appendChild(source);
  13445. });
  13446. this._lastUpdate = BABYLON.Tools.Now;
  13447. }
  13448. VideoTexture.prototype.update = function () {
  13449. if (this._autoLaunch) {
  13450. this._autoLaunch = false;
  13451. this.video.play();
  13452. }
  13453. var now = BABYLON.Tools.Now;
  13454. if (now - this._lastUpdate < 15) {
  13455. return false;
  13456. }
  13457. this._lastUpdate = now;
  13458. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13459. return true;
  13460. };
  13461. return VideoTexture;
  13462. })(BABYLON.Texture);
  13463. BABYLON.VideoTexture = VideoTexture;
  13464. })(BABYLON || (BABYLON = {}));
  13465. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13466. (function (BABYLON) {
  13467. var EffectFallbacks = (function () {
  13468. function EffectFallbacks() {
  13469. this._defines = {};
  13470. this._currentRank = 32;
  13471. this._maxRank = -1;
  13472. }
  13473. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13474. if (!this._defines[rank]) {
  13475. if (rank < this._currentRank) {
  13476. this._currentRank = rank;
  13477. }
  13478. if (rank > this._maxRank) {
  13479. this._maxRank = rank;
  13480. }
  13481. this._defines[rank] = new Array();
  13482. }
  13483. this._defines[rank].push(define);
  13484. };
  13485. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13486. get: function () {
  13487. return this._currentRank <= this._maxRank;
  13488. },
  13489. enumerable: true,
  13490. configurable: true
  13491. });
  13492. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13493. var currentFallbacks = this._defines[this._currentRank];
  13494. for (var index = 0; index < currentFallbacks.length; index++) {
  13495. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13496. }
  13497. this._currentRank++;
  13498. return currentDefines;
  13499. };
  13500. return EffectFallbacks;
  13501. })();
  13502. BABYLON.EffectFallbacks = EffectFallbacks;
  13503. var Effect = (function () {
  13504. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13505. var _this = this;
  13506. this._isReady = false;
  13507. this._compilationError = "";
  13508. this._valueCache = [];
  13509. this._engine = engine;
  13510. this.name = baseName;
  13511. this.defines = defines;
  13512. this._uniformsNames = uniformsNames.concat(samplers);
  13513. this._samplers = samplers;
  13514. this._attributesNames = attributesNames;
  13515. this.onError = onError;
  13516. this.onCompiled = onCompiled;
  13517. var vertexSource;
  13518. var fragmentSource;
  13519. if (baseName.vertexElement) {
  13520. vertexSource = document.getElementById(baseName.vertexElement);
  13521. if (!vertexSource) {
  13522. vertexSource = baseName.vertexElement;
  13523. }
  13524. }
  13525. else {
  13526. vertexSource = baseName.vertex || baseName;
  13527. }
  13528. if (baseName.fragmentElement) {
  13529. fragmentSource = document.getElementById(baseName.fragmentElement);
  13530. if (!fragmentSource) {
  13531. fragmentSource = baseName.fragmentElement;
  13532. }
  13533. }
  13534. else {
  13535. fragmentSource = baseName.fragment || baseName;
  13536. }
  13537. this._loadVertexShader(vertexSource, function (vertexCode) {
  13538. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13539. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13540. });
  13541. });
  13542. }
  13543. // Properties
  13544. Effect.prototype.isReady = function () {
  13545. return this._isReady;
  13546. };
  13547. Effect.prototype.getProgram = function () {
  13548. return this._program;
  13549. };
  13550. Effect.prototype.getAttributesNames = function () {
  13551. return this._attributesNames;
  13552. };
  13553. Effect.prototype.getAttributeLocation = function (index) {
  13554. return this._attributes[index];
  13555. };
  13556. Effect.prototype.getAttributeLocationByName = function (name) {
  13557. var index = this._attributesNames.indexOf(name);
  13558. return this._attributes[index];
  13559. };
  13560. Effect.prototype.getAttributesCount = function () {
  13561. return this._attributes.length;
  13562. };
  13563. Effect.prototype.getUniformIndex = function (uniformName) {
  13564. return this._uniformsNames.indexOf(uniformName);
  13565. };
  13566. Effect.prototype.getUniform = function (uniformName) {
  13567. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13568. };
  13569. Effect.prototype.getSamplers = function () {
  13570. return this._samplers;
  13571. };
  13572. Effect.prototype.getCompilationError = function () {
  13573. return this._compilationError;
  13574. };
  13575. // Methods
  13576. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13577. // DOM element ?
  13578. if (vertex instanceof HTMLElement) {
  13579. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13580. callback(vertexCode);
  13581. return;
  13582. }
  13583. // Is in local store ?
  13584. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13585. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13586. return;
  13587. }
  13588. var vertexShaderUrl;
  13589. if (vertex[0] === ".") {
  13590. vertexShaderUrl = vertex;
  13591. }
  13592. else {
  13593. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13594. }
  13595. // Vertex shader
  13596. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13597. };
  13598. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13599. // DOM element ?
  13600. if (fragment instanceof HTMLElement) {
  13601. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13602. callback(fragmentCode);
  13603. return;
  13604. }
  13605. // Is in local store ?
  13606. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13607. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13608. return;
  13609. }
  13610. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13611. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13612. return;
  13613. }
  13614. var fragmentShaderUrl;
  13615. if (fragment[0] === ".") {
  13616. fragmentShaderUrl = fragment;
  13617. }
  13618. else {
  13619. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13620. }
  13621. // Fragment shader
  13622. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13623. };
  13624. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13625. try {
  13626. var engine = this._engine;
  13627. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13628. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13629. this._attributes = engine.getAttributes(this._program, attributesNames);
  13630. for (var index = 0; index < this._samplers.length; index++) {
  13631. var sampler = this.getUniform(this._samplers[index]);
  13632. if (sampler == null) {
  13633. this._samplers.splice(index, 1);
  13634. index--;
  13635. }
  13636. }
  13637. engine.bindSamplers(this);
  13638. this._isReady = true;
  13639. if (this.onCompiled) {
  13640. this.onCompiled(this);
  13641. }
  13642. }
  13643. catch (e) {
  13644. // Is it a problem with precision?
  13645. if (e.message.indexOf("highp") !== -1) {
  13646. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13647. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13648. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13649. return;
  13650. }
  13651. // Let's go through fallbacks then
  13652. if (fallbacks && fallbacks.isMoreFallbacks) {
  13653. defines = fallbacks.reduce(defines);
  13654. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13655. }
  13656. else {
  13657. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13658. BABYLON.Tools.Error("Defines: " + defines);
  13659. BABYLON.Tools.Error("Error: " + e.message);
  13660. this._compilationError = e.message;
  13661. if (this.onError) {
  13662. this.onError(this, this._compilationError);
  13663. }
  13664. }
  13665. }
  13666. };
  13667. Effect.prototype._bindTexture = function (channel, texture) {
  13668. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13669. };
  13670. Effect.prototype.setTexture = function (channel, texture) {
  13671. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13672. };
  13673. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13674. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13675. };
  13676. //public _cacheMatrix(uniformName, matrix) {
  13677. // if (!this._valueCache[uniformName]) {
  13678. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13679. // }
  13680. // for (var index = 0; index < 16; index++) {
  13681. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13682. // }
  13683. //};
  13684. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13685. if (!this._valueCache[uniformName]) {
  13686. this._valueCache[uniformName] = [x, y];
  13687. return;
  13688. }
  13689. this._valueCache[uniformName][0] = x;
  13690. this._valueCache[uniformName][1] = y;
  13691. };
  13692. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13693. if (!this._valueCache[uniformName]) {
  13694. this._valueCache[uniformName] = [x, y, z];
  13695. return;
  13696. }
  13697. this._valueCache[uniformName][0] = x;
  13698. this._valueCache[uniformName][1] = y;
  13699. this._valueCache[uniformName][2] = z;
  13700. };
  13701. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13702. if (!this._valueCache[uniformName]) {
  13703. this._valueCache[uniformName] = [x, y, z, w];
  13704. return;
  13705. }
  13706. this._valueCache[uniformName][0] = x;
  13707. this._valueCache[uniformName][1] = y;
  13708. this._valueCache[uniformName][2] = z;
  13709. this._valueCache[uniformName][3] = w;
  13710. };
  13711. Effect.prototype.setArray = function (uniformName, array) {
  13712. this._engine.setArray(this.getUniform(uniformName), array);
  13713. return this;
  13714. };
  13715. Effect.prototype.setArray2 = function (uniformName, array) {
  13716. this._engine.setArray2(this.getUniform(uniformName), array);
  13717. return this;
  13718. };
  13719. Effect.prototype.setArray3 = function (uniformName, array) {
  13720. this._engine.setArray3(this.getUniform(uniformName), array);
  13721. return this;
  13722. };
  13723. Effect.prototype.setArray4 = function (uniformName, array) {
  13724. this._engine.setArray4(this.getUniform(uniformName), array);
  13725. return this;
  13726. };
  13727. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13728. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13729. return this;
  13730. };
  13731. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13732. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13733. // return;
  13734. //this._cacheMatrix(uniformName, matrix);
  13735. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13736. return this;
  13737. };
  13738. Effect.prototype.setFloat = function (uniformName, value) {
  13739. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13740. return this;
  13741. this._valueCache[uniformName] = value;
  13742. this._engine.setFloat(this.getUniform(uniformName), value);
  13743. return this;
  13744. };
  13745. Effect.prototype.setBool = function (uniformName, bool) {
  13746. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13747. return this;
  13748. this._valueCache[uniformName] = bool;
  13749. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13750. return this;
  13751. };
  13752. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13753. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13754. return this;
  13755. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13756. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13757. return this;
  13758. };
  13759. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13760. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13761. return this;
  13762. this._cacheFloat2(uniformName, x, y);
  13763. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13764. return this;
  13765. };
  13766. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13767. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13768. return this;
  13769. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13770. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13771. return this;
  13772. };
  13773. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13774. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13775. return this;
  13776. this._cacheFloat3(uniformName, x, y, z);
  13777. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13778. return this;
  13779. };
  13780. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13781. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13782. return this;
  13783. this._cacheFloat4(uniformName, x, y, z, w);
  13784. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13785. return this;
  13786. };
  13787. Effect.prototype.setColor3 = function (uniformName, color3) {
  13788. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13789. return this;
  13790. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13791. this._engine.setColor3(this.getUniform(uniformName), color3);
  13792. return this;
  13793. };
  13794. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13795. 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)
  13796. return this;
  13797. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13798. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13799. return this;
  13800. };
  13801. // Statics
  13802. 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}",
  13803. 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}",
  13804. 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}",
  13805. 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}",
  13806. chromaticAberrationPixelShader:"/*\n BABYLON.JS Chromatic Aberration GLSL Shader\n Author: Olivier Guyot\n Separates very slightly R, G and B colors on the edges of the screen\n Inspired by Francois Tarlier & Martins Upitis \n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // original color\n\n// uniforms\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\n// varyings\nvarying vec2 vUV;\n\nvoid main(void)\n{\n vec2 centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n float radius2 = centered_screen_pos.x*centered_screen_pos.x\n + centered_screen_pos.y*centered_screen_pos.y;\n float radius = sqrt(radius2);\n\n vec4 original = texture2D(textureSampler, vUV);\n\n if(chromatic_aberration > 0.0) {\n //index of refraction of each color channel, causing chromatic dispersion\n vec3 ref_indices = vec3(0.6, 0.3, 0.0);\n float ref_shiftX = chromatic_aberration * radius * 12.0 / screen_width;\n float ref_shiftY = chromatic_aberration * radius * 12.0 / screen_height;\n\n // shifts for red, green & blue\n vec2 ref_coords_r = vec2(vUV.x + ref_indices.r*ref_shiftX, vUV.y + ref_indices.r*ref_shiftY*0.5);\n vec2 ref_coords_g = vec2(vUV.x + ref_indices.g*ref_shiftX, vUV.y + ref_indices.g*ref_shiftY*0.5);\n vec2 ref_coords_b = vec2(vUV.x + ref_indices.b*ref_shiftX, vUV.y + ref_indices.b*ref_shiftY*0.5);\n\n original.r = texture2D(textureSampler, ref_coords_r).r;\n original.g = texture2D(textureSampler, ref_coords_g).g;\n original.b = texture2D(textureSampler, ref_coords_b).b;\n }\n\n gl_FragColor = original;\n}",
  13807. 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}",
  13808. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13809. 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}",
  13810. colorCorrectionPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// samplers\nuniform sampler2D textureSampler; // screen render\nuniform sampler2D colorTable; // color table with modified colors\n\n// varyings\nvarying vec2 vUV;\n\n// constants\nconst float SLICE_COUNT = 16.0; // how many slices in the color cube; 1 slice = 1 pixel\n// it means the image is 256x16 pixels\n\nvec4 sampleAs3DTexture(sampler2D texture, vec3 uv, float width) {\n float sliceSize = 1.0 / width; // space of 1 slice\n float slicePixelSize = sliceSize / width; // space of 1 pixel\n float sliceInnerSize = slicePixelSize * (width - 1.0); // space of width pixels\n float zSlice0 = min(floor(uv.z * width), width - 1.0);\n float zSlice1 = min(zSlice0 + 1.0, width - 1.0);\n float xOffset = slicePixelSize * 0.5 + uv.x * sliceInnerSize;\n float s0 = xOffset + (zSlice0 * sliceSize);\n float s1 = xOffset + (zSlice1 * sliceSize);\n vec4 slice0Color = texture2D(texture, vec2(s0, uv.y));\n vec4 slice1Color = texture2D(texture, vec2(s1, uv.y));\n float zOffset = mod(uv.z * width, 1.0);\n vec4 result = mix(slice0Color, slice1Color, zOffset);\n return result;\n}\n\nvoid main(void)\n{\n vec4 screen_color = texture2D(textureSampler, vUV);\n gl_FragColor = sampleAs3DTexture(colorTable, screen_color.rgb, SLICE_COUNT);\n\n}",
  13811. 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}",
  13812. 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;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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 vec3 shadowsInfo0;\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 vec3 shadowsInfo1;\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 vec3 shadowsInfo2;\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 vec3 shadowsInfo3;\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 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\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, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\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] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n bias = 0.02 + bias;\n if (t <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, bias);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05 - bias, 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z > 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 1.0 - ChebychevInequality(moments, depth.z, bias);\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 = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\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#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\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, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\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, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\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, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\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, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\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}",
  13813. defaultVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attributes\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\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;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\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\n#ifdef NORMAL\n vNormalW = normalize(vec3(finalWorld * vec4(normal, 0.0)));\n#endif\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}",
  13814. depthPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nuniform float far;\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n float depth = (gl_FragCoord.z / gl_FragCoord.w) / far;\n gl_FragColor = vec4(depth, depth * depth, 0.0, 1.0);\n}",
  13815. depthVertexShader:"#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#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 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}",
  13816. depthBoxBlurPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Samplers\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\n// Parameters\nuniform vec2 screenSize;\n\nvoid main(void)\n{\n vec4 colorDepth = vec4(0.0);\n\n for (int x = -OFFSET; x <= OFFSET; x++)\n for (int y = -OFFSET; y <= OFFSET; y++)\n colorDepth += texture2D(textureSampler, vUV + vec2(x, y) / screenSize);\n\n gl_FragColor = (colorDepth / float((OFFSET * 2 + 1) * (OFFSET * 2 + 1)));\n}",
  13817. depthOfFieldPixelShader:"/*\n BABYLON.JS Depth-of-field GLSL Shader\n Author: Olivier Guyot\n Does depth-of-field blur, edge blur, highlights enhancing\n Inspired by Francois Tarlier & Martins Upitis\n*/\n\n#ifdef GL_ES\nprecision highp float;\n#endif\n\n\n// samplers\nuniform sampler2D textureSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\n// uniforms\nuniform float grain_amount;\nuniform bool pentagon;\nuniform float maxZ;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform float focus_depth;\nuniform float aperture;\nuniform float gain;\nuniform float threshold;\nuniform float edge_blur;\n\n// varyings\nvarying vec2 vUV;\n\n// constants\n#define PI 3.14159265\nconst int RING_1_SAMPLES = 4;\nconst int RING_2_SAMPLES = 6;\nconst int RING_3_SAMPLES = 9;\nconst int RING_4_SAMPLES = 12;\nconst int RING_5_SAMPLES = 16;\n//const int RING_6_SAMPLES = 15;\nconst float RING_STEP_DIST = 0.4; // a new blur ring is added each time this distance is passed\nconst float PENTAGON_ANGLE_SUB = 1.2566; // 2PI / 5\nconst float PENTAGON_ANGLE_SUB_HALF = 0.6283; // 2PI / 10\n\n// common calculations\nvec2 centered_screen_pos;\nfloat radius2;\nfloat radius;\n\n\n// applies edge distortion on texture coords\nvec2 getDistortedCoords(vec2 coords) {\n\n if(distortion == 0.0) { return coords; }\n\n vec2 direction = 1.0 * normalize(centered_screen_pos);\n vec2 dist_coords = vec2(0.5, 0.5);\n dist_coords.x = 0.5 + direction.x * radius2 * 1.0;\n dist_coords.y = 0.5 + direction.y * radius2 * 1.0;\n float dist_amount = clamp(distortion*0.23, 0.0, 1.0);\n\n dist_coords = mix(coords, dist_coords, dist_amount);\n\n return dist_coords;\n}\n\n// picks either original screen color or highlights only\nvec4 getColor(vec2 coords, bool highlight) {\n\n vec4 color = texture2D(textureSampler, coords);\n\n if(highlight) {\n float luminance = dot(color.rgb, vec3(0.2125, 0.7154, 0.0721));\n float lum_threshold;\n if(threshold > 1.0) { lum_threshold = 0.94 + 0.01 * threshold; }\n else { lum_threshold = 0.5 + 0.44 * threshold; }\n if(luminance < lum_threshold) {\n color.rgb = vec3(0.0, 0.0, 0.0);\n color.a = 1.0;\n }\n }\n\n return color;\n}\n\n// returns a modifier to be applied on the radius, in order to simulate a pentagon\nfloat pentagonShape(float angle) {\n float a1 = mod(angle, PENTAGON_ANGLE_SUB) / PENTAGON_ANGLE_SUB - 0.5;\n float a2 = 0.5 - a1 * a1;\n return 1.35 - 0.94 * a2;\n}\n\n// returns original screen color after blur\nvec4 getBlurColor(vec2 coords, float size, bool highlight) {\n\n float w = (size/screen_width);\n float h = (size/screen_height);\n\n vec4 col = getColor(coords, highlight);\n if(size == 0.0) { return col; }\n\n float s = 1.0;\n float pw; // sample x relative coord\n float ph; // sample y relative coord\n float bias = 0.65; // inner/outer ring bias\n if(highlight) { bias = 0.95; }\n float sample_angle;\n float ratio_rings;\n float ring_radius;\n float penta; // pentagon shape modifier\n\n int ring_count;\n if(size >= 6.0 * RING_STEP_DIST) { ring_count = 6; }\n else if(size >= 5.0 * RING_STEP_DIST) { ring_count = 5; }\n else if(size >= 4.0 * RING_STEP_DIST) { ring_count = 4; }\n else if(size >= 3.0 * RING_STEP_DIST) { ring_count = 3; }\n else if(size >= 2.0 * RING_STEP_DIST) { ring_count = 2; }\n else { ring_count = 1; }\n \n // RING 1\n if(size > RING_STEP_DIST) {\n ring_radius = size / float(ring_count);\n ratio_rings = 1.0 / float(ring_count);\n for(int i = 0; i < RING_1_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_1_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias);\n }\n } \n\n // RING 2\n if(size > RING_STEP_DIST * 2.0) {\n ring_radius = 2.0 * size / float(ring_count);\n ratio_rings = 2.0 / float(ring_count);\n for(int i = 0; i < RING_2_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_2_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 3\n if(size > RING_STEP_DIST * 3.0) {\n ring_radius = 3.0 * size / float(ring_count);\n ratio_rings = 3.0 / float(ring_count);\n for(int i = 0; i < RING_3_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_3_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 4\n if(size > RING_STEP_DIST * 4.0) {\n ring_radius = 4.0 * size / float(ring_count);\n ratio_rings = 4.0 / float(ring_count);\n for(int i = 0; i < RING_4_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_4_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n // RING 5\n if(size > RING_STEP_DIST * 5.0) {\n ring_radius = 5.0 * size / float(ring_count);\n ratio_rings = 5.0 / float(ring_count);\n for(int i = 0; i < RING_5_SAMPLES; i++) {\n sample_angle = PI *2.0 * float(i) / float(RING_5_SAMPLES);\n if(pentagon) { penta = pentagonShape(sample_angle); }\n else { penta = 1.0; }\n pw = cos( sample_angle ) * penta * ring_radius;\n ph = sin( sample_angle ) * penta * ring_radius;\n col += getColor(coords + vec2(pw*w,ph*h), highlight) * mix( 1.0, ratio_rings, bias );\n s += 1.0 * mix(1.0, ratio_rings, bias); \n }\n } \n\n col /= s; // scales color according to samples taken\n col.a = 1.0;\n\n return col;\n}\n\n// on-the-fly constant noise\nvec2 rand(vec2 co)\n{\n float noise1 = (fract(sin(dot(co ,vec2(12.9898,78.233))) * 43758.5453));\n float noise2 = (fract(sin(dot(co ,vec2(12.9898,78.233)*2.0)) * 43758.5453));\n return clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvoid main(void)\n{\n\n // Common calc\n centered_screen_pos = vec2(vUV.x-0.5, vUV.y-0.5);\n radius2 = centered_screen_pos.x*centered_screen_pos.x + centered_screen_pos.y*centered_screen_pos.y;\n radius = sqrt(radius2);\n\n vec4 final_color;\n vec2 distorted_coords = getDistortedCoords(vUV);\n vec2 texels_coords = vec2(vUV.x * screen_width, vUV.y * screen_height); // varies from 0 to SCREEN_WIDTH or _HEIGHT\n\n // blur from depth of field effect\n float dof_blur_amount = 0.0;\n if(focus_depth != -1.0) {\n vec4 depth_sample = texture2D(depthSampler, distorted_coords);\n float depth = depth_sample.r;\n dof_blur_amount = abs(depth - focus_depth) * aperture * 3.5;\n if(dof_blur_amount < 0.05) { dof_blur_amount = 0.0; } // no blur at all\n else if( depth - focus_depth < 0.0 ) { dof_blur_amount *= 2.0; } // blur more when close to camera\n dof_blur_amount = clamp(dof_blur_amount, 0.0, 1.0);\n }\n\n // blur from edge blur effect\n float edge_blur_amount = 0.0;\n if(edge_blur > 0.0) {\n edge_blur_amount = clamp( ( radius*2.0 - 1.0 + 0.15*edge_blur ) * 1.5 , 0.0 , 1.0 ) * 1.3;\n }\n\n // total blur amount\n float blur_amount = max(edge_blur_amount, dof_blur_amount);\n\n // apply blur if necessary\n if(blur_amount == 0.0) {\n gl_FragColor = getColor(distorted_coords, false);\n } else {\n gl_FragColor = getBlurColor(distorted_coords, blur_amount * 1.7, false)\n + gain * blur_amount*getBlurColor(distorted_coords, blur_amount * 2.75, true);\n\n if(blur_noise) {\n // we put a slight amount of noise in the blurred color\n vec2 noise = rand(distorted_coords) * 0.01 * blur_amount;\n vec2 blurred_coord = vec2(distorted_coords.x + noise.x, distorted_coords.y + noise.y);\n gl_FragColor = 0.04 * getColor(blurred_coord, false) + 0.96 * gl_FragColor;\n }\n }\n\n if(grain_amount > 0.0) {\n vec4 grain_color = texture2D(grainSampler, texels_coords*0.003);\n gl_FragColor.rgb += ( -0.5 + grain_color.rgb ) * 0.20;\n }\n}",
  13818. 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}",
  13819. 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}",
  13820. 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}",
  13821. 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}",
  13822. 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}",
  13823. 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}",
  13824. 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}",
  13825. 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}",
  13826. 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}",
  13827. 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}",
  13828. 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}",
  13829. 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}",
  13830. 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}",
  13831. 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}",
  13832. 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}",
  13833. 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}",
  13834. 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}",
  13835. 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}",
  13836. 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}",
  13837. 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}",
  13838. 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}",
  13839. 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}",
  13840. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bit_shift = vec4(255.0 * 255.0 * 255.0, 255.0 * 255.0, 255.0, 1.0);\n const vec4 bit_mask = vec4(0.0, 1.0 / 255.0, 1.0 / 255.0, 1.0 / 255.0);\n\n vec4 res = fract(depth * bit_shift);\n res -= res.xxyz * bit_mask;\n\n return res;\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\nvarying vec4 vPosition;\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 float depth = vPosition.z / vPosition.w;\n depth = depth * 0.5 + 0.5;\n\n#ifdef VSM\n float moment1 = depth;\n float moment2 = moment1 * moment1;\n\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(depth);\n#endif\n}",
  13841. 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\nvarying vec4 vPosition;\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#endif\n\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n gl_Position = vPosition;\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}",
  13842. 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}",
  13843. 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}",
  13844. ssaoPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define SAMPLES 16\n\nuniform sampler2D textureSampler;\nuniform sampler2D randomSampler;\n\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[16];\n\nvarying vec2 vUV;\n\nconst vec2 offset1 = vec2(0.0, 0.01);\nconst vec2 offset2 = vec2(0.01, 0.0);\n\nvec3 normalFromDepth(const float depth, const vec2 coords) {\n float depth1 = texture2D(textureSampler, coords + offset1).r;\n float depth2 = texture2D(textureSampler, coords + offset2).r;\n\n vec3 p1 = vec3(offset1, depth1 - depth);\n vec3 p2 = vec3(offset2, depth2 - depth);\n\n vec3 normal = cross(p1, p2);\n normal.z = -normal.z;\n\n return normalize(normal);\n}\n\nvoid main(void)\n{\n const float totalStrength = 1.0;\n const float base = 0.2;\n const float area = 0.0075;\n const float fallOff = 0.000001;\n const float radius = 0.0005;\n\n vec3 random = texture2D(randomSampler, vUV * randTextureTiles).rgb;\n float depth = texture2D(textureSampler, vUV).r;\n vec3 position = vec3(vUV, depth);\n vec3 normal = normalFromDepth(depth, vUV);\n float radiusDepth = radius / depth;\n float occlusion = 0.0;\n\n vec3 ray;\n vec3 hemiRay;\n float occlusionDepth;\n float difference;\n\n for (int i = 0; i < SAMPLES; i++)\n {\n ray = radiusDepth * reflect(sampleSphere[i], random);\n hemiRay = position + dot(ray, normal) * ray;\n\n occlusionDepth = texture2D(textureSampler, clamp(hemiRay.xy, 0.0, 1.0)).r;\n difference = depth - occlusionDepth;\n\n occlusion += step(fallOff, difference) * (1.0 - smoothstep(fallOff, area, difference));\n }\n\n float ao = 1.0 - totalStrength * occlusion * samplesFactor;\n\n float result = clamp(ao + base, 0.0, 1.0);\n gl_FragColor.r = result;\n gl_FragColor.g = result;\n gl_FragColor.b = result;\n gl_FragColor.a = 1.0;\n}",
  13845. ssaoCombinePixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D originalColor;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n gl_FragColor = texture2D(originalColor, vUV) * texture2D(textureSampler, vUV);\n}",
  13846. volumetricLightScatteringPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nuniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\n\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\n\nvarying vec2 vUV;\n\nvoid main(void) {\n vec2 tc = vUV;\n vec2 deltaTexCoord = (tc - meshPositionOnScreen.xy);\n deltaTexCoord *= 1.0 / float(NUM_SAMPLES) * density;\n\n float illuminationDecay = 1.0;\n\n vec4 color = texture2D(lightScatteringSampler, tc) * 0.4;\n\n for(int i=0; i < NUM_SAMPLES; i++) {\n tc -= deltaTexCoord;\n vec4 sample = texture2D(lightScatteringSampler, tc) * 0.4;\n sample *= illuminationDecay * weight;\n color += sample;\n illuminationDecay *= decay;\n }\n\n vec4 realColor = texture2D(textureSampler, vUV);\n gl_FragColor = ((vec4((vec3(color.r, color.g, color.b) * exposure), 1)) + (realColor * (1.5 - 0.4)));\n}",
  13847. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n#ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n#else\n gl_FragColor = diffuseColor;\n#endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13848. 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}",
  13849. };
  13850. return Effect;
  13851. })();
  13852. BABYLON.Effect = Effect;
  13853. })(BABYLON || (BABYLON = {}));
  13854. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13855. (function (BABYLON) {
  13856. var Material = (function () {
  13857. function Material(name, scene, doNotAdd) {
  13858. this.name = name;
  13859. this.checkReadyOnEveryCall = true;
  13860. this.checkReadyOnlyOnce = false;
  13861. this.state = "";
  13862. this.alpha = 1.0;
  13863. this.backFaceCulling = true;
  13864. this._wasPreviouslyReady = false;
  13865. this._fillMode = Material.TriangleFillMode;
  13866. this.pointSize = 1.0;
  13867. this.id = name;
  13868. this._scene = scene;
  13869. if (!doNotAdd) {
  13870. scene.materials.push(this);
  13871. }
  13872. }
  13873. Object.defineProperty(Material, "TriangleFillMode", {
  13874. get: function () {
  13875. return Material._TriangleFillMode;
  13876. },
  13877. enumerable: true,
  13878. configurable: true
  13879. });
  13880. Object.defineProperty(Material, "WireFrameFillMode", {
  13881. get: function () {
  13882. return Material._WireFrameFillMode;
  13883. },
  13884. enumerable: true,
  13885. configurable: true
  13886. });
  13887. Object.defineProperty(Material, "PointFillMode", {
  13888. get: function () {
  13889. return Material._PointFillMode;
  13890. },
  13891. enumerable: true,
  13892. configurable: true
  13893. });
  13894. Object.defineProperty(Material.prototype, "wireframe", {
  13895. get: function () {
  13896. return this._fillMode === Material.WireFrameFillMode;
  13897. },
  13898. set: function (value) {
  13899. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13900. },
  13901. enumerable: true,
  13902. configurable: true
  13903. });
  13904. Object.defineProperty(Material.prototype, "pointsCloud", {
  13905. get: function () {
  13906. return this._fillMode === Material.PointFillMode;
  13907. },
  13908. set: function (value) {
  13909. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13910. },
  13911. enumerable: true,
  13912. configurable: true
  13913. });
  13914. Object.defineProperty(Material.prototype, "fillMode", {
  13915. get: function () {
  13916. return this._fillMode;
  13917. },
  13918. set: function (value) {
  13919. this._fillMode = value;
  13920. },
  13921. enumerable: true,
  13922. configurable: true
  13923. });
  13924. Material.prototype.isReady = function (mesh, useInstances) {
  13925. return true;
  13926. };
  13927. Material.prototype.getEffect = function () {
  13928. return this._effect;
  13929. };
  13930. Material.prototype.getScene = function () {
  13931. return this._scene;
  13932. };
  13933. Material.prototype.needAlphaBlending = function () {
  13934. return (this.alpha < 1.0);
  13935. };
  13936. Material.prototype.needAlphaTesting = function () {
  13937. return false;
  13938. };
  13939. Material.prototype.getAlphaTestTexture = function () {
  13940. return null;
  13941. };
  13942. Material.prototype.trackCreation = function (onCompiled, onError) {
  13943. };
  13944. Material.prototype._preBind = function () {
  13945. var engine = this._scene.getEngine();
  13946. engine.enableEffect(this._effect);
  13947. engine.setState(this.backFaceCulling);
  13948. };
  13949. Material.prototype.bind = function (world, mesh) {
  13950. this._scene._cachedMaterial = this;
  13951. if (this.onBind) {
  13952. this.onBind(this);
  13953. }
  13954. };
  13955. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13956. };
  13957. Material.prototype.unbind = function () {
  13958. };
  13959. Material.prototype.dispose = function (forceDisposeEffect) {
  13960. // Remove from scene
  13961. var index = this._scene.materials.indexOf(this);
  13962. this._scene.materials.splice(index, 1);
  13963. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13964. if (forceDisposeEffect && this._effect) {
  13965. this._scene.getEngine()._releaseEffect(this._effect);
  13966. this._effect = null;
  13967. }
  13968. // Callback
  13969. if (this.onDispose) {
  13970. this.onDispose();
  13971. }
  13972. };
  13973. Material._TriangleFillMode = 0;
  13974. Material._WireFrameFillMode = 1;
  13975. Material._PointFillMode = 2;
  13976. return Material;
  13977. })();
  13978. BABYLON.Material = Material;
  13979. })(BABYLON || (BABYLON = {}));
  13980. //# sourceMappingURL=babylon.material.js.map
  13981. var BABYLON;
  13982. (function (BABYLON) {
  13983. var maxSimultaneousLights = 4;
  13984. var FresnelParameters = (function () {
  13985. function FresnelParameters() {
  13986. this.isEnabled = true;
  13987. this.leftColor = BABYLON.Color3.White();
  13988. this.rightColor = BABYLON.Color3.Black();
  13989. this.bias = 0;
  13990. this.power = 1;
  13991. }
  13992. return FresnelParameters;
  13993. })();
  13994. BABYLON.FresnelParameters = FresnelParameters;
  13995. var StandardMaterial = (function (_super) {
  13996. __extends(StandardMaterial, _super);
  13997. function StandardMaterial(name, scene) {
  13998. var _this = this;
  13999. _super.call(this, name, scene);
  14000. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14001. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14002. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14003. this.specularPower = 64;
  14004. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14005. this.useAlphaFromDiffuseTexture = false;
  14006. this.useSpecularOverAlpha = true;
  14007. this.fogEnabled = true;
  14008. this._cachedDefines = null;
  14009. this._renderTargets = new BABYLON.SmartArray(16);
  14010. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14011. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14012. this._scaledDiffuse = new BABYLON.Color3();
  14013. this._scaledSpecular = new BABYLON.Color3();
  14014. this.getRenderTargetTextures = function () {
  14015. _this._renderTargets.reset();
  14016. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14017. _this._renderTargets.push(_this.reflectionTexture);
  14018. }
  14019. return _this._renderTargets;
  14020. };
  14021. }
  14022. StandardMaterial.prototype.needAlphaBlending = function () {
  14023. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14024. };
  14025. StandardMaterial.prototype.needAlphaTesting = function () {
  14026. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14027. };
  14028. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14029. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14030. };
  14031. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14032. return this.diffuseTexture;
  14033. };
  14034. // Methods
  14035. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14036. if (this.checkReadyOnlyOnce) {
  14037. if (this._wasPreviouslyReady) {
  14038. return true;
  14039. }
  14040. }
  14041. var scene = this.getScene();
  14042. if (!this.checkReadyOnEveryCall) {
  14043. if (this._renderId === scene.getRenderId()) {
  14044. return true;
  14045. }
  14046. }
  14047. var engine = scene.getEngine();
  14048. var defines = [];
  14049. var fallbacks = new BABYLON.EffectFallbacks();
  14050. var needNormals = false;
  14051. var needUVs = false;
  14052. // Textures
  14053. if (scene.texturesEnabled) {
  14054. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14055. if (!this.diffuseTexture.isReady()) {
  14056. return false;
  14057. }
  14058. else {
  14059. needUVs = true;
  14060. defines.push("#define DIFFUSE");
  14061. }
  14062. }
  14063. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14064. if (!this.ambientTexture.isReady()) {
  14065. return false;
  14066. }
  14067. else {
  14068. needUVs = true;
  14069. defines.push("#define AMBIENT");
  14070. }
  14071. }
  14072. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14073. if (!this.opacityTexture.isReady()) {
  14074. return false;
  14075. }
  14076. else {
  14077. needUVs = true;
  14078. defines.push("#define OPACITY");
  14079. if (this.opacityTexture.getAlphaFromRGB) {
  14080. defines.push("#define OPACITYRGB");
  14081. }
  14082. }
  14083. }
  14084. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14085. if (!this.reflectionTexture.isReady()) {
  14086. return false;
  14087. }
  14088. else {
  14089. needNormals = true;
  14090. needUVs = true;
  14091. defines.push("#define REFLECTION");
  14092. fallbacks.addFallback(0, "REFLECTION");
  14093. }
  14094. }
  14095. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14096. if (!this.emissiveTexture.isReady()) {
  14097. return false;
  14098. }
  14099. else {
  14100. needUVs = true;
  14101. defines.push("#define EMISSIVE");
  14102. }
  14103. }
  14104. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14105. if (!this.specularTexture.isReady()) {
  14106. return false;
  14107. }
  14108. else {
  14109. needUVs = true;
  14110. defines.push("#define SPECULAR");
  14111. fallbacks.addFallback(0, "SPECULAR");
  14112. }
  14113. }
  14114. }
  14115. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14116. if (!this.bumpTexture.isReady()) {
  14117. return false;
  14118. }
  14119. else {
  14120. needUVs = true;
  14121. defines.push("#define BUMP");
  14122. fallbacks.addFallback(0, "BUMP");
  14123. }
  14124. }
  14125. // Effect
  14126. if (this.useSpecularOverAlpha) {
  14127. defines.push("#define SPECULAROVERALPHA");
  14128. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14129. }
  14130. if (scene.clipPlane) {
  14131. defines.push("#define CLIPPLANE");
  14132. }
  14133. if (engine.getAlphaTesting()) {
  14134. defines.push("#define ALPHATEST");
  14135. }
  14136. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14137. defines.push("#define ALPHAFROMDIFFUSE");
  14138. }
  14139. // Point size
  14140. if (this.pointsCloud || scene.forcePointsCloud) {
  14141. defines.push("#define POINTSIZE");
  14142. }
  14143. // Fog
  14144. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14145. defines.push("#define FOG");
  14146. fallbacks.addFallback(1, "FOG");
  14147. }
  14148. var shadowsActivated = false;
  14149. var lightIndex = 0;
  14150. if (scene.lightsEnabled) {
  14151. for (var index = 0; index < scene.lights.length; index++) {
  14152. var light = scene.lights[index];
  14153. if (!light.isEnabled()) {
  14154. continue;
  14155. }
  14156. // Excluded check
  14157. if (light._excludedMeshesIds.length > 0) {
  14158. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14159. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14160. if (excludedMesh) {
  14161. light.excludedMeshes.push(excludedMesh);
  14162. }
  14163. }
  14164. light._excludedMeshesIds = [];
  14165. }
  14166. // Included check
  14167. if (light._includedOnlyMeshesIds.length > 0) {
  14168. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14169. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14170. if (includedOnlyMesh) {
  14171. light.includedOnlyMeshes.push(includedOnlyMesh);
  14172. }
  14173. }
  14174. light._includedOnlyMeshesIds = [];
  14175. }
  14176. if (!light.canAffectMesh(mesh)) {
  14177. continue;
  14178. }
  14179. needNormals = true;
  14180. defines.push("#define LIGHT" + lightIndex);
  14181. if (lightIndex > 0) {
  14182. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14183. }
  14184. var type;
  14185. if (light instanceof BABYLON.SpotLight) {
  14186. type = "#define SPOTLIGHT" + lightIndex;
  14187. }
  14188. else if (light instanceof BABYLON.HemisphericLight) {
  14189. type = "#define HEMILIGHT" + lightIndex;
  14190. }
  14191. else {
  14192. type = "#define POINTDIRLIGHT" + lightIndex;
  14193. }
  14194. defines.push(type);
  14195. if (lightIndex > 0) {
  14196. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14197. }
  14198. // Shadows
  14199. if (scene.shadowsEnabled) {
  14200. var shadowGenerator = light.getShadowGenerator();
  14201. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14202. defines.push("#define SHADOW" + lightIndex);
  14203. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14204. if (!shadowsActivated) {
  14205. defines.push("#define SHADOWS");
  14206. shadowsActivated = true;
  14207. }
  14208. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14209. defines.push("#define SHADOWVSM" + lightIndex);
  14210. if (lightIndex > 0) {
  14211. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14212. }
  14213. }
  14214. if (shadowGenerator.usePoissonSampling) {
  14215. defines.push("#define SHADOWPCF" + lightIndex);
  14216. if (lightIndex > 0) {
  14217. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14218. }
  14219. }
  14220. }
  14221. }
  14222. lightIndex++;
  14223. if (lightIndex === maxSimultaneousLights)
  14224. break;
  14225. }
  14226. }
  14227. if (StandardMaterial.FresnelEnabled) {
  14228. // Fresnel
  14229. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14230. var fresnelRank = 1;
  14231. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14232. defines.push("#define DIFFUSEFRESNEL");
  14233. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14234. fresnelRank++;
  14235. }
  14236. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14237. defines.push("#define OPACITYFRESNEL");
  14238. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14239. fresnelRank++;
  14240. }
  14241. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14242. defines.push("#define REFLECTIONFRESNEL");
  14243. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14244. fresnelRank++;
  14245. }
  14246. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14247. defines.push("#define EMISSIVEFRESNEL");
  14248. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14249. fresnelRank++;
  14250. }
  14251. needNormals = true;
  14252. defines.push("#define FRESNEL");
  14253. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14254. }
  14255. }
  14256. // Attribs
  14257. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14258. if (mesh) {
  14259. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14260. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14261. defines.push("#define NORMAL");
  14262. }
  14263. if (needUVs) {
  14264. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14265. attribs.push(BABYLON.VertexBuffer.UVKind);
  14266. defines.push("#define UV1");
  14267. }
  14268. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14269. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14270. defines.push("#define UV2");
  14271. }
  14272. }
  14273. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14274. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14275. defines.push("#define VERTEXCOLOR");
  14276. if (mesh.hasVertexAlpha) {
  14277. defines.push("#define VERTEXALPHA");
  14278. }
  14279. }
  14280. if (mesh.useBones) {
  14281. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14282. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14283. defines.push("#define BONES");
  14284. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14285. defines.push("#define BONES4");
  14286. fallbacks.addFallback(0, "BONES4");
  14287. }
  14288. // Instances
  14289. if (useInstances) {
  14290. defines.push("#define INSTANCES");
  14291. attribs.push("world0");
  14292. attribs.push("world1");
  14293. attribs.push("world2");
  14294. attribs.push("world3");
  14295. }
  14296. }
  14297. // Get correct effect
  14298. var join = defines.join("\n");
  14299. if (this._cachedDefines !== join) {
  14300. this._cachedDefines = join;
  14301. scene.resetCachedMaterial();
  14302. // Legacy browser patch
  14303. var shaderName = "default";
  14304. if (!scene.getEngine().getCaps().standardDerivatives) {
  14305. shaderName = "legacydefault";
  14306. }
  14307. 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", "shadowsInfo0", "shadowsInfo1", "shadowsInfo2", "shadowsInfo3", "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);
  14308. }
  14309. if (!this._effect.isReady()) {
  14310. return false;
  14311. }
  14312. this._renderId = scene.getRenderId();
  14313. this._wasPreviouslyReady = true;
  14314. return true;
  14315. };
  14316. StandardMaterial.prototype.unbind = function () {
  14317. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14318. this._effect.setTexture("reflection2DSampler", null);
  14319. }
  14320. };
  14321. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14322. this._effect.setMatrix("world", world);
  14323. };
  14324. StandardMaterial.prototype.bind = function (world, mesh) {
  14325. var scene = this.getScene();
  14326. // Matrices
  14327. this.bindOnlyWorldMatrix(world);
  14328. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14329. // Bones
  14330. if (mesh.useBones) {
  14331. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14332. }
  14333. if (scene.getCachedMaterial() !== this) {
  14334. if (StandardMaterial.FresnelEnabled) {
  14335. // Fresnel
  14336. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14337. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14338. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14339. }
  14340. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14341. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14342. }
  14343. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14344. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14345. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14346. }
  14347. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14348. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14349. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14350. }
  14351. }
  14352. // Textures
  14353. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14354. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14355. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14356. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14357. }
  14358. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14359. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14360. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14361. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14362. }
  14363. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14364. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14365. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14366. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14367. }
  14368. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14369. if (this.reflectionTexture.isCube) {
  14370. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14371. }
  14372. else {
  14373. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14374. }
  14375. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14376. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14377. }
  14378. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14379. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14380. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14381. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14382. }
  14383. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14384. this._effect.setTexture("specularSampler", this.specularTexture);
  14385. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14386. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14387. }
  14388. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14389. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14390. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14391. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14392. }
  14393. // Clip plane
  14394. if (scene.clipPlane) {
  14395. var clipPlane = scene.clipPlane;
  14396. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14397. }
  14398. // Point size
  14399. if (this.pointsCloud) {
  14400. this._effect.setFloat("pointSize", this.pointSize);
  14401. }
  14402. // Colors
  14403. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14404. // Scaling down color according to emissive
  14405. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14406. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14407. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14408. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14409. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14410. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14411. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14412. }
  14413. // Scaling down color according to emissive
  14414. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14415. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14416. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14417. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14418. if (scene.lightsEnabled) {
  14419. var lightIndex = 0;
  14420. for (var index = 0; index < scene.lights.length; index++) {
  14421. var light = scene.lights[index];
  14422. if (!light.isEnabled()) {
  14423. continue;
  14424. }
  14425. if (!light.canAffectMesh(mesh)) {
  14426. continue;
  14427. }
  14428. if (light instanceof BABYLON.PointLight) {
  14429. // Point Light
  14430. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14431. }
  14432. else if (light instanceof BABYLON.DirectionalLight) {
  14433. // Directional Light
  14434. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14435. }
  14436. else if (light instanceof BABYLON.SpotLight) {
  14437. // Spot Light
  14438. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14439. }
  14440. else if (light instanceof BABYLON.HemisphericLight) {
  14441. // Hemispheric Light
  14442. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14443. }
  14444. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14445. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14446. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14447. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14448. // Shadows
  14449. if (scene.shadowsEnabled) {
  14450. var shadowGenerator = light.getShadowGenerator();
  14451. if (mesh.receiveShadows && shadowGenerator) {
  14452. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14453. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14454. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14455. }
  14456. }
  14457. lightIndex++;
  14458. if (lightIndex === maxSimultaneousLights)
  14459. break;
  14460. }
  14461. }
  14462. // View
  14463. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14464. this._effect.setMatrix("view", scene.getViewMatrix());
  14465. }
  14466. // Fog
  14467. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14468. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14469. this._effect.setColor3("vFogColor", scene.fogColor);
  14470. }
  14471. _super.prototype.bind.call(this, world, mesh);
  14472. };
  14473. StandardMaterial.prototype.getAnimatables = function () {
  14474. var results = [];
  14475. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14476. results.push(this.diffuseTexture);
  14477. }
  14478. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14479. results.push(this.ambientTexture);
  14480. }
  14481. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14482. results.push(this.opacityTexture);
  14483. }
  14484. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14485. results.push(this.reflectionTexture);
  14486. }
  14487. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14488. results.push(this.emissiveTexture);
  14489. }
  14490. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14491. results.push(this.specularTexture);
  14492. }
  14493. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14494. results.push(this.bumpTexture);
  14495. }
  14496. return results;
  14497. };
  14498. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14499. if (this.diffuseTexture) {
  14500. this.diffuseTexture.dispose();
  14501. }
  14502. if (this.ambientTexture) {
  14503. this.ambientTexture.dispose();
  14504. }
  14505. if (this.opacityTexture) {
  14506. this.opacityTexture.dispose();
  14507. }
  14508. if (this.reflectionTexture) {
  14509. this.reflectionTexture.dispose();
  14510. }
  14511. if (this.emissiveTexture) {
  14512. this.emissiveTexture.dispose();
  14513. }
  14514. if (this.specularTexture) {
  14515. this.specularTexture.dispose();
  14516. }
  14517. if (this.bumpTexture) {
  14518. this.bumpTexture.dispose();
  14519. }
  14520. _super.prototype.dispose.call(this, forceDisposeEffect);
  14521. };
  14522. StandardMaterial.prototype.clone = function (name) {
  14523. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14524. // Base material
  14525. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14526. newStandardMaterial.alpha = this.alpha;
  14527. newStandardMaterial.fillMode = this.fillMode;
  14528. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14529. // Standard material
  14530. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14531. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14532. }
  14533. if (this.ambientTexture && this.ambientTexture.clone) {
  14534. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14535. }
  14536. if (this.opacityTexture && this.opacityTexture.clone) {
  14537. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14538. }
  14539. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14540. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14541. }
  14542. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14543. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14544. }
  14545. if (this.specularTexture && this.specularTexture.clone) {
  14546. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14547. }
  14548. if (this.bumpTexture && this.bumpTexture.clone) {
  14549. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14550. }
  14551. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14552. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14553. newStandardMaterial.specularColor = this.specularColor.clone();
  14554. newStandardMaterial.specularPower = this.specularPower;
  14555. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14556. return newStandardMaterial;
  14557. };
  14558. // Statics
  14559. // Flags used to enable or disable a type of texture for all Standard Materials
  14560. StandardMaterial.DiffuseTextureEnabled = true;
  14561. StandardMaterial.AmbientTextureEnabled = true;
  14562. StandardMaterial.OpacityTextureEnabled = true;
  14563. StandardMaterial.ReflectionTextureEnabled = true;
  14564. StandardMaterial.EmissiveTextureEnabled = true;
  14565. StandardMaterial.SpecularTextureEnabled = true;
  14566. StandardMaterial.BumpTextureEnabled = true;
  14567. StandardMaterial.FresnelEnabled = true;
  14568. return StandardMaterial;
  14569. })(BABYLON.Material);
  14570. BABYLON.StandardMaterial = StandardMaterial;
  14571. })(BABYLON || (BABYLON = {}));
  14572. //# sourceMappingURL=babylon.standardMaterial.js.map
  14573. var BABYLON;
  14574. (function (BABYLON) {
  14575. var MultiMaterial = (function (_super) {
  14576. __extends(MultiMaterial, _super);
  14577. function MultiMaterial(name, scene) {
  14578. _super.call(this, name, scene, true);
  14579. this.subMaterials = new Array();
  14580. scene.multiMaterials.push(this);
  14581. }
  14582. // Properties
  14583. MultiMaterial.prototype.getSubMaterial = function (index) {
  14584. if (index < 0 || index >= this.subMaterials.length) {
  14585. return this.getScene().defaultMaterial;
  14586. }
  14587. return this.subMaterials[index];
  14588. };
  14589. // Methods
  14590. MultiMaterial.prototype.isReady = function (mesh) {
  14591. for (var index = 0; index < this.subMaterials.length; index++) {
  14592. var subMaterial = this.subMaterials[index];
  14593. if (subMaterial) {
  14594. if (!this.subMaterials[index].isReady(mesh)) {
  14595. return false;
  14596. }
  14597. }
  14598. }
  14599. return true;
  14600. };
  14601. return MultiMaterial;
  14602. })(BABYLON.Material);
  14603. BABYLON.MultiMaterial = MultiMaterial;
  14604. })(BABYLON || (BABYLON = {}));
  14605. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14606. (function (BABYLON) {
  14607. var Database = (function () {
  14608. function Database(urlToScene, callbackManifestChecked) {
  14609. // Handling various flavors of prefixed version of IndexedDB
  14610. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14611. this.callbackManifestChecked = callbackManifestChecked;
  14612. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14613. this.db = null;
  14614. this.enableSceneOffline = false;
  14615. this.enableTexturesOffline = false;
  14616. this.manifestVersionFound = 0;
  14617. this.mustUpdateRessources = false;
  14618. this.hasReachedQuota = false;
  14619. this.checkManifestFile();
  14620. }
  14621. Database.prototype.checkManifestFile = function () {
  14622. var _this = this;
  14623. function noManifestFile() {
  14624. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14625. that.enableSceneOffline = false;
  14626. that.enableTexturesOffline = false;
  14627. that.callbackManifestChecked(false);
  14628. }
  14629. var that = this;
  14630. var manifestURL = this.currentSceneUrl + ".manifest";
  14631. var xhr = new XMLHttpRequest();
  14632. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14633. xhr.open("GET", manifestURLTimeStamped, true);
  14634. xhr.addEventListener("load", function () {
  14635. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14636. try {
  14637. var manifestFile = JSON.parse(xhr.response);
  14638. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14639. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14640. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14641. _this.manifestVersionFound = manifestFile.version;
  14642. }
  14643. if (_this.callbackManifestChecked) {
  14644. _this.callbackManifestChecked(true);
  14645. }
  14646. }
  14647. catch (ex) {
  14648. noManifestFile();
  14649. }
  14650. }
  14651. else {
  14652. noManifestFile();
  14653. }
  14654. }, false);
  14655. xhr.addEventListener("error", function (event) {
  14656. noManifestFile();
  14657. }, false);
  14658. try {
  14659. xhr.send();
  14660. }
  14661. catch (ex) {
  14662. BABYLON.Tools.Error("Error on XHR send request.");
  14663. that.callbackManifestChecked(false);
  14664. }
  14665. };
  14666. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14667. var _this = this;
  14668. function handleError() {
  14669. that.isSupported = false;
  14670. if (errorCallback)
  14671. errorCallback();
  14672. }
  14673. var that = this;
  14674. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14675. // Your browser doesn't support IndexedDB
  14676. this.isSupported = false;
  14677. if (errorCallback)
  14678. errorCallback();
  14679. }
  14680. else {
  14681. // If the DB hasn't been opened or created yet
  14682. if (!this.db) {
  14683. this.hasReachedQuota = false;
  14684. this.isSupported = true;
  14685. var request = this.idbFactory.open("babylonjs", 1);
  14686. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14687. request.onerror = function (event) {
  14688. handleError();
  14689. };
  14690. // executes when a version change transaction cannot complete due to other active transactions
  14691. request.onblocked = function (event) {
  14692. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14693. handleError();
  14694. };
  14695. // DB has been opened successfully
  14696. request.onsuccess = function (event) {
  14697. _this.db = request.result;
  14698. successCallback();
  14699. };
  14700. // Initialization of the DB. Creating Scenes & Textures stores
  14701. request.onupgradeneeded = function (event) {
  14702. _this.db = (event.target).result;
  14703. try {
  14704. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14705. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14706. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14707. }
  14708. catch (ex) {
  14709. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14710. handleError();
  14711. }
  14712. };
  14713. }
  14714. else {
  14715. if (successCallback)
  14716. successCallback();
  14717. }
  14718. }
  14719. };
  14720. Database.prototype.loadImageFromDB = function (url, image) {
  14721. var _this = this;
  14722. var completeURL = Database.ReturnFullUrlLocation(url);
  14723. var saveAndLoadImage = function () {
  14724. if (!_this.hasReachedQuota && _this.db !== null) {
  14725. // the texture is not yet in the DB, let's try to save it
  14726. _this._saveImageIntoDBAsync(completeURL, image);
  14727. }
  14728. else {
  14729. image.src = url;
  14730. }
  14731. };
  14732. if (!this.mustUpdateRessources) {
  14733. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14734. }
  14735. else {
  14736. saveAndLoadImage();
  14737. }
  14738. };
  14739. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14740. if (this.isSupported && this.db !== null) {
  14741. var texture;
  14742. var transaction = this.db.transaction(["textures"]);
  14743. transaction.onabort = function (event) {
  14744. image.src = url;
  14745. };
  14746. transaction.oncomplete = function (event) {
  14747. var blobTextureURL;
  14748. if (texture) {
  14749. var URL = window.URL || window.webkitURL;
  14750. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14751. image.onerror = function () {
  14752. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14753. image.src = url;
  14754. };
  14755. image.src = blobTextureURL;
  14756. }
  14757. else {
  14758. notInDBCallback();
  14759. }
  14760. };
  14761. var getRequest = transaction.objectStore("textures").get(url);
  14762. getRequest.onsuccess = function (event) {
  14763. texture = (event.target).result;
  14764. };
  14765. getRequest.onerror = function (event) {
  14766. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14767. image.src = url;
  14768. };
  14769. }
  14770. else {
  14771. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14772. image.src = url;
  14773. }
  14774. };
  14775. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14776. var _this = this;
  14777. if (this.isSupported) {
  14778. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14779. var generateBlobUrl = function () {
  14780. var blobTextureURL;
  14781. if (blob) {
  14782. var URL = window.URL || window.webkitURL;
  14783. try {
  14784. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14785. }
  14786. catch (ex) {
  14787. blobTextureURL = URL.createObjectURL(blob);
  14788. }
  14789. }
  14790. image.src = blobTextureURL;
  14791. };
  14792. if (Database.isUASupportingBlobStorage) {
  14793. var xhr = new XMLHttpRequest(), blob;
  14794. xhr.open("GET", url, true);
  14795. xhr.responseType = "blob";
  14796. xhr.addEventListener("load", function () {
  14797. if (xhr.status === 200) {
  14798. // Blob as response (XHR2)
  14799. blob = xhr.response;
  14800. var transaction = _this.db.transaction(["textures"], "readwrite");
  14801. // the transaction could abort because of a QuotaExceededError error
  14802. transaction.onabort = function (event) {
  14803. try {
  14804. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14805. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14806. this.hasReachedQuota = true;
  14807. }
  14808. }
  14809. catch (ex) {
  14810. }
  14811. generateBlobUrl();
  14812. };
  14813. transaction.oncomplete = function (event) {
  14814. generateBlobUrl();
  14815. };
  14816. var newTexture = { textureUrl: url, data: blob };
  14817. try {
  14818. // Put the blob into the dabase
  14819. var addRequest = transaction.objectStore("textures").put(newTexture);
  14820. addRequest.onsuccess = function (event) {
  14821. };
  14822. addRequest.onerror = function (event) {
  14823. generateBlobUrl();
  14824. };
  14825. }
  14826. catch (ex) {
  14827. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14828. if (ex.code === 25) {
  14829. Database.isUASupportingBlobStorage = false;
  14830. }
  14831. image.src = url;
  14832. }
  14833. }
  14834. else {
  14835. image.src = url;
  14836. }
  14837. }, false);
  14838. xhr.addEventListener("error", function (event) {
  14839. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14840. image.src = url;
  14841. }, false);
  14842. xhr.send();
  14843. }
  14844. else {
  14845. image.src = url;
  14846. }
  14847. }
  14848. else {
  14849. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14850. image.src = url;
  14851. }
  14852. };
  14853. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14854. var _this = this;
  14855. var updateVersion = function (event) {
  14856. // the version is not yet in the DB or we need to update it
  14857. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14858. };
  14859. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14860. };
  14861. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14862. var _this = this;
  14863. if (this.isSupported) {
  14864. var version;
  14865. try {
  14866. var transaction = this.db.transaction(["versions"]);
  14867. transaction.oncomplete = function (event) {
  14868. if (version) {
  14869. // If the version in the JSON file is > than the version in DB
  14870. if (_this.manifestVersionFound > version.data) {
  14871. _this.mustUpdateRessources = true;
  14872. updateInDBCallback();
  14873. }
  14874. else {
  14875. callback(version.data);
  14876. }
  14877. }
  14878. else {
  14879. _this.mustUpdateRessources = true;
  14880. updateInDBCallback();
  14881. }
  14882. };
  14883. transaction.onabort = function (event) {
  14884. callback(-1);
  14885. };
  14886. var getRequest = transaction.objectStore("versions").get(url);
  14887. getRequest.onsuccess = function (event) {
  14888. version = (event.target).result;
  14889. };
  14890. getRequest.onerror = function (event) {
  14891. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14892. callback(-1);
  14893. };
  14894. }
  14895. catch (ex) {
  14896. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14897. callback(-1);
  14898. }
  14899. }
  14900. else {
  14901. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14902. callback(-1);
  14903. }
  14904. };
  14905. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14906. var _this = this;
  14907. if (this.isSupported && !this.hasReachedQuota) {
  14908. try {
  14909. // Open a transaction to the database
  14910. var transaction = this.db.transaction(["versions"], "readwrite");
  14911. // the transaction could abort because of a QuotaExceededError error
  14912. transaction.onabort = function (event) {
  14913. try {
  14914. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14915. _this.hasReachedQuota = true;
  14916. }
  14917. }
  14918. catch (ex) {
  14919. }
  14920. callback(-1);
  14921. };
  14922. transaction.oncomplete = function (event) {
  14923. callback(_this.manifestVersionFound);
  14924. };
  14925. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14926. // Put the scene into the database
  14927. var addRequest = transaction.objectStore("versions").put(newVersion);
  14928. addRequest.onsuccess = function (event) {
  14929. };
  14930. addRequest.onerror = function (event) {
  14931. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14932. };
  14933. }
  14934. catch (ex) {
  14935. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14936. callback(-1);
  14937. }
  14938. }
  14939. else {
  14940. callback(-1);
  14941. }
  14942. };
  14943. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14944. var _this = this;
  14945. var completeUrl = Database.ReturnFullUrlLocation(url);
  14946. var saveAndLoadFile = function (event) {
  14947. // the scene is not yet in the DB, let's try to save it
  14948. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14949. };
  14950. this._checkVersionFromDB(completeUrl, function (version) {
  14951. if (version !== -1) {
  14952. if (!_this.mustUpdateRessources) {
  14953. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14954. }
  14955. else {
  14956. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14957. }
  14958. }
  14959. else {
  14960. errorCallback();
  14961. }
  14962. });
  14963. };
  14964. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14965. if (this.isSupported) {
  14966. var targetStore;
  14967. if (url.indexOf(".babylon") !== -1) {
  14968. targetStore = "scenes";
  14969. }
  14970. else {
  14971. targetStore = "textures";
  14972. }
  14973. var file;
  14974. var transaction = this.db.transaction([targetStore]);
  14975. transaction.oncomplete = function (event) {
  14976. if (file) {
  14977. callback(file.data);
  14978. }
  14979. else {
  14980. notInDBCallback();
  14981. }
  14982. };
  14983. transaction.onabort = function (event) {
  14984. notInDBCallback();
  14985. };
  14986. var getRequest = transaction.objectStore(targetStore).get(url);
  14987. getRequest.onsuccess = function (event) {
  14988. file = (event.target).result;
  14989. };
  14990. getRequest.onerror = function (event) {
  14991. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14992. notInDBCallback();
  14993. };
  14994. }
  14995. else {
  14996. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14997. callback();
  14998. }
  14999. };
  15000. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15001. var _this = this;
  15002. if (this.isSupported) {
  15003. var targetStore;
  15004. if (url.indexOf(".babylon") !== -1) {
  15005. targetStore = "scenes";
  15006. }
  15007. else {
  15008. targetStore = "textures";
  15009. }
  15010. // Create XHR
  15011. var xhr = new XMLHttpRequest(), fileData;
  15012. xhr.open("GET", url, true);
  15013. if (useArrayBuffer) {
  15014. xhr.responseType = "arraybuffer";
  15015. }
  15016. xhr.onprogress = progressCallback;
  15017. xhr.addEventListener("load", function () {
  15018. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15019. // Blob as response (XHR2)
  15020. //fileData = xhr.responseText;
  15021. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15022. if (!_this.hasReachedQuota) {
  15023. // Open a transaction to the database
  15024. var transaction = _this.db.transaction([targetStore], "readwrite");
  15025. // the transaction could abort because of a QuotaExceededError error
  15026. transaction.onabort = function (event) {
  15027. try {
  15028. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15029. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15030. this.hasReachedQuota = true;
  15031. }
  15032. }
  15033. catch (ex) {
  15034. }
  15035. callback(fileData);
  15036. };
  15037. transaction.oncomplete = function (event) {
  15038. callback(fileData);
  15039. };
  15040. var newFile;
  15041. if (targetStore === "scenes") {
  15042. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15043. }
  15044. else {
  15045. newFile = { textureUrl: url, data: fileData };
  15046. }
  15047. try {
  15048. // Put the scene into the database
  15049. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15050. addRequest.onsuccess = function (event) {
  15051. };
  15052. addRequest.onerror = function (event) {
  15053. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15054. };
  15055. }
  15056. catch (ex) {
  15057. callback(fileData);
  15058. }
  15059. }
  15060. else {
  15061. callback(fileData);
  15062. }
  15063. }
  15064. else {
  15065. callback();
  15066. }
  15067. }, false);
  15068. xhr.addEventListener("error", function (event) {
  15069. BABYLON.Tools.Error("error on XHR request.");
  15070. callback();
  15071. }, false);
  15072. xhr.send();
  15073. }
  15074. else {
  15075. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15076. callback();
  15077. }
  15078. };
  15079. Database.isUASupportingBlobStorage = true;
  15080. Database.parseURL = function (url) {
  15081. var a = document.createElement('a');
  15082. a.href = url;
  15083. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15084. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15085. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15086. return absLocation;
  15087. };
  15088. Database.ReturnFullUrlLocation = function (url) {
  15089. if (url.indexOf("http:/") === -1) {
  15090. return (BABYLON.Database.parseURL(window.location.href) + url);
  15091. }
  15092. else {
  15093. return url;
  15094. }
  15095. };
  15096. return Database;
  15097. })();
  15098. BABYLON.Database = Database;
  15099. })(BABYLON || (BABYLON = {}));
  15100. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15101. (function (BABYLON) {
  15102. var SpriteManager = (function () {
  15103. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15104. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15105. this.name = name;
  15106. this.cellSize = cellSize;
  15107. this.sprites = new Array();
  15108. this.renderingGroupId = 0;
  15109. this.fogEnabled = true;
  15110. this._vertexDeclaration = [3, 4, 4, 4];
  15111. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15112. this._capacity = capacity;
  15113. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15114. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15115. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15116. // temp fix for correct 'pixelated' appearance
  15117. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  15118. this._spriteTexture.anisotropicFilteringLevel = 1;
  15119. }
  15120. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15121. this._scene = scene;
  15122. this._scene.spriteManagers.push(this);
  15123. // VBO
  15124. this._vertexDeclaration = [3, 4, 4, 4];
  15125. this._vertexStrideSize = 15 * 4;
  15126. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15127. var indices = [];
  15128. var index = 0;
  15129. for (var count = 0; count < capacity; count++) {
  15130. indices.push(index);
  15131. indices.push(index + 1);
  15132. indices.push(index + 2);
  15133. indices.push(index);
  15134. indices.push(index + 2);
  15135. indices.push(index + 3);
  15136. index += 4;
  15137. }
  15138. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15139. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15140. // Effects
  15141. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15142. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15143. }
  15144. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15145. var arrayOffset = index * 15;
  15146. if (offsetX === 0)
  15147. offsetX = this._epsilon;
  15148. else if (offsetX === 1)
  15149. offsetX = 1 - this._epsilon;
  15150. if (offsetY === 0)
  15151. offsetY = this._epsilon;
  15152. else if (offsetY === 1)
  15153. offsetY = 1 - this._epsilon;
  15154. this._vertices[arrayOffset] = sprite.position.x;
  15155. this._vertices[arrayOffset + 1] = sprite.position.y;
  15156. this._vertices[arrayOffset + 2] = sprite.position.z;
  15157. this._vertices[arrayOffset + 3] = sprite.angle;
  15158. this._vertices[arrayOffset + 4] = sprite.size;
  15159. this._vertices[arrayOffset + 5] = offsetX;
  15160. this._vertices[arrayOffset + 6] = offsetY;
  15161. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15162. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15163. var offset = (sprite.cellIndex / rowSize) >> 0;
  15164. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15165. this._vertices[arrayOffset + 10] = offset;
  15166. // Color
  15167. this._vertices[arrayOffset + 11] = sprite.color.r;
  15168. this._vertices[arrayOffset + 12] = sprite.color.g;
  15169. this._vertices[arrayOffset + 13] = sprite.color.b;
  15170. this._vertices[arrayOffset + 14] = sprite.color.a;
  15171. };
  15172. SpriteManager.prototype.render = function () {
  15173. // Check
  15174. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15175. return;
  15176. var engine = this._scene.getEngine();
  15177. var baseSize = this._spriteTexture.getBaseSize();
  15178. // Sprites
  15179. var deltaTime = engine.getDeltaTime();
  15180. var max = Math.min(this._capacity, this.sprites.length);
  15181. var rowSize = baseSize.width / this.cellSize;
  15182. var offset = 0;
  15183. for (var index = 0; index < max; index++) {
  15184. var sprite = this.sprites[index];
  15185. if (!sprite) {
  15186. continue;
  15187. }
  15188. sprite._animate(deltaTime);
  15189. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15190. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15191. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15192. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15193. }
  15194. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15195. // Render
  15196. var effect = this._effectBase;
  15197. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15198. effect = this._effectFog;
  15199. }
  15200. engine.enableEffect(effect);
  15201. var viewMatrix = this._scene.getViewMatrix();
  15202. effect.setTexture("diffuseSampler", this._spriteTexture);
  15203. effect.setMatrix("view", viewMatrix);
  15204. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15205. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15206. // Fog
  15207. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15208. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15209. effect.setColor3("vFogColor", this._scene.fogColor);
  15210. }
  15211. // VBOs
  15212. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15213. // Draw order
  15214. effect.setBool("alphaTest", true);
  15215. engine.setColorWrite(false);
  15216. engine.draw(true, 0, max * 6);
  15217. engine.setColorWrite(true);
  15218. effect.setBool("alphaTest", false);
  15219. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15220. engine.draw(true, 0, max * 6);
  15221. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15222. };
  15223. SpriteManager.prototype.dispose = function () {
  15224. if (this._vertexBuffer) {
  15225. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15226. this._vertexBuffer = null;
  15227. }
  15228. if (this._indexBuffer) {
  15229. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15230. this._indexBuffer = null;
  15231. }
  15232. if (this._spriteTexture) {
  15233. this._spriteTexture.dispose();
  15234. this._spriteTexture = null;
  15235. }
  15236. // Remove from scene
  15237. var index = this._scene.spriteManagers.indexOf(this);
  15238. this._scene.spriteManagers.splice(index, 1);
  15239. // Callback
  15240. if (this.onDispose) {
  15241. this.onDispose();
  15242. }
  15243. };
  15244. return SpriteManager;
  15245. })();
  15246. BABYLON.SpriteManager = SpriteManager;
  15247. })(BABYLON || (BABYLON = {}));
  15248. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15249. (function (BABYLON) {
  15250. var Sprite = (function () {
  15251. function Sprite(name, manager) {
  15252. this.name = name;
  15253. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15254. this.size = 1.0;
  15255. this.angle = 0;
  15256. this.cellIndex = 0;
  15257. this.invertU = 0;
  15258. this.invertV = 0;
  15259. this.animations = new Array();
  15260. this._animationStarted = false;
  15261. this._loopAnimation = false;
  15262. this._fromIndex = 0;
  15263. this._toIndex = 0;
  15264. this._delay = 0;
  15265. this._direction = 1;
  15266. this._frameCount = 0;
  15267. this._time = 0;
  15268. this._manager = manager;
  15269. this._manager.sprites.push(this);
  15270. this.position = BABYLON.Vector3.Zero();
  15271. }
  15272. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15273. this._fromIndex = from;
  15274. this._toIndex = to;
  15275. this._loopAnimation = loop;
  15276. this._delay = delay;
  15277. this._animationStarted = true;
  15278. this._direction = from < to ? 1 : -1;
  15279. this.cellIndex = from;
  15280. this._time = 0;
  15281. };
  15282. Sprite.prototype.stopAnimation = function () {
  15283. this._animationStarted = false;
  15284. };
  15285. Sprite.prototype._animate = function (deltaTime) {
  15286. if (!this._animationStarted)
  15287. return;
  15288. this._time += deltaTime;
  15289. if (this._time > this._delay) {
  15290. this._time = this._time % this._delay;
  15291. this.cellIndex += this._direction;
  15292. if (this.cellIndex == this._toIndex) {
  15293. if (this._loopAnimation) {
  15294. this.cellIndex = this._fromIndex;
  15295. }
  15296. else {
  15297. this._animationStarted = false;
  15298. if (this.disposeWhenFinishedAnimating) {
  15299. this.dispose();
  15300. }
  15301. }
  15302. }
  15303. }
  15304. };
  15305. Sprite.prototype.dispose = function () {
  15306. for (var i = 0; i < this._manager.sprites.length; i++) {
  15307. if (this._manager.sprites[i] == this) {
  15308. this._manager.sprites.splice(i, 1);
  15309. }
  15310. }
  15311. };
  15312. return Sprite;
  15313. })();
  15314. BABYLON.Sprite = Sprite;
  15315. })(BABYLON || (BABYLON = {}));
  15316. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15317. (function (BABYLON) {
  15318. var Layer = (function () {
  15319. function Layer(name, imgUrl, scene, isBackground, color) {
  15320. this.name = name;
  15321. this._vertexDeclaration = [2];
  15322. this._vertexStrideSize = 2 * 4;
  15323. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15324. this.isBackground = isBackground === undefined ? true : isBackground;
  15325. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15326. this._scene = scene;
  15327. this._scene.layers.push(this);
  15328. // VBO
  15329. var vertices = [];
  15330. vertices.push(1, 1);
  15331. vertices.push(-1, 1);
  15332. vertices.push(-1, -1);
  15333. vertices.push(1, -1);
  15334. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15335. // Indices
  15336. var indices = [];
  15337. indices.push(0);
  15338. indices.push(1);
  15339. indices.push(2);
  15340. indices.push(0);
  15341. indices.push(2);
  15342. indices.push(3);
  15343. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15344. // Effects
  15345. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15346. }
  15347. Layer.prototype.render = function () {
  15348. // Check
  15349. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15350. return;
  15351. var engine = this._scene.getEngine();
  15352. // Render
  15353. engine.enableEffect(this._effect);
  15354. engine.setState(false);
  15355. // Texture
  15356. this._effect.setTexture("textureSampler", this.texture);
  15357. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15358. // Color
  15359. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15360. // VBOs
  15361. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15362. // Draw order
  15363. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15364. engine.draw(true, 0, 6);
  15365. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15366. };
  15367. Layer.prototype.dispose = function () {
  15368. if (this._vertexBuffer) {
  15369. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15370. this._vertexBuffer = null;
  15371. }
  15372. if (this._indexBuffer) {
  15373. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15374. this._indexBuffer = null;
  15375. }
  15376. if (this.texture) {
  15377. this.texture.dispose();
  15378. this.texture = null;
  15379. }
  15380. // Remove from scene
  15381. var index = this._scene.layers.indexOf(this);
  15382. this._scene.layers.splice(index, 1);
  15383. // Callback
  15384. if (this.onDispose) {
  15385. this.onDispose();
  15386. }
  15387. };
  15388. return Layer;
  15389. })();
  15390. BABYLON.Layer = Layer;
  15391. })(BABYLON || (BABYLON = {}));
  15392. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15393. (function (BABYLON) {
  15394. var Particle = (function () {
  15395. function Particle() {
  15396. this.position = BABYLON.Vector3.Zero();
  15397. this.direction = BABYLON.Vector3.Zero();
  15398. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15399. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15400. this.lifeTime = 1.0;
  15401. this.age = 0;
  15402. this.size = 0;
  15403. this.angle = 0;
  15404. this.angularSpeed = 0;
  15405. }
  15406. Particle.prototype.copyTo = function (other) {
  15407. other.position.copyFrom(this.position);
  15408. other.direction.copyFrom(this.direction);
  15409. other.color.copyFrom(this.color);
  15410. other.colorStep.copyFrom(this.colorStep);
  15411. other.lifeTime = this.lifeTime;
  15412. other.age = this.age;
  15413. other.size = this.size;
  15414. other.angle = this.angle;
  15415. other.angularSpeed = this.angularSpeed;
  15416. };
  15417. return Particle;
  15418. })();
  15419. BABYLON.Particle = Particle;
  15420. })(BABYLON || (BABYLON = {}));
  15421. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15422. (function (BABYLON) {
  15423. var randomNumber = function (min, max) {
  15424. if (min === max) {
  15425. return (min);
  15426. }
  15427. var random = Math.random();
  15428. return ((random * (max - min)) + min);
  15429. };
  15430. var ParticleSystem = (function () {
  15431. function ParticleSystem(name, capacity, scene, customEffect) {
  15432. var _this = this;
  15433. this.name = name;
  15434. this.renderingGroupId = 0;
  15435. this.emitter = null;
  15436. this.emitRate = 10;
  15437. this.manualEmitCount = -1;
  15438. this.updateSpeed = 0.01;
  15439. this.targetStopDuration = 0;
  15440. this.disposeOnStop = false;
  15441. this.minEmitPower = 1;
  15442. this.maxEmitPower = 1;
  15443. this.minLifeTime = 1;
  15444. this.maxLifeTime = 1;
  15445. this.minSize = 1;
  15446. this.maxSize = 1;
  15447. this.minAngularSpeed = 0;
  15448. this.maxAngularSpeed = 0;
  15449. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15450. this.forceDepthWrite = false;
  15451. this.gravity = BABYLON.Vector3.Zero();
  15452. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15453. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15454. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15455. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15456. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15457. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15458. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15459. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15460. this.particles = new Array();
  15461. this._vertexDeclaration = [3, 4, 4];
  15462. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15463. this._stockParticles = new Array();
  15464. this._newPartsExcess = 0;
  15465. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15466. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15467. this._scaledDirection = BABYLON.Vector3.Zero();
  15468. this._scaledGravity = BABYLON.Vector3.Zero();
  15469. this._currentRenderId = -1;
  15470. this._started = false;
  15471. this._stopped = false;
  15472. this._actualFrame = 0;
  15473. this.id = name;
  15474. this._capacity = capacity;
  15475. this._scene = scene;
  15476. this._customEffect = customEffect;
  15477. scene.particleSystems.push(this);
  15478. // VBO
  15479. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15480. var indices = [];
  15481. var index = 0;
  15482. for (var count = 0; count < capacity; count++) {
  15483. indices.push(index);
  15484. indices.push(index + 1);
  15485. indices.push(index + 2);
  15486. indices.push(index);
  15487. indices.push(index + 2);
  15488. indices.push(index + 3);
  15489. index += 4;
  15490. }
  15491. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15492. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15493. // Default behaviors
  15494. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15495. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15496. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15497. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15498. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15499. };
  15500. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15501. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15502. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15503. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15504. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15505. };
  15506. this.updateFunction = function (particles) {
  15507. for (var index = 0; index < particles.length; index++) {
  15508. var particle = particles[index];
  15509. particle.age += _this._scaledUpdateSpeed;
  15510. if (particle.age >= particle.lifeTime) {
  15511. _this.recycleParticle(particle);
  15512. index--;
  15513. continue;
  15514. }
  15515. else {
  15516. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15517. particle.color.addInPlace(_this._scaledColorStep);
  15518. if (particle.color.a < 0)
  15519. particle.color.a = 0;
  15520. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15521. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15522. particle.position.addInPlace(_this._scaledDirection);
  15523. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15524. particle.direction.addInPlace(_this._scaledGravity);
  15525. }
  15526. }
  15527. };
  15528. }
  15529. ParticleSystem.prototype.recycleParticle = function (particle) {
  15530. var lastParticle = this.particles.pop();
  15531. if (lastParticle !== particle) {
  15532. lastParticle.copyTo(particle);
  15533. this._stockParticles.push(lastParticle);
  15534. }
  15535. };
  15536. ParticleSystem.prototype.getCapacity = function () {
  15537. return this._capacity;
  15538. };
  15539. ParticleSystem.prototype.isAlive = function () {
  15540. return this._alive;
  15541. };
  15542. ParticleSystem.prototype.isStarted = function () {
  15543. return this._started;
  15544. };
  15545. ParticleSystem.prototype.start = function () {
  15546. this._started = true;
  15547. this._stopped = false;
  15548. this._actualFrame = 0;
  15549. };
  15550. ParticleSystem.prototype.stop = function () {
  15551. this._stopped = true;
  15552. };
  15553. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15554. var offset = index * 11;
  15555. this._vertices[offset] = particle.position.x;
  15556. this._vertices[offset + 1] = particle.position.y;
  15557. this._vertices[offset + 2] = particle.position.z;
  15558. this._vertices[offset + 3] = particle.color.r;
  15559. this._vertices[offset + 4] = particle.color.g;
  15560. this._vertices[offset + 5] = particle.color.b;
  15561. this._vertices[offset + 6] = particle.color.a;
  15562. this._vertices[offset + 7] = particle.angle;
  15563. this._vertices[offset + 8] = particle.size;
  15564. this._vertices[offset + 9] = offsetX;
  15565. this._vertices[offset + 10] = offsetY;
  15566. };
  15567. ParticleSystem.prototype._update = function (newParticles) {
  15568. // Update current
  15569. this._alive = this.particles.length > 0;
  15570. this.updateFunction(this.particles);
  15571. // Add new ones
  15572. var worldMatrix;
  15573. if (this.emitter.position) {
  15574. worldMatrix = this.emitter.getWorldMatrix();
  15575. }
  15576. else {
  15577. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15578. }
  15579. for (var index = 0; index < newParticles; index++) {
  15580. if (this.particles.length === this._capacity) {
  15581. break;
  15582. }
  15583. if (this._stockParticles.length !== 0) {
  15584. var particle = this._stockParticles.pop();
  15585. particle.age = 0;
  15586. }
  15587. else {
  15588. particle = new BABYLON.Particle();
  15589. }
  15590. this.particles.push(particle);
  15591. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15592. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15593. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15594. particle.size = randomNumber(this.minSize, this.maxSize);
  15595. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15596. this.startPositionFunction(worldMatrix, particle.position);
  15597. var step = randomNumber(0, 1.0);
  15598. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15599. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15600. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15601. }
  15602. };
  15603. ParticleSystem.prototype._getEffect = function () {
  15604. if (this._customEffect) {
  15605. return this._customEffect;
  15606. }
  15607. ;
  15608. var defines = [];
  15609. if (this._scene.clipPlane) {
  15610. defines.push("#define CLIPPLANE");
  15611. }
  15612. // Effect
  15613. var join = defines.join("\n");
  15614. if (this._cachedDefines !== join) {
  15615. this._cachedDefines = join;
  15616. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15617. }
  15618. return this._effect;
  15619. };
  15620. ParticleSystem.prototype.animate = function () {
  15621. if (!this._started)
  15622. return;
  15623. var effect = this._getEffect();
  15624. // Check
  15625. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15626. return;
  15627. if (this._currentRenderId === this._scene.getRenderId()) {
  15628. return;
  15629. }
  15630. this._currentRenderId = this._scene.getRenderId();
  15631. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15632. // determine the number of particles we need to create
  15633. var emitCout;
  15634. if (this.manualEmitCount > -1) {
  15635. emitCout = this.manualEmitCount;
  15636. this.manualEmitCount = 0;
  15637. }
  15638. else {
  15639. emitCout = this.emitRate;
  15640. }
  15641. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15642. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15643. if (this._newPartsExcess > 1.0) {
  15644. newParticles += this._newPartsExcess >> 0;
  15645. this._newPartsExcess -= this._newPartsExcess >> 0;
  15646. }
  15647. this._alive = false;
  15648. if (!this._stopped) {
  15649. this._actualFrame += this._scaledUpdateSpeed;
  15650. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15651. this.stop();
  15652. }
  15653. else {
  15654. newParticles = 0;
  15655. }
  15656. this._update(newParticles);
  15657. // Stopped?
  15658. if (this._stopped) {
  15659. if (!this._alive) {
  15660. this._started = false;
  15661. if (this.disposeOnStop) {
  15662. this._scene._toBeDisposed.push(this);
  15663. }
  15664. }
  15665. }
  15666. // Update VBO
  15667. var offset = 0;
  15668. for (var index = 0; index < this.particles.length; index++) {
  15669. var particle = this.particles[index];
  15670. this._appendParticleVertex(offset++, particle, 0, 0);
  15671. this._appendParticleVertex(offset++, particle, 1, 0);
  15672. this._appendParticleVertex(offset++, particle, 1, 1);
  15673. this._appendParticleVertex(offset++, particle, 0, 1);
  15674. }
  15675. var engine = this._scene.getEngine();
  15676. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15677. };
  15678. ParticleSystem.prototype.render = function () {
  15679. var effect = this._getEffect();
  15680. // Check
  15681. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15682. return 0;
  15683. var engine = this._scene.getEngine();
  15684. // Render
  15685. engine.enableEffect(effect);
  15686. engine.setState(false);
  15687. var viewMatrix = this._scene.getViewMatrix();
  15688. effect.setTexture("diffuseSampler", this.particleTexture);
  15689. effect.setMatrix("view", viewMatrix);
  15690. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15691. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15692. if (this._scene.clipPlane) {
  15693. var clipPlane = this._scene.clipPlane;
  15694. var invView = viewMatrix.clone();
  15695. invView.invert();
  15696. effect.setMatrix("invView", invView);
  15697. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15698. }
  15699. // VBOs
  15700. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15701. // Draw order
  15702. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15703. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15704. }
  15705. else {
  15706. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15707. }
  15708. if (this.forceDepthWrite) {
  15709. engine.setDepthWrite(true);
  15710. }
  15711. engine.draw(true, 0, this.particles.length * 6);
  15712. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15713. return this.particles.length;
  15714. };
  15715. ParticleSystem.prototype.dispose = function () {
  15716. if (this._vertexBuffer) {
  15717. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15718. this._vertexBuffer = null;
  15719. }
  15720. if (this._indexBuffer) {
  15721. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15722. this._indexBuffer = null;
  15723. }
  15724. if (this.particleTexture) {
  15725. this.particleTexture.dispose();
  15726. this.particleTexture = null;
  15727. }
  15728. // Remove from scene
  15729. var index = this._scene.particleSystems.indexOf(this);
  15730. this._scene.particleSystems.splice(index, 1);
  15731. // Callback
  15732. if (this.onDispose) {
  15733. this.onDispose();
  15734. }
  15735. };
  15736. // Clone
  15737. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15738. var result = new ParticleSystem(name, this._capacity, this._scene);
  15739. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15740. if (newEmitter === undefined) {
  15741. newEmitter = this.emitter;
  15742. }
  15743. result.emitter = newEmitter;
  15744. if (this.particleTexture) {
  15745. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15746. }
  15747. result.start();
  15748. return result;
  15749. };
  15750. // Statics
  15751. ParticleSystem.BLENDMODE_ONEONE = 0;
  15752. ParticleSystem.BLENDMODE_STANDARD = 1;
  15753. return ParticleSystem;
  15754. })();
  15755. BABYLON.ParticleSystem = ParticleSystem;
  15756. })(BABYLON || (BABYLON = {}));
  15757. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15758. (function (BABYLON) {
  15759. var Animation = (function () {
  15760. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15761. this.name = name;
  15762. this.targetProperty = targetProperty;
  15763. this.framePerSecond = framePerSecond;
  15764. this.dataType = dataType;
  15765. this.loopMode = loopMode;
  15766. this._offsetsCache = {};
  15767. this._highLimitsCache = {};
  15768. this._stopped = false;
  15769. this.targetPropertyPath = targetProperty.split(".");
  15770. this.dataType = dataType;
  15771. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15772. }
  15773. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15774. var dataType = undefined;
  15775. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15776. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15777. }
  15778. else if (from instanceof BABYLON.Quaternion) {
  15779. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15780. }
  15781. else if (from instanceof BABYLON.Vector3) {
  15782. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15783. }
  15784. else if (from instanceof BABYLON.Vector2) {
  15785. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15786. }
  15787. else if (from instanceof BABYLON.Color3) {
  15788. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15789. }
  15790. if (dataType == undefined) {
  15791. return null;
  15792. }
  15793. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15794. var keys = [];
  15795. keys.push({ frame: 0, value: from });
  15796. keys.push({ frame: totalFrame, value: to });
  15797. animation.setKeys(keys);
  15798. mesh.animations.push(animation);
  15799. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15800. };
  15801. // Methods
  15802. Animation.prototype.isStopped = function () {
  15803. return this._stopped;
  15804. };
  15805. Animation.prototype.getKeys = function () {
  15806. return this._keys;
  15807. };
  15808. Animation.prototype.getEasingFunction = function () {
  15809. return this._easingFunction;
  15810. };
  15811. Animation.prototype.setEasingFunction = function (easingFunction) {
  15812. this._easingFunction = easingFunction;
  15813. };
  15814. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15815. return startValue + (endValue - startValue) * gradient;
  15816. };
  15817. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15818. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15819. };
  15820. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15821. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15822. };
  15823. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15824. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15825. };
  15826. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15827. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15828. };
  15829. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15830. var startScale = new BABYLON.Vector3(0, 0, 0);
  15831. var startRotation = new BABYLON.Quaternion();
  15832. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15833. startValue.decompose(startScale, startRotation, startTranslation);
  15834. var endScale = new BABYLON.Vector3(0, 0, 0);
  15835. var endRotation = new BABYLON.Quaternion();
  15836. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15837. endValue.decompose(endScale, endRotation, endTranslation);
  15838. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15839. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15840. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15841. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15842. return result;
  15843. };
  15844. Animation.prototype.clone = function () {
  15845. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15846. clone.setKeys(this._keys);
  15847. return clone;
  15848. };
  15849. Animation.prototype.setKeys = function (values) {
  15850. this._keys = values.slice(0);
  15851. this._offsetsCache = {};
  15852. this._highLimitsCache = {};
  15853. };
  15854. Animation.prototype._getKeyValue = function (value) {
  15855. if (typeof value === "function") {
  15856. return value();
  15857. }
  15858. return value;
  15859. };
  15860. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15861. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15862. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15863. }
  15864. this.currentFrame = currentFrame;
  15865. for (var key = 0; key < this._keys.length; key++) {
  15866. // for each frame, we need the key just before the frame superior
  15867. if (this._keys[key + 1].frame >= currentFrame) {
  15868. var startValue = this._getKeyValue(this._keys[key].value);
  15869. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15870. // gradient : percent of currentFrame between the frame inf and the frame sup
  15871. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15872. // check for easingFunction and correction of gradient
  15873. if (this._easingFunction != null) {
  15874. gradient = this._easingFunction.ease(gradient);
  15875. }
  15876. switch (this.dataType) {
  15877. case Animation.ANIMATIONTYPE_FLOAT:
  15878. switch (loopMode) {
  15879. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15880. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15881. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15882. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15883. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15884. }
  15885. break;
  15886. case Animation.ANIMATIONTYPE_QUATERNION:
  15887. var quaternion = null;
  15888. switch (loopMode) {
  15889. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15890. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15891. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15892. break;
  15893. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15894. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15895. break;
  15896. }
  15897. return quaternion;
  15898. case Animation.ANIMATIONTYPE_VECTOR3:
  15899. switch (loopMode) {
  15900. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15901. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15902. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15903. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15904. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15905. }
  15906. case Animation.ANIMATIONTYPE_VECTOR2:
  15907. switch (loopMode) {
  15908. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15909. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15910. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15911. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15912. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15913. }
  15914. case Animation.ANIMATIONTYPE_COLOR3:
  15915. switch (loopMode) {
  15916. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15917. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15918. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15919. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15920. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15921. }
  15922. case Animation.ANIMATIONTYPE_MATRIX:
  15923. switch (loopMode) {
  15924. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15925. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15926. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15927. return startValue;
  15928. }
  15929. default:
  15930. break;
  15931. }
  15932. break;
  15933. }
  15934. }
  15935. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15936. };
  15937. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15938. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15939. this._stopped = true;
  15940. return false;
  15941. }
  15942. var returnValue = true;
  15943. // Adding a start key at frame 0 if missing
  15944. if (this._keys[0].frame !== 0) {
  15945. var newKey = { frame: 0, value: this._keys[0].value };
  15946. this._keys.splice(0, 0, newKey);
  15947. }
  15948. // Check limits
  15949. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15950. from = this._keys[0].frame;
  15951. }
  15952. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15953. to = this._keys[this._keys.length - 1].frame;
  15954. }
  15955. // Compute ratio
  15956. var range = to - from;
  15957. var offsetValue;
  15958. // ratio represents the frame delta between from and to
  15959. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15960. var highLimitValue = 0;
  15961. if (ratio > range && !loop) {
  15962. returnValue = false;
  15963. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15964. }
  15965. else {
  15966. // Get max value if required
  15967. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15968. var keyOffset = to.toString() + from.toString();
  15969. if (!this._offsetsCache[keyOffset]) {
  15970. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15971. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15972. switch (this.dataType) {
  15973. case Animation.ANIMATIONTYPE_FLOAT:
  15974. this._offsetsCache[keyOffset] = toValue - fromValue;
  15975. break;
  15976. case Animation.ANIMATIONTYPE_QUATERNION:
  15977. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15978. break;
  15979. case Animation.ANIMATIONTYPE_VECTOR3:
  15980. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15981. case Animation.ANIMATIONTYPE_VECTOR2:
  15982. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15983. case Animation.ANIMATIONTYPE_COLOR3:
  15984. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15985. default:
  15986. break;
  15987. }
  15988. this._highLimitsCache[keyOffset] = toValue;
  15989. }
  15990. highLimitValue = this._highLimitsCache[keyOffset];
  15991. offsetValue = this._offsetsCache[keyOffset];
  15992. }
  15993. }
  15994. if (offsetValue === undefined) {
  15995. switch (this.dataType) {
  15996. case Animation.ANIMATIONTYPE_FLOAT:
  15997. offsetValue = 0;
  15998. break;
  15999. case Animation.ANIMATIONTYPE_QUATERNION:
  16000. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16001. break;
  16002. case Animation.ANIMATIONTYPE_VECTOR3:
  16003. offsetValue = BABYLON.Vector3.Zero();
  16004. break;
  16005. case Animation.ANIMATIONTYPE_VECTOR2:
  16006. offsetValue = BABYLON.Vector2.Zero();
  16007. break;
  16008. case Animation.ANIMATIONTYPE_COLOR3:
  16009. offsetValue = BABYLON.Color3.Black();
  16010. }
  16011. }
  16012. // Compute value
  16013. var repeatCount = (ratio / range) >> 0;
  16014. var currentFrame = returnValue ? from + ratio % range : to;
  16015. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16016. // Set value
  16017. if (this.targetPropertyPath.length > 1) {
  16018. var property = this._target[this.targetPropertyPath[0]];
  16019. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16020. property = property[this.targetPropertyPath[index]];
  16021. }
  16022. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16023. }
  16024. else {
  16025. this._target[this.targetPropertyPath[0]] = currentValue;
  16026. }
  16027. if (this._target.markAsDirty) {
  16028. this._target.markAsDirty(this.targetProperty);
  16029. }
  16030. if (!returnValue) {
  16031. this._stopped = true;
  16032. }
  16033. return returnValue;
  16034. };
  16035. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16036. get: function () {
  16037. return Animation._ANIMATIONTYPE_FLOAT;
  16038. },
  16039. enumerable: true,
  16040. configurable: true
  16041. });
  16042. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16043. get: function () {
  16044. return Animation._ANIMATIONTYPE_VECTOR3;
  16045. },
  16046. enumerable: true,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16050. get: function () {
  16051. return Animation._ANIMATIONTYPE_VECTOR2;
  16052. },
  16053. enumerable: true,
  16054. configurable: true
  16055. });
  16056. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16057. get: function () {
  16058. return Animation._ANIMATIONTYPE_QUATERNION;
  16059. },
  16060. enumerable: true,
  16061. configurable: true
  16062. });
  16063. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16064. get: function () {
  16065. return Animation._ANIMATIONTYPE_MATRIX;
  16066. },
  16067. enumerable: true,
  16068. configurable: true
  16069. });
  16070. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16071. get: function () {
  16072. return Animation._ANIMATIONTYPE_COLOR3;
  16073. },
  16074. enumerable: true,
  16075. configurable: true
  16076. });
  16077. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16078. get: function () {
  16079. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16080. },
  16081. enumerable: true,
  16082. configurable: true
  16083. });
  16084. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16085. get: function () {
  16086. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16087. },
  16088. enumerable: true,
  16089. configurable: true
  16090. });
  16091. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16092. get: function () {
  16093. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16094. },
  16095. enumerable: true,
  16096. configurable: true
  16097. });
  16098. // Statics
  16099. Animation._ANIMATIONTYPE_FLOAT = 0;
  16100. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16101. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16102. Animation._ANIMATIONTYPE_MATRIX = 3;
  16103. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16104. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16105. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16106. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16107. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16108. return Animation;
  16109. })();
  16110. BABYLON.Animation = Animation;
  16111. })(BABYLON || (BABYLON = {}));
  16112. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16113. (function (BABYLON) {
  16114. var Animatable = (function () {
  16115. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16116. if (fromFrame === void 0) { fromFrame = 0; }
  16117. if (toFrame === void 0) { toFrame = 100; }
  16118. if (loopAnimation === void 0) { loopAnimation = false; }
  16119. if (speedRatio === void 0) { speedRatio = 1.0; }
  16120. this.target = target;
  16121. this.fromFrame = fromFrame;
  16122. this.toFrame = toFrame;
  16123. this.loopAnimation = loopAnimation;
  16124. this.speedRatio = speedRatio;
  16125. this.onAnimationEnd = onAnimationEnd;
  16126. this._animations = new Array();
  16127. this._paused = false;
  16128. this.animationStarted = false;
  16129. if (animations) {
  16130. this.appendAnimations(target, animations);
  16131. }
  16132. this._scene = scene;
  16133. scene._activeAnimatables.push(this);
  16134. }
  16135. // Methods
  16136. Animatable.prototype.appendAnimations = function (target, animations) {
  16137. for (var index = 0; index < animations.length; index++) {
  16138. var animation = animations[index];
  16139. animation._target = target;
  16140. this._animations.push(animation);
  16141. }
  16142. };
  16143. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16144. var animations = this._animations;
  16145. for (var index = 0; index < animations.length; index++) {
  16146. if (animations[index].targetProperty === property) {
  16147. return animations[index];
  16148. }
  16149. }
  16150. return null;
  16151. };
  16152. Animatable.prototype.pause = function () {
  16153. if (this._paused) {
  16154. return;
  16155. }
  16156. this._paused = true;
  16157. };
  16158. Animatable.prototype.restart = function () {
  16159. this._paused = false;
  16160. };
  16161. Animatable.prototype.stop = function () {
  16162. var index = this._scene._activeAnimatables.indexOf(this);
  16163. if (index > -1) {
  16164. this._scene._activeAnimatables.splice(index, 1);
  16165. }
  16166. if (this.onAnimationEnd) {
  16167. this.onAnimationEnd();
  16168. }
  16169. };
  16170. Animatable.prototype._animate = function (delay) {
  16171. if (this._paused) {
  16172. if (!this._pausedDelay) {
  16173. this._pausedDelay = delay;
  16174. }
  16175. return true;
  16176. }
  16177. if (!this._localDelayOffset) {
  16178. this._localDelayOffset = delay;
  16179. }
  16180. else if (this._pausedDelay) {
  16181. this._localDelayOffset += delay - this._pausedDelay;
  16182. this._pausedDelay = null;
  16183. }
  16184. // Animating
  16185. var running = false;
  16186. var animations = this._animations;
  16187. for (var index = 0; index < animations.length; index++) {
  16188. var animation = animations[index];
  16189. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16190. running = running || isRunning;
  16191. }
  16192. if (!running && this.onAnimationEnd) {
  16193. this.onAnimationEnd();
  16194. }
  16195. return running;
  16196. };
  16197. return Animatable;
  16198. })();
  16199. BABYLON.Animatable = Animatable;
  16200. })(BABYLON || (BABYLON = {}));
  16201. //# sourceMappingURL=babylon.animatable.js.map
  16202. var BABYLON;
  16203. (function (BABYLON) {
  16204. var EasingFunction = (function () {
  16205. function EasingFunction() {
  16206. // Properties
  16207. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16208. }
  16209. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16210. get: function () {
  16211. return EasingFunction._EASINGMODE_EASEIN;
  16212. },
  16213. enumerable: true,
  16214. configurable: true
  16215. });
  16216. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16217. get: function () {
  16218. return EasingFunction._EASINGMODE_EASEOUT;
  16219. },
  16220. enumerable: true,
  16221. configurable: true
  16222. });
  16223. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16224. get: function () {
  16225. return EasingFunction._EASINGMODE_EASEINOUT;
  16226. },
  16227. enumerable: true,
  16228. configurable: true
  16229. });
  16230. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16231. var n = Math.min(Math.max(easingMode, 0), 2);
  16232. this._easingMode = n;
  16233. };
  16234. EasingFunction.prototype.getEasingMode = function () {
  16235. return this._easingMode;
  16236. };
  16237. EasingFunction.prototype.easeInCore = function (gradient) {
  16238. throw new Error('You must implement this method');
  16239. };
  16240. EasingFunction.prototype.ease = function (gradient) {
  16241. switch (this._easingMode) {
  16242. case EasingFunction.EASINGMODE_EASEIN:
  16243. return this.easeInCore(gradient);
  16244. case EasingFunction.EASINGMODE_EASEOUT:
  16245. return (1 - this.easeInCore(1 - gradient));
  16246. }
  16247. if (gradient >= 0.5) {
  16248. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16249. }
  16250. return (this.easeInCore(gradient * 2) * 0.5);
  16251. };
  16252. //Statics
  16253. EasingFunction._EASINGMODE_EASEIN = 0;
  16254. EasingFunction._EASINGMODE_EASEOUT = 1;
  16255. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16256. return EasingFunction;
  16257. })();
  16258. BABYLON.EasingFunction = EasingFunction;
  16259. var CircleEase = (function (_super) {
  16260. __extends(CircleEase, _super);
  16261. function CircleEase() {
  16262. _super.apply(this, arguments);
  16263. }
  16264. CircleEase.prototype.easeInCore = function (gradient) {
  16265. gradient = Math.max(0, Math.min(1, gradient));
  16266. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16267. };
  16268. return CircleEase;
  16269. })(EasingFunction);
  16270. BABYLON.CircleEase = CircleEase;
  16271. var BackEase = (function (_super) {
  16272. __extends(BackEase, _super);
  16273. function BackEase(amplitude) {
  16274. if (amplitude === void 0) { amplitude = 1; }
  16275. _super.call(this);
  16276. this.amplitude = amplitude;
  16277. }
  16278. BackEase.prototype.easeInCore = function (gradient) {
  16279. var num = Math.max(0, this.amplitude);
  16280. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16281. };
  16282. return BackEase;
  16283. })(EasingFunction);
  16284. BABYLON.BackEase = BackEase;
  16285. var BounceEase = (function (_super) {
  16286. __extends(BounceEase, _super);
  16287. function BounceEase(bounces, bounciness) {
  16288. if (bounces === void 0) { bounces = 3; }
  16289. if (bounciness === void 0) { bounciness = 2; }
  16290. _super.call(this);
  16291. this.bounces = bounces;
  16292. this.bounciness = bounciness;
  16293. }
  16294. BounceEase.prototype.easeInCore = function (gradient) {
  16295. var y = Math.max(0.0, this.bounces);
  16296. var bounciness = this.bounciness;
  16297. if (bounciness <= 1.0) {
  16298. bounciness = 1.001;
  16299. }
  16300. var num9 = Math.pow(bounciness, y);
  16301. var num5 = 1.0 - bounciness;
  16302. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16303. var num15 = gradient * num4;
  16304. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16305. var num3 = Math.floor(num65);
  16306. var num13 = num3 + 1.0;
  16307. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16308. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16309. var num7 = (num8 + num12) * 0.5;
  16310. var num6 = gradient - num7;
  16311. var num2 = num7 - num8;
  16312. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16313. };
  16314. return BounceEase;
  16315. })(EasingFunction);
  16316. BABYLON.BounceEase = BounceEase;
  16317. var CubicEase = (function (_super) {
  16318. __extends(CubicEase, _super);
  16319. function CubicEase() {
  16320. _super.apply(this, arguments);
  16321. }
  16322. CubicEase.prototype.easeInCore = function (gradient) {
  16323. return (gradient * gradient * gradient);
  16324. };
  16325. return CubicEase;
  16326. })(EasingFunction);
  16327. BABYLON.CubicEase = CubicEase;
  16328. var ElasticEase = (function (_super) {
  16329. __extends(ElasticEase, _super);
  16330. function ElasticEase(oscillations, springiness) {
  16331. if (oscillations === void 0) { oscillations = 3; }
  16332. if (springiness === void 0) { springiness = 3; }
  16333. _super.call(this);
  16334. this.oscillations = oscillations;
  16335. this.springiness = springiness;
  16336. }
  16337. ElasticEase.prototype.easeInCore = function (gradient) {
  16338. var num2;
  16339. var num3 = Math.max(0.0, this.oscillations);
  16340. var num = Math.max(0.0, this.springiness);
  16341. if (num == 0) {
  16342. num2 = gradient;
  16343. }
  16344. else {
  16345. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16346. }
  16347. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16348. };
  16349. return ElasticEase;
  16350. })(EasingFunction);
  16351. BABYLON.ElasticEase = ElasticEase;
  16352. var ExponentialEase = (function (_super) {
  16353. __extends(ExponentialEase, _super);
  16354. function ExponentialEase(exponent) {
  16355. if (exponent === void 0) { exponent = 2; }
  16356. _super.call(this);
  16357. this.exponent = exponent;
  16358. }
  16359. ExponentialEase.prototype.easeInCore = function (gradient) {
  16360. if (this.exponent <= 0) {
  16361. return gradient;
  16362. }
  16363. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16364. };
  16365. return ExponentialEase;
  16366. })(EasingFunction);
  16367. BABYLON.ExponentialEase = ExponentialEase;
  16368. var PowerEase = (function (_super) {
  16369. __extends(PowerEase, _super);
  16370. function PowerEase(power) {
  16371. if (power === void 0) { power = 2; }
  16372. _super.call(this);
  16373. this.power = power;
  16374. }
  16375. PowerEase.prototype.easeInCore = function (gradient) {
  16376. var y = Math.max(0.0, this.power);
  16377. return Math.pow(gradient, y);
  16378. };
  16379. return PowerEase;
  16380. })(EasingFunction);
  16381. BABYLON.PowerEase = PowerEase;
  16382. var QuadraticEase = (function (_super) {
  16383. __extends(QuadraticEase, _super);
  16384. function QuadraticEase() {
  16385. _super.apply(this, arguments);
  16386. }
  16387. QuadraticEase.prototype.easeInCore = function (gradient) {
  16388. return (gradient * gradient);
  16389. };
  16390. return QuadraticEase;
  16391. })(EasingFunction);
  16392. BABYLON.QuadraticEase = QuadraticEase;
  16393. var QuarticEase = (function (_super) {
  16394. __extends(QuarticEase, _super);
  16395. function QuarticEase() {
  16396. _super.apply(this, arguments);
  16397. }
  16398. QuarticEase.prototype.easeInCore = function (gradient) {
  16399. return (gradient * gradient * gradient * gradient);
  16400. };
  16401. return QuarticEase;
  16402. })(EasingFunction);
  16403. BABYLON.QuarticEase = QuarticEase;
  16404. var QuinticEase = (function (_super) {
  16405. __extends(QuinticEase, _super);
  16406. function QuinticEase() {
  16407. _super.apply(this, arguments);
  16408. }
  16409. QuinticEase.prototype.easeInCore = function (gradient) {
  16410. return (gradient * gradient * gradient * gradient * gradient);
  16411. };
  16412. return QuinticEase;
  16413. })(EasingFunction);
  16414. BABYLON.QuinticEase = QuinticEase;
  16415. var SineEase = (function (_super) {
  16416. __extends(SineEase, _super);
  16417. function SineEase() {
  16418. _super.apply(this, arguments);
  16419. }
  16420. SineEase.prototype.easeInCore = function (gradient) {
  16421. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16422. };
  16423. return SineEase;
  16424. })(EasingFunction);
  16425. BABYLON.SineEase = SineEase;
  16426. var BezierCurveEase = (function (_super) {
  16427. __extends(BezierCurveEase, _super);
  16428. function BezierCurveEase(x1, y1, x2, y2) {
  16429. if (x1 === void 0) { x1 = 0; }
  16430. if (y1 === void 0) { y1 = 0; }
  16431. if (x2 === void 0) { x2 = 1; }
  16432. if (y2 === void 0) { y2 = 1; }
  16433. _super.call(this);
  16434. this.x1 = x1;
  16435. this.y1 = y1;
  16436. this.x2 = x2;
  16437. this.y2 = y2;
  16438. }
  16439. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16440. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16441. };
  16442. return BezierCurveEase;
  16443. })(EasingFunction);
  16444. BABYLON.BezierCurveEase = BezierCurveEase;
  16445. })(BABYLON || (BABYLON = {}));
  16446. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16447. (function (BABYLON) {
  16448. var Octree = (function () {
  16449. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16450. if (maxDepth === void 0) { maxDepth = 2; }
  16451. this.maxDepth = maxDepth;
  16452. this.dynamicContent = new Array();
  16453. this._maxBlockCapacity = maxBlockCapacity || 64;
  16454. this._selectionContent = new BABYLON.SmartArray(1024);
  16455. this._creationFunc = creationFunc;
  16456. }
  16457. // Methods
  16458. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16459. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16460. };
  16461. Octree.prototype.addMesh = function (entry) {
  16462. for (var index = 0; index < this.blocks.length; index++) {
  16463. var block = this.blocks[index];
  16464. block.addEntry(entry);
  16465. }
  16466. };
  16467. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16468. this._selectionContent.reset();
  16469. for (var index = 0; index < this.blocks.length; index++) {
  16470. var block = this.blocks[index];
  16471. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16472. }
  16473. if (allowDuplicate) {
  16474. this._selectionContent.concat(this.dynamicContent);
  16475. }
  16476. else {
  16477. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16478. }
  16479. return this._selectionContent;
  16480. };
  16481. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16482. this._selectionContent.reset();
  16483. for (var index = 0; index < this.blocks.length; index++) {
  16484. var block = this.blocks[index];
  16485. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16486. }
  16487. if (allowDuplicate) {
  16488. this._selectionContent.concat(this.dynamicContent);
  16489. }
  16490. else {
  16491. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16492. }
  16493. return this._selectionContent;
  16494. };
  16495. Octree.prototype.intersectsRay = function (ray) {
  16496. this._selectionContent.reset();
  16497. for (var index = 0; index < this.blocks.length; index++) {
  16498. var block = this.blocks[index];
  16499. block.intersectsRay(ray, this._selectionContent);
  16500. }
  16501. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16502. return this._selectionContent;
  16503. };
  16504. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16505. target.blocks = new Array();
  16506. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16507. for (var x = 0; x < 2; x++) {
  16508. for (var y = 0; y < 2; y++) {
  16509. for (var z = 0; z < 2; z++) {
  16510. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16511. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16512. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16513. block.addEntries(entries);
  16514. target.blocks.push(block);
  16515. }
  16516. }
  16517. }
  16518. };
  16519. Octree.CreationFuncForMeshes = function (entry, block) {
  16520. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16521. block.entries.push(entry);
  16522. }
  16523. };
  16524. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16525. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16526. block.entries.push(entry);
  16527. }
  16528. };
  16529. return Octree;
  16530. })();
  16531. BABYLON.Octree = Octree;
  16532. })(BABYLON || (BABYLON = {}));
  16533. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16534. (function (BABYLON) {
  16535. var OctreeBlock = (function () {
  16536. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16537. this.entries = new Array();
  16538. this._boundingVectors = new Array();
  16539. this._capacity = capacity;
  16540. this._depth = depth;
  16541. this._maxDepth = maxDepth;
  16542. this._creationFunc = creationFunc;
  16543. this._minPoint = minPoint;
  16544. this._maxPoint = maxPoint;
  16545. this._boundingVectors.push(minPoint.clone());
  16546. this._boundingVectors.push(maxPoint.clone());
  16547. this._boundingVectors.push(minPoint.clone());
  16548. this._boundingVectors[2].x = maxPoint.x;
  16549. this._boundingVectors.push(minPoint.clone());
  16550. this._boundingVectors[3].y = maxPoint.y;
  16551. this._boundingVectors.push(minPoint.clone());
  16552. this._boundingVectors[4].z = maxPoint.z;
  16553. this._boundingVectors.push(maxPoint.clone());
  16554. this._boundingVectors[5].z = minPoint.z;
  16555. this._boundingVectors.push(maxPoint.clone());
  16556. this._boundingVectors[6].x = minPoint.x;
  16557. this._boundingVectors.push(maxPoint.clone());
  16558. this._boundingVectors[7].y = minPoint.y;
  16559. }
  16560. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16561. // Property
  16562. get: function () {
  16563. return this._capacity;
  16564. },
  16565. enumerable: true,
  16566. configurable: true
  16567. });
  16568. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16569. get: function () {
  16570. return this._minPoint;
  16571. },
  16572. enumerable: true,
  16573. configurable: true
  16574. });
  16575. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16576. get: function () {
  16577. return this._maxPoint;
  16578. },
  16579. enumerable: true,
  16580. configurable: true
  16581. });
  16582. // Methods
  16583. OctreeBlock.prototype.addEntry = function (entry) {
  16584. if (this.blocks) {
  16585. for (var index = 0; index < this.blocks.length; index++) {
  16586. var block = this.blocks[index];
  16587. block.addEntry(entry);
  16588. }
  16589. return;
  16590. }
  16591. this._creationFunc(entry, this);
  16592. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16593. this.createInnerBlocks();
  16594. }
  16595. };
  16596. OctreeBlock.prototype.addEntries = function (entries) {
  16597. for (var index = 0; index < entries.length; index++) {
  16598. var mesh = entries[index];
  16599. this.addEntry(mesh);
  16600. }
  16601. };
  16602. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16603. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16604. if (this.blocks) {
  16605. for (var index = 0; index < this.blocks.length; index++) {
  16606. var block = this.blocks[index];
  16607. block.select(frustumPlanes, selection, allowDuplicate);
  16608. }
  16609. return;
  16610. }
  16611. if (allowDuplicate) {
  16612. selection.concat(this.entries);
  16613. }
  16614. else {
  16615. selection.concatWithNoDuplicate(this.entries);
  16616. }
  16617. }
  16618. };
  16619. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16620. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16621. if (this.blocks) {
  16622. for (var index = 0; index < this.blocks.length; index++) {
  16623. var block = this.blocks[index];
  16624. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16625. }
  16626. return;
  16627. }
  16628. if (allowDuplicate) {
  16629. selection.concat(this.entries);
  16630. }
  16631. else {
  16632. selection.concatWithNoDuplicate(this.entries);
  16633. }
  16634. }
  16635. };
  16636. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16637. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16638. if (this.blocks) {
  16639. for (var index = 0; index < this.blocks.length; index++) {
  16640. var block = this.blocks[index];
  16641. block.intersectsRay(ray, selection);
  16642. }
  16643. return;
  16644. }
  16645. selection.concatWithNoDuplicate(this.entries);
  16646. }
  16647. };
  16648. OctreeBlock.prototype.createInnerBlocks = function () {
  16649. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16650. };
  16651. return OctreeBlock;
  16652. })();
  16653. BABYLON.OctreeBlock = OctreeBlock;
  16654. })(BABYLON || (BABYLON = {}));
  16655. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16656. (function (BABYLON) {
  16657. var Bone = (function () {
  16658. function Bone(name, skeleton, parentBone, matrix) {
  16659. this.name = name;
  16660. this.children = new Array();
  16661. this.animations = new Array();
  16662. this._worldTransform = new BABYLON.Matrix();
  16663. this._absoluteTransform = new BABYLON.Matrix();
  16664. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16665. this._skeleton = skeleton;
  16666. this._matrix = matrix;
  16667. this._baseMatrix = matrix;
  16668. skeleton.bones.push(this);
  16669. if (parentBone) {
  16670. this._parent = parentBone;
  16671. parentBone.children.push(this);
  16672. }
  16673. else {
  16674. this._parent = null;
  16675. }
  16676. this._updateDifferenceMatrix();
  16677. }
  16678. // Members
  16679. Bone.prototype.getParent = function () {
  16680. return this._parent;
  16681. };
  16682. Bone.prototype.getLocalMatrix = function () {
  16683. return this._matrix;
  16684. };
  16685. Bone.prototype.getBaseMatrix = function () {
  16686. return this._baseMatrix;
  16687. };
  16688. Bone.prototype.getWorldMatrix = function () {
  16689. return this._worldTransform;
  16690. };
  16691. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16692. return this._invertedAbsoluteTransform;
  16693. };
  16694. Bone.prototype.getAbsoluteMatrix = function () {
  16695. var matrix = this._matrix.clone();
  16696. var parent = this._parent;
  16697. while (parent) {
  16698. matrix = matrix.multiply(parent.getLocalMatrix());
  16699. parent = parent.getParent();
  16700. }
  16701. return matrix;
  16702. };
  16703. // Methods
  16704. Bone.prototype.updateMatrix = function (matrix) {
  16705. this._matrix = matrix;
  16706. this._skeleton._markAsDirty();
  16707. this._updateDifferenceMatrix();
  16708. };
  16709. Bone.prototype._updateDifferenceMatrix = function () {
  16710. if (this._parent) {
  16711. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16712. }
  16713. else {
  16714. this._absoluteTransform.copyFrom(this._matrix);
  16715. }
  16716. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16717. for (var index = 0; index < this.children.length; index++) {
  16718. this.children[index]._updateDifferenceMatrix();
  16719. }
  16720. };
  16721. Bone.prototype.markAsDirty = function () {
  16722. this._skeleton._markAsDirty();
  16723. };
  16724. return Bone;
  16725. })();
  16726. BABYLON.Bone = Bone;
  16727. })(BABYLON || (BABYLON = {}));
  16728. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16729. (function (BABYLON) {
  16730. var Skeleton = (function () {
  16731. function Skeleton(name, id, scene) {
  16732. this.name = name;
  16733. this.id = id;
  16734. this.bones = new Array();
  16735. this._isDirty = true;
  16736. this._identity = BABYLON.Matrix.Identity();
  16737. this.bones = [];
  16738. this._scene = scene;
  16739. scene.skeletons.push(this);
  16740. }
  16741. // Members
  16742. Skeleton.prototype.getTransformMatrices = function () {
  16743. return this._transformMatrices;
  16744. };
  16745. // Methods
  16746. Skeleton.prototype._markAsDirty = function () {
  16747. this._isDirty = true;
  16748. };
  16749. Skeleton.prototype.prepare = function () {
  16750. if (!this._isDirty) {
  16751. return;
  16752. }
  16753. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16754. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16755. }
  16756. for (var index = 0; index < this.bones.length; index++) {
  16757. var bone = this.bones[index];
  16758. var parentBone = bone.getParent();
  16759. if (parentBone) {
  16760. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16761. }
  16762. else {
  16763. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16764. }
  16765. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16766. }
  16767. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16768. this._isDirty = false;
  16769. this._scene._activeBones += this.bones.length;
  16770. };
  16771. Skeleton.prototype.getAnimatables = function () {
  16772. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16773. this._animatables = [];
  16774. for (var index = 0; index < this.bones.length; index++) {
  16775. this._animatables.push(this.bones[index]);
  16776. }
  16777. }
  16778. return this._animatables;
  16779. };
  16780. Skeleton.prototype.clone = function (name, id) {
  16781. var result = new Skeleton(name, id || name, this._scene);
  16782. for (var index = 0; index < this.bones.length; index++) {
  16783. var source = this.bones[index];
  16784. var parentBone = null;
  16785. if (source.getParent()) {
  16786. var parentIndex = this.bones.indexOf(source.getParent());
  16787. parentBone = result.bones[parentIndex];
  16788. }
  16789. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16790. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16791. }
  16792. return result;
  16793. };
  16794. return Skeleton;
  16795. })();
  16796. BABYLON.Skeleton = Skeleton;
  16797. })(BABYLON || (BABYLON = {}));
  16798. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16799. (function (BABYLON) {
  16800. var PostProcess = (function () {
  16801. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16802. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16803. this.name = name;
  16804. this.width = -1;
  16805. this.height = -1;
  16806. this._reusable = false;
  16807. this._textures = new BABYLON.SmartArray(2);
  16808. this._currentRenderTextureInd = 0;
  16809. if (camera != null) {
  16810. this._camera = camera;
  16811. this._scene = camera.getScene();
  16812. camera.attachPostProcess(this);
  16813. this._engine = this._scene.getEngine();
  16814. }
  16815. else {
  16816. this._engine = engine;
  16817. }
  16818. this._renderRatio = ratio;
  16819. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16820. this._reusable = reusable || false;
  16821. samplers = samplers || [];
  16822. samplers.push("textureSampler");
  16823. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16824. }
  16825. PostProcess.prototype.isReusable = function () {
  16826. return this._reusable;
  16827. };
  16828. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16829. camera = camera || this._camera;
  16830. var scene = camera.getScene();
  16831. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16832. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16833. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16834. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16835. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16836. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16837. if (this._textures.length > 0) {
  16838. for (var i = 0; i < this._textures.length; i++) {
  16839. this._engine._releaseTexture(this._textures.data[i]);
  16840. }
  16841. this._textures.reset();
  16842. }
  16843. this.width = desiredWidth;
  16844. this.height = desiredHeight;
  16845. 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 }));
  16846. if (this._reusable) {
  16847. 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 }));
  16848. }
  16849. if (this.onSizeChanged) {
  16850. this.onSizeChanged();
  16851. }
  16852. }
  16853. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16854. if (this.onActivate) {
  16855. this.onActivate(camera);
  16856. }
  16857. // Clear
  16858. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16859. if (this._reusable) {
  16860. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16861. }
  16862. };
  16863. PostProcess.prototype.apply = function () {
  16864. // Check
  16865. if (!this._effect.isReady())
  16866. return null;
  16867. // States
  16868. this._engine.enableEffect(this._effect);
  16869. this._engine.setState(false);
  16870. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16871. this._engine.setDepthBuffer(false);
  16872. this._engine.setDepthWrite(false);
  16873. // Texture
  16874. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16875. // Parameters
  16876. if (this.onApply) {
  16877. this.onApply(this._effect);
  16878. }
  16879. return this._effect;
  16880. };
  16881. PostProcess.prototype.dispose = function (camera) {
  16882. camera = camera || this._camera;
  16883. if (this._textures.length > 0) {
  16884. for (var i = 0; i < this._textures.length; i++) {
  16885. this._engine._releaseTexture(this._textures.data[i]);
  16886. }
  16887. this._textures.reset();
  16888. }
  16889. if (!camera) {
  16890. return;
  16891. }
  16892. camera.detachPostProcess(this);
  16893. var index = camera._postProcesses.indexOf(this);
  16894. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16895. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16896. }
  16897. };
  16898. return PostProcess;
  16899. })();
  16900. BABYLON.PostProcess = PostProcess;
  16901. })(BABYLON || (BABYLON = {}));
  16902. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16903. (function (BABYLON) {
  16904. var PostProcessManager = (function () {
  16905. function PostProcessManager(scene) {
  16906. this._vertexDeclaration = [2];
  16907. this._vertexStrideSize = 2 * 4;
  16908. this._scene = scene;
  16909. // VBO
  16910. var vertices = [];
  16911. vertices.push(1, 1);
  16912. vertices.push(-1, 1);
  16913. vertices.push(-1, -1);
  16914. vertices.push(1, -1);
  16915. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16916. // Indices
  16917. var indices = [];
  16918. indices.push(0);
  16919. indices.push(1);
  16920. indices.push(2);
  16921. indices.push(0);
  16922. indices.push(2);
  16923. indices.push(3);
  16924. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16925. }
  16926. // Methods
  16927. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16928. var postProcesses = this._scene.activeCamera._postProcesses;
  16929. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16930. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16931. return false;
  16932. }
  16933. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16934. return true;
  16935. };
  16936. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16937. var engine = this._scene.getEngine();
  16938. for (var index = 0; index < postProcesses.length; index++) {
  16939. if (index < postProcesses.length - 1) {
  16940. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16941. }
  16942. else {
  16943. if (targetTexture) {
  16944. engine.bindFramebuffer(targetTexture);
  16945. }
  16946. else {
  16947. engine.restoreDefaultFramebuffer();
  16948. }
  16949. }
  16950. var pp = postProcesses[index];
  16951. var effect = pp.apply();
  16952. if (effect) {
  16953. if (pp.onBeforeRender) {
  16954. pp.onBeforeRender(effect);
  16955. }
  16956. // VBOs
  16957. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16958. // Draw order
  16959. engine.draw(true, 0, 6);
  16960. }
  16961. }
  16962. // Restore depth buffer
  16963. engine.setDepthBuffer(true);
  16964. engine.setDepthWrite(true);
  16965. };
  16966. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  16967. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  16968. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16969. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16970. return;
  16971. }
  16972. var engine = this._scene.getEngine();
  16973. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16974. if (index < postProcessesTakenIndices.length - 1) {
  16975. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16976. }
  16977. else {
  16978. if (targetTexture) {
  16979. engine.bindFramebuffer(targetTexture);
  16980. }
  16981. else {
  16982. engine.restoreDefaultFramebuffer();
  16983. }
  16984. }
  16985. if (doNotPresent) {
  16986. break;
  16987. }
  16988. var pp = postProcesses[postProcessesTakenIndices[index]];
  16989. var effect = pp.apply();
  16990. if (effect) {
  16991. if (pp.onBeforeRender) {
  16992. pp.onBeforeRender(effect);
  16993. }
  16994. // VBOs
  16995. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16996. // Draw order
  16997. engine.draw(true, 0, 6);
  16998. }
  16999. }
  17000. // Restore depth buffer
  17001. engine.setDepthBuffer(true);
  17002. engine.setDepthWrite(true);
  17003. };
  17004. PostProcessManager.prototype.dispose = function () {
  17005. if (this._vertexBuffer) {
  17006. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17007. this._vertexBuffer = null;
  17008. }
  17009. if (this._indexBuffer) {
  17010. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17011. this._indexBuffer = null;
  17012. }
  17013. };
  17014. return PostProcessManager;
  17015. })();
  17016. BABYLON.PostProcessManager = PostProcessManager;
  17017. })(BABYLON || (BABYLON = {}));
  17018. //# sourceMappingURL=babylon.postProcessManager.js.map
  17019. var BABYLON;
  17020. (function (BABYLON) {
  17021. var PassPostProcess = (function (_super) {
  17022. __extends(PassPostProcess, _super);
  17023. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17024. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17025. }
  17026. return PassPostProcess;
  17027. })(BABYLON.PostProcess);
  17028. BABYLON.PassPostProcess = PassPostProcess;
  17029. })(BABYLON || (BABYLON = {}));
  17030. //# sourceMappingURL=babylon.passPostProcess.js.map
  17031. var BABYLON;
  17032. (function (BABYLON) {
  17033. var BlurPostProcess = (function (_super) {
  17034. __extends(BlurPostProcess, _super);
  17035. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17036. var _this = this;
  17037. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17038. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17039. this.direction = direction;
  17040. this.blurWidth = blurWidth;
  17041. this.onApply = function (effect) {
  17042. effect.setFloat2("screenSize", _this.width, _this.height);
  17043. effect.setVector2("direction", _this.direction);
  17044. effect.setFloat("blurWidth", _this.blurWidth);
  17045. };
  17046. }
  17047. return BlurPostProcess;
  17048. })(BABYLON.PostProcess);
  17049. BABYLON.BlurPostProcess = BlurPostProcess;
  17050. })(BABYLON || (BABYLON = {}));
  17051. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17052. var BABYLON;
  17053. (function (BABYLON) {
  17054. var FilterPostProcess = (function (_super) {
  17055. __extends(FilterPostProcess, _super);
  17056. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17057. var _this = this;
  17058. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17059. this.kernelMatrix = kernelMatrix;
  17060. this.onApply = function (effect) {
  17061. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17062. };
  17063. }
  17064. return FilterPostProcess;
  17065. })(BABYLON.PostProcess);
  17066. BABYLON.FilterPostProcess = FilterPostProcess;
  17067. })(BABYLON || (BABYLON = {}));
  17068. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17069. var BABYLON;
  17070. (function (BABYLON) {
  17071. var RefractionPostProcess = (function (_super) {
  17072. __extends(RefractionPostProcess, _super);
  17073. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17074. var _this = this;
  17075. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17076. this.color = color;
  17077. this.depth = depth;
  17078. this.colorLevel = colorLevel;
  17079. this.onActivate = function (cam) {
  17080. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17081. };
  17082. this.onApply = function (effect) {
  17083. effect.setColor3("baseColor", _this.color);
  17084. effect.setFloat("depth", _this.depth);
  17085. effect.setFloat("colorLevel", _this.colorLevel);
  17086. effect.setTexture("refractionSampler", _this._refRexture);
  17087. };
  17088. }
  17089. // Methods
  17090. RefractionPostProcess.prototype.dispose = function (camera) {
  17091. if (this._refRexture) {
  17092. this._refRexture.dispose();
  17093. }
  17094. _super.prototype.dispose.call(this, camera);
  17095. };
  17096. return RefractionPostProcess;
  17097. })(BABYLON.PostProcess);
  17098. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17099. })(BABYLON || (BABYLON = {}));
  17100. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17101. var BABYLON;
  17102. (function (BABYLON) {
  17103. var BlackAndWhitePostProcess = (function (_super) {
  17104. __extends(BlackAndWhitePostProcess, _super);
  17105. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17106. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17107. }
  17108. return BlackAndWhitePostProcess;
  17109. })(BABYLON.PostProcess);
  17110. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17111. })(BABYLON || (BABYLON = {}));
  17112. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17113. var BABYLON;
  17114. (function (BABYLON) {
  17115. var ConvolutionPostProcess = (function (_super) {
  17116. __extends(ConvolutionPostProcess, _super);
  17117. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17118. var _this = this;
  17119. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17120. this.kernel = kernel;
  17121. this.onApply = function (effect) {
  17122. effect.setFloat2("screenSize", _this.width, _this.height);
  17123. effect.setArray("kernel", _this.kernel);
  17124. };
  17125. }
  17126. // Statics
  17127. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17128. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17129. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17130. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17131. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17132. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17133. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17134. return ConvolutionPostProcess;
  17135. })(BABYLON.PostProcess);
  17136. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17137. })(BABYLON || (BABYLON = {}));
  17138. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17139. var BABYLON;
  17140. (function (BABYLON) {
  17141. var FxaaPostProcess = (function (_super) {
  17142. __extends(FxaaPostProcess, _super);
  17143. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17144. var _this = this;
  17145. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17146. this.onSizeChanged = function () {
  17147. _this.texelWidth = 1.0 / _this.width;
  17148. _this.texelHeight = 1.0 / _this.height;
  17149. };
  17150. this.onApply = function (effect) {
  17151. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17152. };
  17153. }
  17154. return FxaaPostProcess;
  17155. })(BABYLON.PostProcess);
  17156. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17157. })(BABYLON || (BABYLON = {}));
  17158. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17159. (function (BABYLON) {
  17160. var LensFlare = (function () {
  17161. function LensFlare(size, position, color, imgUrl, system) {
  17162. this.size = size;
  17163. this.position = position;
  17164. this.dispose = function () {
  17165. if (this.texture) {
  17166. this.texture.dispose();
  17167. }
  17168. // Remove from scene
  17169. var index = this._system.lensFlares.indexOf(this);
  17170. this._system.lensFlares.splice(index, 1);
  17171. };
  17172. this.color = color || new BABYLON.Color3(1, 1, 1);
  17173. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17174. this._system = system;
  17175. system.lensFlares.push(this);
  17176. }
  17177. return LensFlare;
  17178. })();
  17179. BABYLON.LensFlare = LensFlare;
  17180. })(BABYLON || (BABYLON = {}));
  17181. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17182. (function (BABYLON) {
  17183. var LensFlareSystem = (function () {
  17184. function LensFlareSystem(name, emitter, scene) {
  17185. this.name = name;
  17186. this.lensFlares = new Array();
  17187. this.borderLimit = 300;
  17188. this._vertexDeclaration = [2];
  17189. this._vertexStrideSize = 2 * 4;
  17190. this._isEnabled = true;
  17191. this._scene = scene;
  17192. this._emitter = emitter;
  17193. scene.lensFlareSystems.push(this);
  17194. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17195. // VBO
  17196. var vertices = [];
  17197. vertices.push(1, 1);
  17198. vertices.push(-1, 1);
  17199. vertices.push(-1, -1);
  17200. vertices.push(1, -1);
  17201. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17202. // Indices
  17203. var indices = [];
  17204. indices.push(0);
  17205. indices.push(1);
  17206. indices.push(2);
  17207. indices.push(0);
  17208. indices.push(2);
  17209. indices.push(3);
  17210. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17211. // Effects
  17212. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17213. }
  17214. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17215. get: function () {
  17216. return this._isEnabled;
  17217. },
  17218. set: function (value) {
  17219. this._isEnabled = value;
  17220. },
  17221. enumerable: true,
  17222. configurable: true
  17223. });
  17224. LensFlareSystem.prototype.getScene = function () {
  17225. return this._scene;
  17226. };
  17227. LensFlareSystem.prototype.getEmitter = function () {
  17228. return this._emitter;
  17229. };
  17230. LensFlareSystem.prototype.getEmitterPosition = function () {
  17231. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17232. };
  17233. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17234. var position = this.getEmitterPosition();
  17235. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17236. this._positionX = position.x;
  17237. this._positionY = position.y;
  17238. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17239. if (position.z > 0) {
  17240. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17241. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17242. return true;
  17243. }
  17244. }
  17245. return false;
  17246. };
  17247. LensFlareSystem.prototype._isVisible = function () {
  17248. if (!this._isEnabled) {
  17249. return false;
  17250. }
  17251. var emitterPosition = this.getEmitterPosition();
  17252. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17253. var distance = direction.length();
  17254. direction.normalize();
  17255. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17256. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17257. return !pickInfo.hit || pickInfo.distance > distance;
  17258. };
  17259. LensFlareSystem.prototype.render = function () {
  17260. if (!this._effect.isReady())
  17261. return false;
  17262. var engine = this._scene.getEngine();
  17263. var viewport = this._scene.activeCamera.viewport;
  17264. var globalViewport = viewport.toGlobal(engine);
  17265. // Position
  17266. if (!this.computeEffectivePosition(globalViewport)) {
  17267. return false;
  17268. }
  17269. // Visibility
  17270. if (!this._isVisible()) {
  17271. return false;
  17272. }
  17273. // Intensity
  17274. var awayX;
  17275. var awayY;
  17276. if (this._positionX < this.borderLimit + globalViewport.x) {
  17277. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17278. }
  17279. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17280. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17281. }
  17282. else {
  17283. awayX = 0;
  17284. }
  17285. if (this._positionY < this.borderLimit + globalViewport.y) {
  17286. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17287. }
  17288. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17289. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17290. }
  17291. else {
  17292. awayY = 0;
  17293. }
  17294. var away = (awayX > awayY) ? awayX : awayY;
  17295. if (away > this.borderLimit) {
  17296. away = this.borderLimit;
  17297. }
  17298. var intensity = 1.0 - (away / this.borderLimit);
  17299. if (intensity < 0) {
  17300. return false;
  17301. }
  17302. if (intensity > 1.0) {
  17303. intensity = 1.0;
  17304. }
  17305. // Position
  17306. var centerX = globalViewport.x + globalViewport.width / 2;
  17307. var centerY = globalViewport.y + globalViewport.height / 2;
  17308. var distX = centerX - this._positionX;
  17309. var distY = centerY - this._positionY;
  17310. // Effects
  17311. engine.enableEffect(this._effect);
  17312. engine.setState(false);
  17313. engine.setDepthBuffer(false);
  17314. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17315. // VBOs
  17316. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17317. for (var index = 0; index < this.lensFlares.length; index++) {
  17318. var flare = this.lensFlares[index];
  17319. var x = centerX - (distX * flare.position);
  17320. var y = centerY - (distY * flare.position);
  17321. var cw = flare.size;
  17322. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17323. var cx = 2 * (x / globalViewport.width) - 1.0;
  17324. var cy = 1.0 - 2 * (y / globalViewport.height);
  17325. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17326. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17327. // Texture
  17328. this._effect.setTexture("textureSampler", flare.texture);
  17329. // Color
  17330. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17331. // Draw order
  17332. engine.draw(true, 0, 6);
  17333. }
  17334. engine.setDepthBuffer(true);
  17335. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17336. return true;
  17337. };
  17338. LensFlareSystem.prototype.dispose = function () {
  17339. if (this._vertexBuffer) {
  17340. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17341. this._vertexBuffer = null;
  17342. }
  17343. if (this._indexBuffer) {
  17344. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17345. this._indexBuffer = null;
  17346. }
  17347. while (this.lensFlares.length) {
  17348. this.lensFlares[0].dispose();
  17349. }
  17350. // Remove from scene
  17351. var index = this._scene.lensFlareSystems.indexOf(this);
  17352. this._scene.lensFlareSystems.splice(index, 1);
  17353. };
  17354. return LensFlareSystem;
  17355. })();
  17356. BABYLON.LensFlareSystem = LensFlareSystem;
  17357. })(BABYLON || (BABYLON = {}));
  17358. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17359. (function (BABYLON) {
  17360. var IntersectionInfo = (function () {
  17361. function IntersectionInfo(bu, bv, distance) {
  17362. this.bu = bu;
  17363. this.bv = bv;
  17364. this.distance = distance;
  17365. this.faceId = 0;
  17366. this.subMeshId = 0;
  17367. }
  17368. return IntersectionInfo;
  17369. })();
  17370. BABYLON.IntersectionInfo = IntersectionInfo;
  17371. var PickingInfo = (function () {
  17372. function PickingInfo() {
  17373. this.hit = false;
  17374. this.distance = 0;
  17375. this.pickedPoint = null;
  17376. this.pickedMesh = null;
  17377. this.bu = 0;
  17378. this.bv = 0;
  17379. this.faceId = -1;
  17380. this.subMeshId = 0;
  17381. }
  17382. // Methods
  17383. PickingInfo.prototype.getNormal = function () {
  17384. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17385. return null;
  17386. }
  17387. var indices = this.pickedMesh.getIndices();
  17388. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17389. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17390. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17391. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17392. normal0 = normal0.scale(this.bu);
  17393. normal1 = normal1.scale(this.bv);
  17394. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17395. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17396. };
  17397. PickingInfo.prototype.getTextureCoordinates = function () {
  17398. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17399. return null;
  17400. }
  17401. var indices = this.pickedMesh.getIndices();
  17402. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17403. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17404. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17405. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17406. uv0 = uv0.scale(this.bu);
  17407. uv1 = uv1.scale(this.bv);
  17408. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17409. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17410. };
  17411. return PickingInfo;
  17412. })();
  17413. BABYLON.PickingInfo = PickingInfo;
  17414. })(BABYLON || (BABYLON = {}));
  17415. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17416. (function (BABYLON) {
  17417. var FilesInput = (function () {
  17418. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17419. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17420. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17421. this._engine = p_engine;
  17422. this._canvas = p_canvas;
  17423. this._currentScene = p_scene;
  17424. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17425. this._progressCallback = p_progressCallback;
  17426. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17427. this._textureLoadingCallback = p_textureLoadingCallback;
  17428. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17429. }
  17430. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17431. var _this = this;
  17432. if (p_elementToMonitor) {
  17433. this._elementToMonitor = p_elementToMonitor;
  17434. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17435. _this.drag(e);
  17436. }, false);
  17437. this._elementToMonitor.addEventListener("dragover", function (e) {
  17438. _this.drag(e);
  17439. }, false);
  17440. this._elementToMonitor.addEventListener("drop", function (e) {
  17441. _this.drop(e);
  17442. }, false);
  17443. }
  17444. };
  17445. FilesInput.prototype.renderFunction = function () {
  17446. if (this._additionnalRenderLoopLogicCallback) {
  17447. this._additionnalRenderLoopLogicCallback();
  17448. }
  17449. if (this._currentScene) {
  17450. if (this._textureLoadingCallback) {
  17451. var remaining = this._currentScene.getWaitingItemsCount();
  17452. if (remaining > 0) {
  17453. this._textureLoadingCallback(remaining);
  17454. }
  17455. }
  17456. this._currentScene.render();
  17457. }
  17458. };
  17459. FilesInput.prototype.drag = function (e) {
  17460. e.stopPropagation();
  17461. e.preventDefault();
  17462. };
  17463. FilesInput.prototype.drop = function (eventDrop) {
  17464. eventDrop.stopPropagation();
  17465. eventDrop.preventDefault();
  17466. this.loadFiles(eventDrop);
  17467. };
  17468. FilesInput.prototype.loadFiles = function (event) {
  17469. if (this._startingProcessingFilesCallback)
  17470. this._startingProcessingFilesCallback();
  17471. // Handling data transfer via drag'n'drop
  17472. if (event && event.dataTransfer && event.dataTransfer.files) {
  17473. this._filesToLoad = event.dataTransfer.files;
  17474. }
  17475. // Handling files from input files
  17476. if (event && event.target && event.target.files) {
  17477. this._filesToLoad = event.target.files;
  17478. }
  17479. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17480. for (var i = 0; i < this._filesToLoad.length; i++) {
  17481. switch (this._filesToLoad[i].type) {
  17482. case "image/jpeg":
  17483. case "image/png":
  17484. case "image/bmp":
  17485. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17486. break;
  17487. case "image/targa":
  17488. case "image/vnd.ms-dds":
  17489. case "audio/wav":
  17490. case "audio/x-wav":
  17491. case "audio/mp3":
  17492. case "audio/mpeg":
  17493. case "audio/mpeg3":
  17494. case "audio/x-mpeg-3":
  17495. case "audio/ogg":
  17496. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17497. break;
  17498. default:
  17499. if (this._filesToLoad[i].name.indexOf(".babylon") !== -1 && this._filesToLoad[i].name.indexOf(".manifest") === -1 && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1 && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1) {
  17500. this._sceneFileToLoad = this._filesToLoad[i];
  17501. }
  17502. break;
  17503. }
  17504. }
  17505. this.reload();
  17506. }
  17507. };
  17508. FilesInput.prototype.reload = function () {
  17509. var _this = this;
  17510. var that = this;
  17511. // If a ".babylon" file has been provided
  17512. if (this._sceneFileToLoad) {
  17513. if (this._currentScene) {
  17514. this._engine.stopRenderLoop();
  17515. this._currentScene.dispose();
  17516. }
  17517. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17518. that._currentScene = newScene;
  17519. // Wait for textures and shaders to be ready
  17520. that._currentScene.executeWhenReady(function () {
  17521. // Attach camera to canvas inputs
  17522. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17523. that._currentScene.createDefaultCameraOrLight();
  17524. }
  17525. that._currentScene.activeCamera.attachControl(that._canvas);
  17526. if (that._sceneLoadedCallback) {
  17527. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17528. }
  17529. that._engine.runRenderLoop(function () {
  17530. that.renderFunction();
  17531. });
  17532. });
  17533. }, function (progress) {
  17534. if (_this._progressCallback) {
  17535. _this._progressCallback(progress);
  17536. }
  17537. });
  17538. }
  17539. else {
  17540. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17541. }
  17542. };
  17543. FilesInput.FilesTextures = new Array();
  17544. FilesInput.FilesToLoad = new Array();
  17545. return FilesInput;
  17546. })();
  17547. BABYLON.FilesInput = FilesInput;
  17548. })(BABYLON || (BABYLON = {}));
  17549. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17550. (function (BABYLON) {
  17551. var OimoJSPlugin = (function () {
  17552. function OimoJSPlugin() {
  17553. this._registeredMeshes = [];
  17554. /**
  17555. * Update the body position according to the mesh position
  17556. * @param mesh
  17557. */
  17558. this.updateBodyPosition = function (mesh) {
  17559. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17560. var registeredMesh = this._registeredMeshes[index];
  17561. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17562. var body = registeredMesh.body.body;
  17563. mesh.computeWorldMatrix(true);
  17564. var center = mesh.getBoundingInfo().boundingBox.center;
  17565. body.setPosition(center.x, center.y, center.z);
  17566. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17567. return;
  17568. }
  17569. // Case where the parent has been updated
  17570. if (registeredMesh.mesh.parent === mesh) {
  17571. mesh.computeWorldMatrix(true);
  17572. registeredMesh.mesh.computeWorldMatrix(true);
  17573. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17574. var absoluteRotation = mesh.rotation;
  17575. body = registeredMesh.body.body;
  17576. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17577. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17578. return;
  17579. }
  17580. }
  17581. };
  17582. }
  17583. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17584. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17585. };
  17586. OimoJSPlugin.prototype.initialize = function (iterations) {
  17587. this._world = new OIMO.World();
  17588. this._world.clear();
  17589. };
  17590. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17591. this._world.gravity = gravity;
  17592. };
  17593. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17594. var body = null;
  17595. this.unregisterMesh(mesh);
  17596. mesh.computeWorldMatrix(true);
  17597. var initialRotation = null;
  17598. if (mesh.rotationQuaternion) {
  17599. initialRotation = mesh.rotationQuaternion.clone();
  17600. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17601. mesh.computeWorldMatrix(true);
  17602. }
  17603. var bbox = mesh.getBoundingInfo().boundingBox;
  17604. // The delta between the mesh position and the mesh bounding box center
  17605. var deltaPosition = mesh.position.subtract(bbox.center);
  17606. // Transform delta position with the rotation
  17607. if (initialRotation) {
  17608. var m = new BABYLON.Matrix();
  17609. initialRotation.toRotationMatrix(m);
  17610. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17611. }
  17612. switch (impostor) {
  17613. case BABYLON.PhysicsEngine.SphereImpostor:
  17614. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17615. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17616. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17617. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17618. body = new OIMO.Body({
  17619. type: 'sphere',
  17620. size: [size],
  17621. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17622. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17623. move: options.mass != 0,
  17624. config: [options.mass, options.friction, options.restitution],
  17625. world: this._world
  17626. });
  17627. break;
  17628. case BABYLON.PhysicsEngine.PlaneImpostor:
  17629. case BABYLON.PhysicsEngine.CylinderImpostor:
  17630. case BABYLON.PhysicsEngine.BoxImpostor:
  17631. var min = bbox.minimumWorld;
  17632. var max = bbox.maximumWorld;
  17633. var box = max.subtract(min);
  17634. var sizeX = this._checkWithEpsilon(box.x);
  17635. var sizeY = this._checkWithEpsilon(box.y);
  17636. var sizeZ = this._checkWithEpsilon(box.z);
  17637. body = new OIMO.Body({
  17638. type: 'box',
  17639. size: [sizeX, sizeY, sizeZ],
  17640. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17641. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17642. move: options.mass != 0,
  17643. config: [options.mass, options.friction, options.restitution],
  17644. world: this._world
  17645. });
  17646. break;
  17647. }
  17648. //If quaternion was set as the rotation of the object
  17649. if (initialRotation) {
  17650. //We have to access the rigid body's properties to set the quaternion.
  17651. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17652. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17653. //update the internal rotation matrix
  17654. body.body.syncShapes();
  17655. }
  17656. this._registeredMeshes.push({
  17657. mesh: mesh,
  17658. body: body,
  17659. delta: deltaPosition
  17660. });
  17661. return body;
  17662. };
  17663. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17664. var types = [], sizes = [], positions = [], rotations = [];
  17665. var initialMesh = parts[0].mesh;
  17666. for (var index = 0; index < parts.length; index++) {
  17667. var part = parts[index];
  17668. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17669. types.push(bodyParameters.type);
  17670. sizes.push.apply(sizes, bodyParameters.size);
  17671. positions.push.apply(positions, bodyParameters.pos);
  17672. rotations.push.apply(rotations, bodyParameters.rot);
  17673. }
  17674. var body = new OIMO.Body({
  17675. type: types,
  17676. size: sizes,
  17677. pos: positions,
  17678. rot: rotations,
  17679. move: options.mass != 0,
  17680. config: [options.mass, options.friction, options.restitution],
  17681. world: this._world
  17682. });
  17683. this._registeredMeshes.push({
  17684. mesh: initialMesh,
  17685. body: body
  17686. });
  17687. return body;
  17688. };
  17689. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17690. var bodyParameters = null;
  17691. var mesh = part.mesh;
  17692. // We need the bounding box/sphere info to compute the physics body
  17693. mesh.computeWorldMatrix();
  17694. switch (part.impostor) {
  17695. case BABYLON.PhysicsEngine.SphereImpostor:
  17696. var bbox = mesh.getBoundingInfo().boundingBox;
  17697. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17698. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17699. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17700. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17701. bodyParameters = {
  17702. type: 'sphere',
  17703. /* bug with oimo : sphere needs 3 sizes in this case */
  17704. size: [size, -1, -1],
  17705. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17706. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17707. };
  17708. break;
  17709. case BABYLON.PhysicsEngine.PlaneImpostor:
  17710. case BABYLON.PhysicsEngine.BoxImpostor:
  17711. bbox = mesh.getBoundingInfo().boundingBox;
  17712. var min = bbox.minimumWorld;
  17713. var max = bbox.maximumWorld;
  17714. var box = max.subtract(min);
  17715. var sizeX = this._checkWithEpsilon(box.x);
  17716. var sizeY = this._checkWithEpsilon(box.y);
  17717. var sizeZ = this._checkWithEpsilon(box.z);
  17718. var relativePosition = mesh.position;
  17719. bodyParameters = {
  17720. type: 'box',
  17721. size: [sizeX, sizeY, sizeZ],
  17722. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17723. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17724. };
  17725. break;
  17726. }
  17727. return bodyParameters;
  17728. };
  17729. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17730. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17731. var registeredMesh = this._registeredMeshes[index];
  17732. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17733. if (registeredMesh.body) {
  17734. this._world.removeRigidBody(registeredMesh.body.body);
  17735. this._unbindBody(registeredMesh.body);
  17736. }
  17737. this._registeredMeshes.splice(index, 1);
  17738. return;
  17739. }
  17740. }
  17741. };
  17742. OimoJSPlugin.prototype._unbindBody = function (body) {
  17743. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17744. var registeredMesh = this._registeredMeshes[index];
  17745. if (registeredMesh.body === body) {
  17746. registeredMesh.body = null;
  17747. }
  17748. }
  17749. };
  17750. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17751. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17752. var registeredMesh = this._registeredMeshes[index];
  17753. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17754. // Get object mass to have a behaviour similar to cannon.js
  17755. var mass = registeredMesh.body.body.massInfo.mass;
  17756. // The force is scaled with the mass of object
  17757. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17758. return;
  17759. }
  17760. }
  17761. };
  17762. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17763. var body1 = null, body2 = null;
  17764. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17765. var registeredMesh = this._registeredMeshes[index];
  17766. if (registeredMesh.mesh === mesh1) {
  17767. body1 = registeredMesh.body.body;
  17768. }
  17769. else if (registeredMesh.mesh === mesh2) {
  17770. body2 = registeredMesh.body.body;
  17771. }
  17772. }
  17773. if (!body1 || !body2) {
  17774. return false;
  17775. }
  17776. if (!options) {
  17777. options = {};
  17778. }
  17779. new OIMO.Link({
  17780. type: options.type,
  17781. body1: body1,
  17782. body2: body2,
  17783. min: options.min,
  17784. max: options.max,
  17785. axe1: options.axe1,
  17786. axe2: options.axe2,
  17787. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17788. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17789. collision: options.collision,
  17790. spring: options.spring,
  17791. world: this._world
  17792. });
  17793. return true;
  17794. };
  17795. OimoJSPlugin.prototype.dispose = function () {
  17796. this._world.clear();
  17797. while (this._registeredMeshes.length) {
  17798. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17799. }
  17800. };
  17801. OimoJSPlugin.prototype.isSupported = function () {
  17802. return OIMO !== undefined;
  17803. };
  17804. OimoJSPlugin.prototype._getLastShape = function (body) {
  17805. var lastShape = body.shapes;
  17806. while (lastShape.next) {
  17807. lastShape = lastShape.next;
  17808. }
  17809. return lastShape;
  17810. };
  17811. OimoJSPlugin.prototype.runOneStep = function (time) {
  17812. this._world.step();
  17813. // Update the position of all registered meshes
  17814. var i = this._registeredMeshes.length;
  17815. var m;
  17816. while (i--) {
  17817. var body = this._registeredMeshes[i].body.body;
  17818. var mesh = this._registeredMeshes[i].mesh;
  17819. var delta = this._registeredMeshes[i].delta;
  17820. if (!body.sleeping) {
  17821. if (body.shapes.next) {
  17822. var parentShape = this._getLastShape(body);
  17823. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17824. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17825. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17826. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17827. if (!mesh.rotationQuaternion) {
  17828. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17829. }
  17830. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17831. mesh.computeWorldMatrix();
  17832. }
  17833. else {
  17834. m = body.getMatrix();
  17835. mtx = BABYLON.Matrix.FromArray(m);
  17836. // Body position
  17837. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17838. if (!delta) {
  17839. mesh.position.x = bodyX;
  17840. mesh.position.y = bodyY;
  17841. mesh.position.z = bodyZ;
  17842. }
  17843. else {
  17844. mesh.position.x = bodyX + delta.x;
  17845. mesh.position.y = bodyY + delta.y;
  17846. mesh.position.z = bodyZ + delta.z;
  17847. }
  17848. if (!mesh.rotationQuaternion) {
  17849. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17850. }
  17851. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17852. mesh.computeWorldMatrix();
  17853. }
  17854. }
  17855. }
  17856. };
  17857. return OimoJSPlugin;
  17858. })();
  17859. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17860. })(BABYLON || (BABYLON = {}));
  17861. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17862. (function (BABYLON) {
  17863. var PhysicsEngine = (function () {
  17864. function PhysicsEngine(plugin) {
  17865. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17866. }
  17867. PhysicsEngine.prototype._initialize = function (gravity) {
  17868. this._currentPlugin.initialize();
  17869. this._setGravity(gravity);
  17870. };
  17871. PhysicsEngine.prototype._runOneStep = function (delta) {
  17872. if (delta > 0.1) {
  17873. delta = 0.1;
  17874. }
  17875. else if (delta <= 0) {
  17876. delta = 1.0 / 60.0;
  17877. }
  17878. this._currentPlugin.runOneStep(delta);
  17879. };
  17880. PhysicsEngine.prototype._setGravity = function (gravity) {
  17881. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17882. this._currentPlugin.setGravity(this.gravity);
  17883. };
  17884. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17885. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17886. };
  17887. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17888. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17889. };
  17890. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17891. this._currentPlugin.unregisterMesh(mesh);
  17892. };
  17893. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17894. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17895. };
  17896. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17897. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17898. };
  17899. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17900. this._currentPlugin.updateBodyPosition(mesh);
  17901. };
  17902. PhysicsEngine.prototype.dispose = function () {
  17903. this._currentPlugin.dispose();
  17904. };
  17905. PhysicsEngine.prototype.isSupported = function () {
  17906. return this._currentPlugin.isSupported();
  17907. };
  17908. // Statics
  17909. PhysicsEngine.NoImpostor = 0;
  17910. PhysicsEngine.SphereImpostor = 1;
  17911. PhysicsEngine.BoxImpostor = 2;
  17912. PhysicsEngine.PlaneImpostor = 3;
  17913. PhysicsEngine.MeshImpostor = 4;
  17914. PhysicsEngine.CapsuleImpostor = 5;
  17915. PhysicsEngine.ConeImpostor = 6;
  17916. PhysicsEngine.CylinderImpostor = 7;
  17917. PhysicsEngine.ConvexHullImpostor = 8;
  17918. PhysicsEngine.Epsilon = 0.001;
  17919. return PhysicsEngine;
  17920. })();
  17921. BABYLON.PhysicsEngine = PhysicsEngine;
  17922. })(BABYLON || (BABYLON = {}));
  17923. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17924. (function (BABYLON) {
  17925. var serializeLight = function (light) {
  17926. var serializationObject = {};
  17927. serializationObject.name = light.name;
  17928. serializationObject.id = light.id;
  17929. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17930. if (light instanceof BABYLON.PointLight) {
  17931. serializationObject.type = 0;
  17932. serializationObject.position = light.position.asArray();
  17933. }
  17934. else if (light instanceof BABYLON.DirectionalLight) {
  17935. serializationObject.type = 1;
  17936. var directionalLight = light;
  17937. serializationObject.position = directionalLight.position.asArray();
  17938. serializationObject.direction = directionalLight.direction.asArray();
  17939. }
  17940. else if (light instanceof BABYLON.SpotLight) {
  17941. serializationObject.type = 2;
  17942. var spotLight = light;
  17943. serializationObject.position = spotLight.position.asArray();
  17944. serializationObject.direction = spotLight.position.asArray();
  17945. serializationObject.angle = spotLight.angle;
  17946. serializationObject.exponent = spotLight.exponent;
  17947. }
  17948. else if (light instanceof BABYLON.HemisphericLight) {
  17949. serializationObject.type = 3;
  17950. var hemisphericLight = light;
  17951. serializationObject.direction = hemisphericLight.direction.asArray();
  17952. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17953. }
  17954. if (light.intensity) {
  17955. serializationObject.intensity = light.intensity;
  17956. }
  17957. serializationObject.range = light.range;
  17958. serializationObject.diffuse = light.diffuse.asArray();
  17959. serializationObject.specular = light.specular.asArray();
  17960. return serializationObject;
  17961. };
  17962. var serializeFresnelParameter = function (fresnelParameter) {
  17963. var serializationObject = {};
  17964. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17965. serializationObject.leftColor = fresnelParameter.leftColor;
  17966. serializationObject.rightColor = fresnelParameter.rightColor;
  17967. serializationObject.bias = fresnelParameter.bias;
  17968. serializationObject.power = fresnelParameter.power;
  17969. return serializationObject;
  17970. };
  17971. var serializeCamera = function (camera) {
  17972. var serializationObject = {};
  17973. serializationObject.name = camera.name;
  17974. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17975. serializationObject.id = camera.id;
  17976. serializationObject.position = camera.position.asArray();
  17977. // Parent
  17978. if (camera.parent) {
  17979. serializationObject.parentId = camera.parent.id;
  17980. }
  17981. serializationObject.fov = camera.fov;
  17982. serializationObject.minZ = camera.minZ;
  17983. serializationObject.maxZ = camera.maxZ;
  17984. serializationObject.inertia = camera.inertia;
  17985. //setting the type
  17986. if (camera instanceof BABYLON.FreeCamera) {
  17987. serializationObject.type = "FreeCamera";
  17988. }
  17989. else if (camera instanceof BABYLON.ArcRotateCamera) {
  17990. serializationObject.type = "ArcRotateCamera";
  17991. }
  17992. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  17993. serializationObject.type = "AnaglyphArcRotateCamera";
  17994. }
  17995. else if (camera instanceof BABYLON.GamepadCamera) {
  17996. serializationObject.type = "GamepadCamera";
  17997. }
  17998. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  17999. serializationObject.type = "AnaglyphFreeCamera";
  18000. }
  18001. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18002. serializationObject.type = "DeviceOrientationCamera";
  18003. }
  18004. else if (camera instanceof BABYLON.FollowCamera) {
  18005. serializationObject.type = "FollowCamera";
  18006. }
  18007. else if (camera instanceof BABYLON.OculusCamera) {
  18008. serializationObject.type = "OculusCamera";
  18009. }
  18010. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18011. serializationObject.type = "OculusGamepadCamera";
  18012. }
  18013. else if (camera instanceof BABYLON.TouchCamera) {
  18014. serializationObject.type = "TouchCamera";
  18015. }
  18016. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18017. serializationObject.type = "VirtualJoysticksCamera";
  18018. }
  18019. else if (camera instanceof BABYLON.WebVRCamera) {
  18020. serializationObject.type = "WebVRCamera";
  18021. }
  18022. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18023. serializationObject.type = "VRDeviceOrientationCamera";
  18024. }
  18025. //special properties of specific cameras
  18026. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18027. var arcCamera = camera;
  18028. serializationObject.alpha = arcCamera.alpha;
  18029. serializationObject.beta = arcCamera.beta;
  18030. serializationObject.radius = arcCamera.radius;
  18031. }
  18032. else if (camera instanceof BABYLON.FollowCamera) {
  18033. var followCam = camera;
  18034. serializationObject.radius = followCam.radius;
  18035. serializationObject.heightOffset = followCam.heightOffset;
  18036. serializationObject.rotationOffset = followCam.rotationOffset;
  18037. }
  18038. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18039. //eye space is a private member and can only be access like this. Without changing the implementation this is the best way to get it.
  18040. if (camera['_eyeSpace'] !== undefined) {
  18041. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18042. }
  18043. }
  18044. //general properties that not all cameras have. The [] is due to typescript's type safety
  18045. if (camera['speed'] !== undefined) {
  18046. serializationObject.speed = camera['speed'];
  18047. }
  18048. // Target
  18049. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18050. serializationObject.rotation = camera['rotation'].asArray();
  18051. }
  18052. // Locked target
  18053. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18054. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18055. }
  18056. if (camera['checkCollisions'] !== undefined) {
  18057. serializationObject.checkCollisions = camera['checkCollisions'];
  18058. }
  18059. if (camera['applyGravity'] !== undefined) {
  18060. serializationObject.applyGravity = camera['applyGravity'];
  18061. }
  18062. if (camera['ellipsoid']) {
  18063. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18064. }
  18065. // Animations
  18066. appendAnimations(camera, serializationObject);
  18067. // Layer mask
  18068. serializationObject.layerMask = camera.layerMask;
  18069. return serializationObject;
  18070. };
  18071. var appendAnimations = function (source, destination) {
  18072. if (source.animations) {
  18073. destination.animations = [];
  18074. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18075. var animation = source.animations[animationIndex];
  18076. destination.animations.push(serializeAnimation(animation));
  18077. }
  18078. }
  18079. };
  18080. var serializeAnimation = function (animation) {
  18081. var serializationObject = {};
  18082. serializationObject.name = animation.name;
  18083. serializationObject.property = animation.targetProperty;
  18084. serializationObject.framePerSecond = animation.framePerSecond;
  18085. serializationObject.dataType = animation.dataType;
  18086. serializationObject.loopBehavior = animation.loopMode;
  18087. var dataType = animation.dataType;
  18088. serializationObject.keys = [];
  18089. var keys = animation.getKeys();
  18090. for (var index = 0; index < keys.length; index++) {
  18091. var animationKey = keys[index];
  18092. var key = {};
  18093. key.frame = animationKey.frame;
  18094. switch (dataType) {
  18095. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18096. key.values = [animationKey.value];
  18097. break;
  18098. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18099. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18100. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18101. key.values = animationKey.value.asArray();
  18102. break;
  18103. }
  18104. serializationObject.keys.push(key);
  18105. }
  18106. return serializationObject;
  18107. };
  18108. var serializeMultiMaterial = function (material) {
  18109. var serializationObject = {};
  18110. serializationObject.name = material.name;
  18111. serializationObject.id = material.id;
  18112. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18113. serializationObject.materials = [];
  18114. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18115. var subMat = material.subMaterials[matIndex];
  18116. if (subMat) {
  18117. serializationObject.materials.push(subMat.id);
  18118. }
  18119. else {
  18120. serializationObject.materials.push(null);
  18121. }
  18122. }
  18123. return serializationObject;
  18124. };
  18125. var serializeMaterial = function (material) {
  18126. var serializationObject = {};
  18127. serializationObject.name = material.name;
  18128. serializationObject.ambient = material.ambientColor.asArray();
  18129. serializationObject.diffuse = material.diffuseColor.asArray();
  18130. serializationObject.specular = material.specularColor.asArray();
  18131. serializationObject.specularPower = material.specularPower;
  18132. serializationObject.emissive = material.emissiveColor.asArray();
  18133. serializationObject.alpha = material.alpha;
  18134. serializationObject.id = material.id;
  18135. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18136. serializationObject.backFaceCulling = material.backFaceCulling;
  18137. if (material.diffuseTexture) {
  18138. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18139. }
  18140. if (material.diffuseFresnelParameters) {
  18141. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18142. }
  18143. if (material.ambientTexture) {
  18144. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18145. }
  18146. if (material.opacityTexture) {
  18147. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18148. }
  18149. if (material.opacityFresnelParameters) {
  18150. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18151. }
  18152. if (material.reflectionTexture) {
  18153. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18154. }
  18155. if (material.reflectionFresnelParameters) {
  18156. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18157. }
  18158. if (material.emissiveTexture) {
  18159. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18160. }
  18161. if (material.emissiveFresnelParameters) {
  18162. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18163. }
  18164. if (material.specularTexture) {
  18165. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18166. }
  18167. if (material.bumpTexture) {
  18168. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18169. }
  18170. return serializationObject;
  18171. };
  18172. var serializeTexture = function (texture) {
  18173. var serializationObject = {};
  18174. if (!texture.name) {
  18175. return null;
  18176. }
  18177. if (texture instanceof BABYLON.CubeTexture) {
  18178. serializationObject.name = texture.name;
  18179. serializationObject.hasAlpha = texture.hasAlpha;
  18180. serializationObject.level = texture.level;
  18181. serializationObject.coordinatesMode = texture.coordinatesMode;
  18182. return serializationObject;
  18183. }
  18184. if (texture instanceof BABYLON.MirrorTexture) {
  18185. var mirrorTexture = texture;
  18186. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18187. serializationObject.renderList = [];
  18188. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18189. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18190. }
  18191. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18192. }
  18193. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18194. var renderTargetTexture = texture;
  18195. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18196. serializationObject.renderList = [];
  18197. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18198. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18199. }
  18200. }
  18201. var regularTexture = texture;
  18202. serializationObject.name = texture.name;
  18203. serializationObject.hasAlpha = texture.hasAlpha;
  18204. serializationObject.level = texture.level;
  18205. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18206. serializationObject.coordinatesMode = texture.coordinatesMode;
  18207. serializationObject.uOffset = regularTexture.uOffset;
  18208. serializationObject.vOffset = regularTexture.vOffset;
  18209. serializationObject.uScale = regularTexture.uScale;
  18210. serializationObject.vScale = regularTexture.vScale;
  18211. serializationObject.uAng = regularTexture.uAng;
  18212. serializationObject.vAng = regularTexture.vAng;
  18213. serializationObject.wAng = regularTexture.wAng;
  18214. serializationObject.wrapU = texture.wrapU;
  18215. serializationObject.wrapV = texture.wrapV;
  18216. // Animations
  18217. appendAnimations(texture, serializationObject);
  18218. return serializationObject;
  18219. };
  18220. var serializeSkeleton = function (skeleton) {
  18221. var serializationObject = {};
  18222. serializationObject.name = skeleton.name;
  18223. serializationObject.id = skeleton.id;
  18224. serializationObject.bones = [];
  18225. for (var index = 0; index < skeleton.bones.length; index++) {
  18226. var bone = skeleton.bones[index];
  18227. var serializedBone = {
  18228. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18229. name: bone.name,
  18230. matrix: bone.getLocalMatrix().toArray()
  18231. };
  18232. serializationObject.bones.push(serializedBone);
  18233. if (bone.animations && bone.animations.length > 0) {
  18234. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18235. }
  18236. }
  18237. return serializationObject;
  18238. };
  18239. var serializeParticleSystem = function (particleSystem) {
  18240. var serializationObject = {};
  18241. serializationObject.emitterId = particleSystem.emitter.id;
  18242. serializationObject.capacity = particleSystem.getCapacity();
  18243. if (particleSystem.particleTexture) {
  18244. serializationObject.textureName = particleSystem.particleTexture.name;
  18245. }
  18246. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18247. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18248. serializationObject.minSize = particleSystem.minSize;
  18249. serializationObject.maxSize = particleSystem.maxSize;
  18250. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18251. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18252. serializationObject.emitRate = particleSystem.emitRate;
  18253. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18254. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18255. serializationObject.gravity = particleSystem.gravity.asArray();
  18256. serializationObject.direction1 = particleSystem.direction1.asArray();
  18257. serializationObject.direction2 = particleSystem.direction2.asArray();
  18258. serializationObject.color1 = particleSystem.color1.asArray();
  18259. serializationObject.color2 = particleSystem.color2.asArray();
  18260. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18261. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18262. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18263. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18264. serializationObject.blendMode = particleSystem.blendMode;
  18265. return serializationObject;
  18266. };
  18267. var serializeLensFlareSystem = function (lensFlareSystem) {
  18268. var serializationObject = {};
  18269. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18270. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18271. serializationObject.flares = [];
  18272. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18273. var flare = lensFlareSystem.lensFlares[index];
  18274. serializationObject.flares.push({
  18275. size: flare.size,
  18276. position: flare.position,
  18277. color: flare.color.asArray(),
  18278. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18279. });
  18280. }
  18281. return serializationObject;
  18282. };
  18283. var serializeShadowGenerator = function (light) {
  18284. var serializationObject = {};
  18285. var shadowGenerator = light.getShadowGenerator();
  18286. serializationObject.lightId = light.id;
  18287. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18288. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18289. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18290. serializationObject.renderList = [];
  18291. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18292. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18293. serializationObject.renderList.push(mesh.id);
  18294. }
  18295. return serializationObject;
  18296. };
  18297. var serializedGeometries = [];
  18298. var serializeGeometry = function (geometry, serializationGeometries) {
  18299. if (serializedGeometries[geometry.id]) {
  18300. return;
  18301. }
  18302. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18303. serializationGeometries.boxes.push(serializeBox(geometry));
  18304. }
  18305. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18306. serializationGeometries.spheres.push(serializeSphere(geometry));
  18307. }
  18308. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18309. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18310. }
  18311. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18312. serializationGeometries.toruses.push(serializeTorus(geometry));
  18313. }
  18314. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18315. serializationGeometries.grounds.push(serializeGround(geometry));
  18316. }
  18317. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18318. serializationGeometries.planes.push(serializePlane(geometry));
  18319. }
  18320. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18321. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18322. }
  18323. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18324. throw new Error("Unknow primitive type");
  18325. }
  18326. else {
  18327. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18328. }
  18329. serializedGeometries[geometry.id] = true;
  18330. };
  18331. var serializeGeometryBase = function (geometry) {
  18332. var serializationObject = {};
  18333. serializationObject.id = geometry.id;
  18334. if (BABYLON.Tags.HasTags(geometry)) {
  18335. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18336. }
  18337. return serializationObject;
  18338. };
  18339. var serializeVertexData = function (vertexData) {
  18340. var serializationObject = serializeGeometryBase(vertexData);
  18341. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18342. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18343. }
  18344. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18345. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18346. }
  18347. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18348. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18349. }
  18350. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18351. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18352. }
  18353. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18354. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18355. }
  18356. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18357. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18358. serializationObject.matricesIndices._isExpanded = true;
  18359. }
  18360. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18361. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18362. }
  18363. serializationObject.indices = vertexData.getIndices();
  18364. return serializationObject;
  18365. };
  18366. var serializePrimitive = function (primitive) {
  18367. var serializationObject = serializeGeometryBase(primitive);
  18368. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18369. return serializationObject;
  18370. };
  18371. var serializeBox = function (box) {
  18372. var serializationObject = serializePrimitive(box);
  18373. serializationObject.size = box.size;
  18374. return serializationObject;
  18375. };
  18376. var serializeSphere = function (sphere) {
  18377. var serializationObject = serializePrimitive(sphere);
  18378. serializationObject.segments = sphere.segments;
  18379. serializationObject.diameter = sphere.diameter;
  18380. return serializationObject;
  18381. };
  18382. var serializeCylinder = function (cylinder) {
  18383. var serializationObject = serializePrimitive(cylinder);
  18384. serializationObject.height = cylinder.height;
  18385. serializationObject.diameterTop = cylinder.diameterTop;
  18386. serializationObject.diameterBottom = cylinder.diameterBottom;
  18387. serializationObject.tessellation = cylinder.tessellation;
  18388. return serializationObject;
  18389. };
  18390. var serializeTorus = function (torus) {
  18391. var serializationObject = serializePrimitive(torus);
  18392. serializationObject.diameter = torus.diameter;
  18393. serializationObject.thickness = torus.thickness;
  18394. serializationObject.tessellation = torus.tessellation;
  18395. return serializationObject;
  18396. };
  18397. var serializeGround = function (ground) {
  18398. var serializationObject = serializePrimitive(ground);
  18399. serializationObject.width = ground.width;
  18400. serializationObject.height = ground.height;
  18401. serializationObject.subdivisions = ground.subdivisions;
  18402. return serializationObject;
  18403. };
  18404. var serializePlane = function (plane) {
  18405. var serializationObject = serializePrimitive(plane);
  18406. serializationObject.size = plane.size;
  18407. return serializationObject;
  18408. };
  18409. var serializeTorusKnot = function (torusKnot) {
  18410. var serializationObject = serializePrimitive(torusKnot);
  18411. serializationObject.radius = torusKnot.radius;
  18412. serializationObject.tube = torusKnot.tube;
  18413. serializationObject.radialSegments = torusKnot.radialSegments;
  18414. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18415. serializationObject.p = torusKnot.p;
  18416. serializationObject.q = torusKnot.q;
  18417. return serializationObject;
  18418. };
  18419. var serializeMesh = function (mesh, serializationScene) {
  18420. var serializationObject = {};
  18421. serializationObject.name = mesh.name;
  18422. serializationObject.id = mesh.id;
  18423. if (BABYLON.Tags.HasTags(mesh)) {
  18424. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18425. }
  18426. serializationObject.position = mesh.position.asArray();
  18427. if (mesh.rotationQuaternion) {
  18428. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18429. }
  18430. else if (mesh.rotation) {
  18431. serializationObject.rotation = mesh.rotation.asArray();
  18432. }
  18433. serializationObject.scaling = mesh.scaling.asArray();
  18434. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18435. serializationObject.isEnabled = mesh.isEnabled();
  18436. serializationObject.isVisible = mesh.isVisible;
  18437. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18438. serializationObject.pickable = mesh.isPickable;
  18439. serializationObject.receiveShadows = mesh.receiveShadows;
  18440. serializationObject.billboardMode = mesh.billboardMode;
  18441. serializationObject.visibility = mesh.visibility;
  18442. serializationObject.checkCollisions = mesh.checkCollisions;
  18443. // Parent
  18444. if (mesh.parent) {
  18445. serializationObject.parentId = mesh.parent.id;
  18446. }
  18447. // Geometry
  18448. var geometry = mesh._geometry;
  18449. if (geometry) {
  18450. var geometryId = geometry.id;
  18451. serializationObject.geometryId = geometryId;
  18452. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18453. // 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
  18454. serializeGeometry(geometry, serializationScene.geometries);
  18455. }
  18456. // SubMeshes
  18457. serializationObject.subMeshes = [];
  18458. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18459. var subMesh = mesh.subMeshes[subIndex];
  18460. serializationObject.subMeshes.push({
  18461. materialIndex: subMesh.materialIndex,
  18462. verticesStart: subMesh.verticesStart,
  18463. verticesCount: subMesh.verticesCount,
  18464. indexStart: subMesh.indexStart,
  18465. indexCount: subMesh.indexCount
  18466. });
  18467. }
  18468. }
  18469. // Material
  18470. if (mesh.material) {
  18471. serializationObject.materialId = mesh.material.id;
  18472. }
  18473. else {
  18474. mesh.material = null;
  18475. }
  18476. // Skeleton
  18477. if (mesh.skeleton) {
  18478. serializationObject.skeletonId = mesh.skeleton.id;
  18479. }
  18480. // Physics
  18481. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18482. serializationObject.physicsMass = mesh.getPhysicsMass();
  18483. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18484. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18485. switch (mesh.getPhysicsImpostor()) {
  18486. case BABYLON.PhysicsEngine.BoxImpostor:
  18487. serializationObject.physicsImpostor = 1;
  18488. break;
  18489. case BABYLON.PhysicsEngine.SphereImpostor:
  18490. serializationObject.physicsImpostor = 2;
  18491. break;
  18492. }
  18493. }
  18494. // Instances
  18495. serializationObject.instances = [];
  18496. for (var index = 0; index < mesh.instances.length; index++) {
  18497. var instance = mesh.instances[index];
  18498. var serializationInstance = {
  18499. name: instance.name,
  18500. position: instance.position,
  18501. rotation: instance.rotation,
  18502. rotationQuaternion: instance.rotationQuaternion,
  18503. scaling: instance.scaling
  18504. };
  18505. serializationObject.instances.push(serializationInstance);
  18506. // Animations
  18507. appendAnimations(instance, serializationInstance);
  18508. }
  18509. // Animations
  18510. appendAnimations(mesh, serializationObject);
  18511. // Layer mask
  18512. serializationObject.layerMask = mesh.layerMask;
  18513. return serializationObject;
  18514. };
  18515. var SceneSerializer = (function () {
  18516. function SceneSerializer() {
  18517. }
  18518. SceneSerializer.Serialize = function (scene) {
  18519. var serializationObject = {};
  18520. // Scene
  18521. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18522. serializationObject.autoClear = scene.autoClear;
  18523. serializationObject.clearColor = scene.clearColor.asArray();
  18524. serializationObject.ambientColor = scene.ambientColor.asArray();
  18525. serializationObject.gravity = scene.gravity.asArray();
  18526. // Fog
  18527. if (scene.fogMode && scene.fogMode !== 0) {
  18528. serializationObject.fogMode = scene.fogMode;
  18529. serializationObject.fogColor = scene.fogColor.asArray();
  18530. serializationObject.fogStart = scene.fogStart;
  18531. serializationObject.fogEnd = scene.fogEnd;
  18532. serializationObject.fogDensity = scene.fogDensity;
  18533. }
  18534. // Lights
  18535. serializationObject.lights = [];
  18536. for (var index = 0; index < scene.lights.length; index++) {
  18537. var light = scene.lights[index];
  18538. serializationObject.lights.push(serializeLight(light));
  18539. }
  18540. // Cameras
  18541. serializationObject.cameras = [];
  18542. for (index = 0; index < scene.cameras.length; index++) {
  18543. var camera = scene.cameras[index];
  18544. serializationObject.cameras.push(serializeCamera(camera));
  18545. }
  18546. if (scene.activeCamera) {
  18547. serializationObject.activeCameraID = scene.activeCamera.id;
  18548. }
  18549. // Materials
  18550. serializationObject.materials = [];
  18551. serializationObject.multiMaterials = [];
  18552. for (index = 0; index < scene.materials.length; index++) {
  18553. var material = scene.materials[index];
  18554. if (material instanceof BABYLON.StandardMaterial) {
  18555. serializationObject.materials.push(serializeMaterial(material));
  18556. }
  18557. else if (material instanceof BABYLON.MultiMaterial) {
  18558. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18559. }
  18560. }
  18561. // Skeletons
  18562. serializationObject.skeletons = [];
  18563. for (index = 0; index < scene.skeletons.length; index++) {
  18564. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18565. }
  18566. // Geometries
  18567. serializationObject.geometries = {};
  18568. serializationObject.geometries.boxes = [];
  18569. serializationObject.geometries.spheres = [];
  18570. serializationObject.geometries.cylinders = [];
  18571. serializationObject.geometries.toruses = [];
  18572. serializationObject.geometries.grounds = [];
  18573. serializationObject.geometries.planes = [];
  18574. serializationObject.geometries.torusKnots = [];
  18575. serializationObject.geometries.vertexData = [];
  18576. serializedGeometries = [];
  18577. var geometries = scene.getGeometries();
  18578. for (var index = 0; index < geometries.length; index++) {
  18579. var geometry = geometries[index];
  18580. if (geometry.isReady()) {
  18581. serializeGeometry(geometry, serializationObject.geometries);
  18582. }
  18583. }
  18584. // Meshes
  18585. serializationObject.meshes = [];
  18586. for (index = 0; index < scene.meshes.length; index++) {
  18587. var abstractMesh = scene.meshes[index];
  18588. if (abstractMesh instanceof BABYLON.Mesh) {
  18589. var mesh = abstractMesh;
  18590. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18591. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18592. }
  18593. }
  18594. }
  18595. // Particles Systems
  18596. serializationObject.particleSystems = [];
  18597. for (index = 0; index < scene.particleSystems.length; index++) {
  18598. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18599. }
  18600. // Lens flares
  18601. serializationObject.lensFlareSystems = [];
  18602. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18603. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18604. }
  18605. // Shadows
  18606. serializationObject.shadowGenerators = [];
  18607. for (index = 0; index < scene.lights.length; index++) {
  18608. light = scene.lights[index];
  18609. if (light.getShadowGenerator()) {
  18610. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18611. }
  18612. }
  18613. return serializationObject;
  18614. };
  18615. return SceneSerializer;
  18616. })();
  18617. BABYLON.SceneSerializer = SceneSerializer;
  18618. })(BABYLON || (BABYLON = {}));
  18619. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18620. (function (BABYLON) {
  18621. var SceneLoader = (function () {
  18622. function SceneLoader() {
  18623. }
  18624. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18625. get: function () {
  18626. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18627. },
  18628. set: function (value) {
  18629. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18630. },
  18631. enumerable: true,
  18632. configurable: true
  18633. });
  18634. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18635. get: function () {
  18636. return SceneLoader._ShowLoadingScreen;
  18637. },
  18638. set: function (value) {
  18639. SceneLoader._ShowLoadingScreen = value;
  18640. },
  18641. enumerable: true,
  18642. configurable: true
  18643. });
  18644. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18645. var dotPosition = sceneFilename.lastIndexOf(".");
  18646. var queryStringPosition = sceneFilename.indexOf("?");
  18647. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18648. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18649. var plugin = this._registeredPlugins[index];
  18650. if (plugin.extensions.indexOf(extension) !== -1) {
  18651. return plugin;
  18652. }
  18653. }
  18654. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18655. };
  18656. // Public functions
  18657. SceneLoader.RegisterPlugin = function (plugin) {
  18658. plugin.extensions = plugin.extensions.toLowerCase();
  18659. SceneLoader._registeredPlugins.push(plugin);
  18660. };
  18661. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18662. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18663. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18664. return;
  18665. }
  18666. var manifestChecked = function (success) {
  18667. scene.database = database;
  18668. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18669. var importMeshFromData = function (data) {
  18670. var meshes = [];
  18671. var particleSystems = [];
  18672. var skeletons = [];
  18673. try {
  18674. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18675. if (onerror) {
  18676. onerror(scene, 'unable to load the scene');
  18677. }
  18678. return;
  18679. }
  18680. }
  18681. catch (e) {
  18682. if (onerror) {
  18683. onerror(scene, e);
  18684. }
  18685. return;
  18686. }
  18687. if (onsuccess) {
  18688. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18689. onsuccess(meshes, particleSystems, skeletons);
  18690. }
  18691. };
  18692. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18693. // Direct load
  18694. importMeshFromData(sceneFilename.substr(5));
  18695. return;
  18696. }
  18697. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18698. importMeshFromData(data);
  18699. }, progressCallBack, database);
  18700. };
  18701. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18702. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18703. };
  18704. /**
  18705. * Load a scene
  18706. * @param rootUrl a string that defines the root url for scene and resources
  18707. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18708. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18709. */
  18710. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18711. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18712. };
  18713. /**
  18714. * Append a scene
  18715. * @param rootUrl a string that defines the root url for scene and resources
  18716. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18717. * @param scene is the instance of BABYLON.Scene to append to
  18718. */
  18719. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18720. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18721. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18722. return;
  18723. }
  18724. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18725. var database;
  18726. if (SceneLoader.ShowLoadingScreen) {
  18727. scene.getEngine().displayLoadingUI();
  18728. }
  18729. var loadSceneFromData = function (data) {
  18730. scene.database = database;
  18731. if (!plugin.load(scene, data, rootUrl)) {
  18732. if (onerror) {
  18733. onerror(scene);
  18734. }
  18735. scene.getEngine().hideLoadingUI();
  18736. return;
  18737. }
  18738. if (onsuccess) {
  18739. onsuccess(scene);
  18740. }
  18741. if (SceneLoader.ShowLoadingScreen) {
  18742. scene.executeWhenReady(function () {
  18743. scene.getEngine().hideLoadingUI();
  18744. });
  18745. }
  18746. };
  18747. var manifestChecked = function (success) {
  18748. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18749. };
  18750. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18751. // Direct load
  18752. loadSceneFromData(sceneFilename.substr(5));
  18753. return;
  18754. }
  18755. if (rootUrl.indexOf("file:") === -1) {
  18756. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18757. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18758. }
  18759. else {
  18760. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18761. }
  18762. };
  18763. // Flags
  18764. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18765. SceneLoader._ShowLoadingScreen = true;
  18766. // Members
  18767. SceneLoader._registeredPlugins = new Array();
  18768. return SceneLoader;
  18769. })();
  18770. BABYLON.SceneLoader = SceneLoader;
  18771. ;
  18772. })(BABYLON || (BABYLON = {}));
  18773. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18774. (function (BABYLON) {
  18775. var Internals;
  18776. (function (Internals) {
  18777. var checkColors4 = function (colors, count) {
  18778. // Check if color3 was used
  18779. if (colors.length === count * 3) {
  18780. var colors4 = [];
  18781. for (var index = 0; index < colors.length; index += 3) {
  18782. var newIndex = (index / 3) * 4;
  18783. colors4[newIndex] = colors[index];
  18784. colors4[newIndex + 1] = colors[index + 1];
  18785. colors4[newIndex + 2] = colors[index + 2];
  18786. colors4[newIndex + 3] = 1.0;
  18787. }
  18788. return colors4;
  18789. }
  18790. return colors;
  18791. };
  18792. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18793. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18794. texture.name = parsedTexture.name;
  18795. texture.hasAlpha = parsedTexture.hasAlpha;
  18796. texture.level = parsedTexture.level;
  18797. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18798. return texture;
  18799. };
  18800. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18801. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18802. return null;
  18803. }
  18804. if (parsedTexture.isCube) {
  18805. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18806. }
  18807. var texture;
  18808. if (parsedTexture.mirrorPlane) {
  18809. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18810. texture._waitingRenderList = parsedTexture.renderList;
  18811. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18812. }
  18813. else if (parsedTexture.isRenderTarget) {
  18814. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18815. texture._waitingRenderList = parsedTexture.renderList;
  18816. }
  18817. else {
  18818. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18819. }
  18820. texture.name = parsedTexture.name;
  18821. texture.hasAlpha = parsedTexture.hasAlpha;
  18822. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18823. texture.level = parsedTexture.level;
  18824. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18825. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18826. texture.uOffset = parsedTexture.uOffset;
  18827. texture.vOffset = parsedTexture.vOffset;
  18828. texture.uScale = parsedTexture.uScale;
  18829. texture.vScale = parsedTexture.vScale;
  18830. texture.uAng = parsedTexture.uAng;
  18831. texture.vAng = parsedTexture.vAng;
  18832. texture.wAng = parsedTexture.wAng;
  18833. texture.wrapU = parsedTexture.wrapU;
  18834. texture.wrapV = parsedTexture.wrapV;
  18835. // Animations
  18836. if (parsedTexture.animations) {
  18837. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18838. var parsedAnimation = parsedTexture.animations[animationIndex];
  18839. texture.animations.push(parseAnimation(parsedAnimation));
  18840. }
  18841. }
  18842. return texture;
  18843. };
  18844. var parseSkeleton = function (parsedSkeleton, scene) {
  18845. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18846. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18847. var parsedBone = parsedSkeleton.bones[index];
  18848. var parentBone = null;
  18849. if (parsedBone.parentBoneIndex > -1) {
  18850. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18851. }
  18852. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18853. if (parsedBone.animation) {
  18854. bone.animations.push(parseAnimation(parsedBone.animation));
  18855. }
  18856. }
  18857. return skeleton;
  18858. };
  18859. var parseFresnelParameters = function (parsedFresnelParameters) {
  18860. var fresnelParameters = new BABYLON.FresnelParameters();
  18861. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18862. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18863. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18864. fresnelParameters.bias = parsedFresnelParameters.bias;
  18865. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18866. return fresnelParameters;
  18867. };
  18868. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18869. var material;
  18870. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18871. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18872. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18873. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18874. material.specularPower = parsedMaterial.specularPower;
  18875. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18876. material.alpha = parsedMaterial.alpha;
  18877. material.id = parsedMaterial.id;
  18878. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18879. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18880. material.wireframe = parsedMaterial.wireframe;
  18881. if (parsedMaterial.diffuseTexture) {
  18882. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18883. }
  18884. if (parsedMaterial.diffuseFresnelParameters) {
  18885. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18886. }
  18887. if (parsedMaterial.ambientTexture) {
  18888. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18889. }
  18890. if (parsedMaterial.opacityTexture) {
  18891. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18892. }
  18893. if (parsedMaterial.opacityFresnelParameters) {
  18894. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18895. }
  18896. if (parsedMaterial.reflectionTexture) {
  18897. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18898. }
  18899. if (parsedMaterial.reflectionFresnelParameters) {
  18900. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18901. }
  18902. if (parsedMaterial.emissiveTexture) {
  18903. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18904. }
  18905. if (parsedMaterial.emissiveFresnelParameters) {
  18906. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18907. }
  18908. if (parsedMaterial.specularTexture) {
  18909. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18910. }
  18911. if (parsedMaterial.bumpTexture) {
  18912. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18913. }
  18914. return material;
  18915. };
  18916. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18917. for (var index = 0; index < parsedData.materials.length; index++) {
  18918. var parsedMaterial = parsedData.materials[index];
  18919. if (parsedMaterial.id === id) {
  18920. return parseMaterial(parsedMaterial, scene, rootUrl);
  18921. }
  18922. }
  18923. return null;
  18924. };
  18925. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18926. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18927. multiMaterial.id = parsedMultiMaterial.id;
  18928. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18929. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18930. var subMatId = parsedMultiMaterial.materials[matIndex];
  18931. if (subMatId) {
  18932. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18933. }
  18934. else {
  18935. multiMaterial.subMaterials.push(null);
  18936. }
  18937. }
  18938. return multiMaterial;
  18939. };
  18940. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18941. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18942. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18943. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18944. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18945. var parsedFlare = parsedLensFlareSystem.flares[index];
  18946. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18947. }
  18948. return lensFlareSystem;
  18949. };
  18950. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18951. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18952. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18953. if (parsedParticleSystem.textureName) {
  18954. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18955. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18956. }
  18957. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18958. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18959. particleSystem.minSize = parsedParticleSystem.minSize;
  18960. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18961. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18962. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18963. particleSystem.emitter = emitter;
  18964. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18965. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18966. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18967. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18968. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18969. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18970. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18971. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18972. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18973. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18974. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18975. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18976. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18977. particleSystem.start();
  18978. return particleSystem;
  18979. };
  18980. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18981. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18982. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18983. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18984. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18985. shadowGenerator.getShadowMap().renderList.push(mesh);
  18986. }
  18987. if (parsedShadowGenerator.usePoissonSampling) {
  18988. shadowGenerator.usePoissonSampling = true;
  18989. }
  18990. else if (parsedShadowGenerator.useVarianceShadowMap) {
  18991. shadowGenerator.useVarianceShadowMap = true;
  18992. }
  18993. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  18994. shadowGenerator.useBlurVarianceShadowMap = true;
  18995. }
  18996. if (parsedShadowGenerator.bias) {
  18997. shadowGenerator.bias = parsedShadowGenerator.bias;
  18998. }
  18999. return shadowGenerator;
  19000. };
  19001. var parseAnimation = function (parsedAnimation) {
  19002. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19003. var dataType = parsedAnimation.dataType;
  19004. var keys = [];
  19005. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19006. var key = parsedAnimation.keys[index];
  19007. var data;
  19008. switch (dataType) {
  19009. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19010. data = key.values[0];
  19011. break;
  19012. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19013. data = BABYLON.Quaternion.FromArray(key.values);
  19014. break;
  19015. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19016. data = BABYLON.Matrix.FromArray(key.values);
  19017. break;
  19018. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19019. default:
  19020. data = BABYLON.Vector3.FromArray(key.values);
  19021. break;
  19022. }
  19023. keys.push({
  19024. frame: key.frame,
  19025. value: data
  19026. });
  19027. }
  19028. animation.setKeys(keys);
  19029. return animation;
  19030. };
  19031. var parseLight = function (parsedLight, scene) {
  19032. var light;
  19033. switch (parsedLight.type) {
  19034. case 0:
  19035. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19036. break;
  19037. case 1:
  19038. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19039. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19040. break;
  19041. case 2:
  19042. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19043. break;
  19044. case 3:
  19045. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19046. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19047. break;
  19048. }
  19049. light.id = parsedLight.id;
  19050. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19051. if (parsedLight.intensity !== undefined) {
  19052. light.intensity = parsedLight.intensity;
  19053. }
  19054. if (parsedLight.range) {
  19055. light.range = parsedLight.range;
  19056. }
  19057. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19058. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19059. if (parsedLight.excludedMeshesIds) {
  19060. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19061. }
  19062. // Parent
  19063. if (parsedLight.parentId) {
  19064. light._waitingParentId = parsedLight.parentId;
  19065. }
  19066. if (parsedLight.includedOnlyMeshesIds) {
  19067. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19068. }
  19069. // Animations
  19070. if (parsedLight.animations) {
  19071. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19072. var parsedAnimation = parsedLight.animations[animationIndex];
  19073. light.animations.push(parseAnimation(parsedAnimation));
  19074. }
  19075. }
  19076. if (parsedLight.autoAnimate) {
  19077. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19078. }
  19079. };
  19080. var parseCamera = function (parsedCamera, scene) {
  19081. var camera;
  19082. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19083. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19084. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19085. var alpha = parsedCamera.alpha;
  19086. var beta = parsedCamera.beta;
  19087. var radius = parsedCamera.radius;
  19088. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19089. var eye_space = parsedCamera.eye_space;
  19090. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19091. }
  19092. else {
  19093. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19094. }
  19095. }
  19096. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19097. eye_space = parsedCamera.eye_space;
  19098. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19099. }
  19100. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19101. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19102. }
  19103. else if (parsedCamera.type === "FollowCamera") {
  19104. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19105. camera.heightOffset = parsedCamera.heightOffset;
  19106. camera.radius = parsedCamera.radius;
  19107. camera.rotationOffset = parsedCamera.rotationOffset;
  19108. if (lockedTargetMesh)
  19109. camera.target = lockedTargetMesh;
  19110. }
  19111. else if (parsedCamera.type === "GamepadCamera") {
  19112. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19113. }
  19114. else if (parsedCamera.type === "OculusCamera") {
  19115. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19116. }
  19117. else if (parsedCamera.type === "OculusGamepadCamera") {
  19118. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19119. }
  19120. else if (parsedCamera.type === "TouchCamera") {
  19121. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19122. }
  19123. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19124. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19125. }
  19126. else if (parsedCamera.type === "WebVRCamera") {
  19127. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19128. }
  19129. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19130. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19131. }
  19132. else {
  19133. // Free Camera is the default value
  19134. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19135. }
  19136. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19137. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19138. camera.lockedTarget = lockedTargetMesh;
  19139. }
  19140. camera.id = parsedCamera.id;
  19141. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19142. // Parent
  19143. if (parsedCamera.parentId) {
  19144. camera._waitingParentId = parsedCamera.parentId;
  19145. }
  19146. // Target
  19147. if (parsedCamera.target) {
  19148. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19149. }
  19150. else {
  19151. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19152. }
  19153. camera.fov = parsedCamera.fov;
  19154. camera.minZ = parsedCamera.minZ;
  19155. camera.maxZ = parsedCamera.maxZ;
  19156. camera.speed = parsedCamera.speed;
  19157. camera.inertia = parsedCamera.inertia;
  19158. camera.checkCollisions = parsedCamera.checkCollisions;
  19159. camera.applyGravity = parsedCamera.applyGravity;
  19160. if (parsedCamera.ellipsoid) {
  19161. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19162. }
  19163. // Animations
  19164. if (parsedCamera.animations) {
  19165. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19166. var parsedAnimation = parsedCamera.animations[animationIndex];
  19167. camera.animations.push(parseAnimation(parsedAnimation));
  19168. }
  19169. }
  19170. if (parsedCamera.autoAnimate) {
  19171. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19172. }
  19173. // Layer Mask
  19174. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19175. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19176. }
  19177. else {
  19178. camera.layerMask = 0xFFFFFFFF;
  19179. }
  19180. return camera;
  19181. };
  19182. var parseGeometry = function (parsedGeometry, scene) {
  19183. var id = parsedGeometry.id;
  19184. return scene.getGeometryByID(id);
  19185. };
  19186. var parseBox = function (parsedBox, scene) {
  19187. if (parseGeometry(parsedBox, scene)) {
  19188. return null; // null since geometry could be something else than a box...
  19189. }
  19190. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19191. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19192. scene.pushGeometry(box, true);
  19193. return box;
  19194. };
  19195. var parseSphere = function (parsedSphere, scene) {
  19196. if (parseGeometry(parsedSphere, scene)) {
  19197. return null; // null since geometry could be something else than a sphere...
  19198. }
  19199. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19200. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19201. scene.pushGeometry(sphere, true);
  19202. return sphere;
  19203. };
  19204. var parseCylinder = function (parsedCylinder, scene) {
  19205. if (parseGeometry(parsedCylinder, scene)) {
  19206. return null; // null since geometry could be something else than a cylinder...
  19207. }
  19208. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19209. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19210. scene.pushGeometry(cylinder, true);
  19211. return cylinder;
  19212. };
  19213. var parseTorus = function (parsedTorus, scene) {
  19214. if (parseGeometry(parsedTorus, scene)) {
  19215. return null; // null since geometry could be something else than a torus...
  19216. }
  19217. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19218. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19219. scene.pushGeometry(torus, true);
  19220. return torus;
  19221. };
  19222. var parseGround = function (parsedGround, scene) {
  19223. if (parseGeometry(parsedGround, scene)) {
  19224. return null; // null since geometry could be something else than a ground...
  19225. }
  19226. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19227. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19228. scene.pushGeometry(ground, true);
  19229. return ground;
  19230. };
  19231. var parsePlane = function (parsedPlane, scene) {
  19232. if (parseGeometry(parsedPlane, scene)) {
  19233. return null; // null since geometry could be something else than a plane...
  19234. }
  19235. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19236. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19237. scene.pushGeometry(plane, true);
  19238. return plane;
  19239. };
  19240. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19241. if (parseGeometry(parsedTorusKnot, scene)) {
  19242. return null; // null since geometry could be something else than a torusKnot...
  19243. }
  19244. 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);
  19245. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19246. scene.pushGeometry(torusKnot, true);
  19247. return torusKnot;
  19248. };
  19249. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19250. if (parseGeometry(parsedVertexData, scene)) {
  19251. return null; // null since geometry could be a primitive
  19252. }
  19253. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19254. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19255. if (parsedVertexData.delayLoadingFile) {
  19256. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19257. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19258. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19259. geometry._delayInfo = [];
  19260. if (parsedVertexData.hasUVs) {
  19261. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19262. }
  19263. if (parsedVertexData.hasUVs2) {
  19264. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19265. }
  19266. if (parsedVertexData.hasColors) {
  19267. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19268. }
  19269. if (parsedVertexData.hasMatricesIndices) {
  19270. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19271. }
  19272. if (parsedVertexData.hasMatricesWeights) {
  19273. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19274. }
  19275. geometry._delayLoadingFunction = importVertexData;
  19276. }
  19277. else {
  19278. importVertexData(parsedVertexData, geometry);
  19279. }
  19280. scene.pushGeometry(geometry, true);
  19281. return geometry;
  19282. };
  19283. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19284. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19285. mesh.id = parsedMesh.id;
  19286. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19287. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19288. if (parsedMesh.rotationQuaternion) {
  19289. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19290. }
  19291. else if (parsedMesh.rotation) {
  19292. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19293. }
  19294. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19295. if (parsedMesh.localMatrix) {
  19296. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19297. }
  19298. else if (parsedMesh.pivotMatrix) {
  19299. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19300. }
  19301. mesh.setEnabled(parsedMesh.isEnabled);
  19302. mesh.isVisible = parsedMesh.isVisible;
  19303. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19304. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19305. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19306. if (parsedMesh.applyFog !== undefined) {
  19307. mesh.applyFog = parsedMesh.applyFog;
  19308. }
  19309. if (parsedMesh.pickable !== undefined) {
  19310. mesh.isPickable = parsedMesh.pickable;
  19311. }
  19312. if (parsedMesh.alphaIndex !== undefined) {
  19313. mesh.alphaIndex = parsedMesh.alphaIndex;
  19314. }
  19315. mesh.receiveShadows = parsedMesh.receiveShadows;
  19316. mesh.billboardMode = parsedMesh.billboardMode;
  19317. if (parsedMesh.visibility !== undefined) {
  19318. mesh.visibility = parsedMesh.visibility;
  19319. }
  19320. mesh.checkCollisions = parsedMesh.checkCollisions;
  19321. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19322. // Parent
  19323. if (parsedMesh.parentId) {
  19324. mesh._waitingParentId = parsedMesh.parentId;
  19325. }
  19326. // Actions
  19327. if (parsedMesh.actions !== undefined) {
  19328. mesh._waitingActions = parsedMesh.actions;
  19329. }
  19330. // Geometry
  19331. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19332. if (parsedMesh.delayLoadingFile) {
  19333. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19334. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19335. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19336. if (parsedMesh._binaryInfo) {
  19337. mesh._binaryInfo = parsedMesh._binaryInfo;
  19338. }
  19339. mesh._delayInfo = [];
  19340. if (parsedMesh.hasUVs) {
  19341. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19342. }
  19343. if (parsedMesh.hasUVs2) {
  19344. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19345. }
  19346. if (parsedMesh.hasColors) {
  19347. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19348. }
  19349. if (parsedMesh.hasMatricesIndices) {
  19350. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19351. }
  19352. if (parsedMesh.hasMatricesWeights) {
  19353. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19354. }
  19355. mesh._delayLoadingFunction = importGeometry;
  19356. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19357. mesh._checkDelayState();
  19358. }
  19359. }
  19360. else {
  19361. importGeometry(parsedMesh, mesh);
  19362. }
  19363. // Material
  19364. if (parsedMesh.materialId) {
  19365. mesh.setMaterialByID(parsedMesh.materialId);
  19366. }
  19367. else {
  19368. mesh.material = null;
  19369. }
  19370. // Skeleton
  19371. if (parsedMesh.skeletonId > -1) {
  19372. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19373. }
  19374. // Physics
  19375. if (parsedMesh.physicsImpostor) {
  19376. if (!scene.isPhysicsEnabled()) {
  19377. scene.enablePhysics();
  19378. }
  19379. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19380. }
  19381. // Animations
  19382. if (parsedMesh.animations) {
  19383. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19384. var parsedAnimation = parsedMesh.animations[animationIndex];
  19385. mesh.animations.push(parseAnimation(parsedAnimation));
  19386. }
  19387. }
  19388. if (parsedMesh.autoAnimate) {
  19389. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19390. }
  19391. // Layer Mask
  19392. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19393. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19394. }
  19395. else {
  19396. mesh.layerMask = 0xFFFFFFFF;
  19397. }
  19398. // Instances
  19399. if (parsedMesh.instances) {
  19400. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19401. var parsedInstance = parsedMesh.instances[index];
  19402. var instance = mesh.createInstance(parsedInstance.name);
  19403. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19404. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19405. if (parsedInstance.rotationQuaternion) {
  19406. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19407. }
  19408. else if (parsedInstance.rotation) {
  19409. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19410. }
  19411. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19412. instance.checkCollisions = mesh.checkCollisions;
  19413. if (parsedMesh.animations) {
  19414. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19415. parsedAnimation = parsedMesh.animations[animationIndex];
  19416. instance.animations.push(parseAnimation(parsedAnimation));
  19417. }
  19418. }
  19419. }
  19420. }
  19421. return mesh;
  19422. };
  19423. var parseActions = function (parsedActions, object, scene) {
  19424. var actionManager = new BABYLON.ActionManager(scene);
  19425. if (object === null)
  19426. scene.actionManager = actionManager;
  19427. else
  19428. object.actionManager = actionManager;
  19429. // instanciate a new object
  19430. var instanciate = function (name, params) {
  19431. var newInstance = Object.create(BABYLON[name].prototype);
  19432. newInstance.constructor.apply(newInstance, params);
  19433. return newInstance;
  19434. };
  19435. var parseParameter = function (name, value, target, propertyPath) {
  19436. if (propertyPath === null) {
  19437. // String, boolean or float
  19438. var floatValue = parseFloat(value);
  19439. if (value === "true" || value === "false")
  19440. return value === "true";
  19441. else
  19442. return isNaN(floatValue) ? value : floatValue;
  19443. }
  19444. var effectiveTarget = propertyPath.split(".");
  19445. var values = value.split(",");
  19446. for (var i = 0; i < effectiveTarget.length; i++) {
  19447. target = target[effectiveTarget[i]];
  19448. }
  19449. // Return appropriate value with its type
  19450. if (target instanceof Boolean)
  19451. return values[0] === "true";
  19452. if (target instanceof String)
  19453. return values[0];
  19454. // Parameters with multiple values such as Vector3 etc.
  19455. var split = new Array();
  19456. for (var i = 0; i < values.length; i++)
  19457. split.push(parseFloat(values[i]));
  19458. if (target instanceof BABYLON.Vector3)
  19459. return BABYLON.Vector3.FromArray(split);
  19460. if (target instanceof BABYLON.Vector4)
  19461. return BABYLON.Vector4.FromArray(split);
  19462. if (target instanceof BABYLON.Color3)
  19463. return BABYLON.Color3.FromArray(split);
  19464. if (target instanceof BABYLON.Color4)
  19465. return BABYLON.Color4.FromArray(split);
  19466. return parseFloat(values[0]);
  19467. };
  19468. // traverse graph per trigger
  19469. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19470. if (combineArray === void 0) { combineArray = null; }
  19471. if (parsedAction.detached)
  19472. return;
  19473. var parameters = new Array();
  19474. var target = null;
  19475. var propertyPath = null;
  19476. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19477. // Parameters
  19478. if (parsedAction.type === 2)
  19479. parameters.push(actionManager);
  19480. else
  19481. parameters.push(trigger);
  19482. if (combine) {
  19483. var actions = new Array();
  19484. for (var j = 0; j < parsedAction.combine.length; j++) {
  19485. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19486. }
  19487. parameters.push(actions);
  19488. }
  19489. else {
  19490. for (var i = 0; i < parsedAction.properties.length; i++) {
  19491. var value = parsedAction.properties[i].value;
  19492. var name = parsedAction.properties[i].name;
  19493. if (name === "target")
  19494. value = target = scene.getNodeByName(value);
  19495. else if (name === "parent")
  19496. value = scene.getNodeByName(value);
  19497. else if (name === "sound")
  19498. value = scene.getSoundByName(value);
  19499. else if (name !== "propertyPath") {
  19500. if (parsedAction.type === 2 && name === "operator")
  19501. value = BABYLON.ValueCondition[value];
  19502. else
  19503. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19504. }
  19505. else {
  19506. propertyPath = value;
  19507. }
  19508. parameters.push(value);
  19509. }
  19510. }
  19511. parameters.push(condition);
  19512. // If interpolate value action
  19513. if (parsedAction.name === "InterpolateValueAction") {
  19514. var param = parameters[parameters.length - 2];
  19515. parameters[parameters.length - 1] = param;
  19516. parameters[parameters.length - 2] = condition;
  19517. }
  19518. // Action or condition(s) and not CombineAction
  19519. var newAction = instanciate(parsedAction.name, parameters);
  19520. if (combineArray === null) {
  19521. if (newAction instanceof BABYLON.Condition) {
  19522. condition = newAction;
  19523. newAction = action;
  19524. }
  19525. else {
  19526. condition = null;
  19527. if (action)
  19528. action.then(newAction);
  19529. else
  19530. actionManager.registerAction(newAction);
  19531. }
  19532. }
  19533. else {
  19534. combineArray.push(newAction);
  19535. }
  19536. for (var i = 0; i < parsedAction.children.length; i++)
  19537. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19538. };
  19539. for (var i = 0; i < parsedActions.children.length; i++) {
  19540. var triggerParams;
  19541. var trigger = parsedActions.children[i];
  19542. if (trigger.properties.length > 0) {
  19543. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19544. }
  19545. else
  19546. triggerParams = BABYLON.ActionManager[trigger.name];
  19547. for (var j = 0; j < trigger.children.length; j++)
  19548. traverse(trigger.children[j], triggerParams, null, null);
  19549. }
  19550. };
  19551. var parseSound = function (parsedSound, scene, rootUrl) {
  19552. var soundName = parsedSound.name;
  19553. var soundUrl = rootUrl + soundName;
  19554. var options = {
  19555. autoplay: parsedSound.autoplay,
  19556. loop: parsedSound.loop,
  19557. volume: parsedSound.volume,
  19558. spatialSound: parsedSound.spatialSound,
  19559. maxDistance: parsedSound.maxDistance,
  19560. rolloffFactor: parsedSound.rolloffFactor,
  19561. refDistance: parsedSound.refDistance,
  19562. distanceModel: parsedSound.distanceModel,
  19563. panningModel: parsedSound.panningModel,
  19564. playbackRate: parsedSound.playbackRate
  19565. };
  19566. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19567. scene._removePendingData(newSound);
  19568. }, options);
  19569. scene._addPendingData(newSound);
  19570. if (parsedSound.position) {
  19571. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19572. newSound.setPosition(soundPosition);
  19573. }
  19574. if (parsedSound.isDirectional) {
  19575. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19576. if (parsedSound.localDirectionToMesh) {
  19577. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19578. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19579. }
  19580. }
  19581. if (parsedSound.connectedMeshId) {
  19582. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19583. if (connectedMesh) {
  19584. newSound.attachToMesh(connectedMesh);
  19585. }
  19586. }
  19587. };
  19588. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19589. names = (names instanceof Array) ? names : [names];
  19590. for (var i in names) {
  19591. if (mesh.name === names[i]) {
  19592. hierarchyIds.push(mesh.id);
  19593. return true;
  19594. }
  19595. }
  19596. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19597. hierarchyIds.push(mesh.id);
  19598. return true;
  19599. }
  19600. return false;
  19601. };
  19602. var importVertexData = function (parsedVertexData, geometry) {
  19603. var vertexData = new BABYLON.VertexData();
  19604. // positions
  19605. var positions = parsedVertexData.positions;
  19606. if (positions) {
  19607. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19608. }
  19609. // normals
  19610. var normals = parsedVertexData.normals;
  19611. if (normals) {
  19612. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19613. }
  19614. // uvs
  19615. var uvs = parsedVertexData.uvs;
  19616. if (uvs) {
  19617. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19618. }
  19619. // uv2s
  19620. var uv2s = parsedVertexData.uv2s;
  19621. if (uv2s) {
  19622. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19623. }
  19624. // colors
  19625. var colors = parsedVertexData.colors;
  19626. if (colors) {
  19627. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19628. }
  19629. // matricesIndices
  19630. var matricesIndices = parsedVertexData.matricesIndices;
  19631. if (matricesIndices) {
  19632. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19633. }
  19634. // matricesWeights
  19635. var matricesWeights = parsedVertexData.matricesWeights;
  19636. if (matricesWeights) {
  19637. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19638. }
  19639. // indices
  19640. var indices = parsedVertexData.indices;
  19641. if (indices) {
  19642. vertexData.indices = indices;
  19643. }
  19644. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19645. };
  19646. var importGeometry = function (parsedGeometry, mesh) {
  19647. var scene = mesh.getScene();
  19648. // Geometry
  19649. var geometryId = parsedGeometry.geometryId;
  19650. if (geometryId) {
  19651. var geometry = scene.getGeometryByID(geometryId);
  19652. if (geometry) {
  19653. geometry.applyToMesh(mesh);
  19654. }
  19655. }
  19656. else if (parsedGeometry instanceof ArrayBuffer) {
  19657. var binaryInfo = mesh._binaryInfo;
  19658. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19659. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19660. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19661. }
  19662. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19663. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19664. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19665. }
  19666. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19667. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19668. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19669. }
  19670. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19671. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19672. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19673. }
  19674. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19675. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19676. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19677. }
  19678. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19679. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19680. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19681. }
  19682. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19683. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19684. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19685. }
  19686. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19687. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19688. mesh.setIndices(indicesData);
  19689. }
  19690. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19691. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19692. mesh.subMeshes = [];
  19693. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19694. var materialIndex = subMeshesData[(i * 5) + 0];
  19695. var verticesStart = subMeshesData[(i * 5) + 1];
  19696. var verticesCount = subMeshesData[(i * 5) + 2];
  19697. var indexStart = subMeshesData[(i * 5) + 3];
  19698. var indexCount = subMeshesData[(i * 5) + 4];
  19699. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19700. }
  19701. }
  19702. }
  19703. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19704. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19705. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19706. if (parsedGeometry.uvs) {
  19707. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19708. }
  19709. if (parsedGeometry.uvs2) {
  19710. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19711. }
  19712. if (parsedGeometry.colors) {
  19713. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19714. }
  19715. if (parsedGeometry.matricesIndices) {
  19716. if (!parsedGeometry.matricesIndices._isExpanded) {
  19717. var floatIndices = [];
  19718. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19719. var matricesIndex = parsedGeometry.matricesIndices[i];
  19720. floatIndices.push(matricesIndex & 0x000000FF);
  19721. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19722. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19723. floatIndices.push(matricesIndex >> 24);
  19724. }
  19725. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19726. }
  19727. else {
  19728. delete parsedGeometry.matricesIndices._isExpanded;
  19729. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19730. }
  19731. }
  19732. if (parsedGeometry.matricesWeights) {
  19733. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19734. }
  19735. mesh.setIndices(parsedGeometry.indices);
  19736. // SubMeshes
  19737. if (parsedGeometry.subMeshes) {
  19738. mesh.subMeshes = [];
  19739. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19740. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19741. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19742. }
  19743. }
  19744. }
  19745. // Flat shading
  19746. if (mesh._shouldGenerateFlatShading) {
  19747. mesh.convertToFlatShadedMesh();
  19748. delete mesh._shouldGenerateFlatShading;
  19749. }
  19750. // Update
  19751. mesh.computeWorldMatrix(true);
  19752. // Octree
  19753. if (scene._selectionOctree) {
  19754. scene._selectionOctree.addMesh(mesh);
  19755. }
  19756. };
  19757. BABYLON.SceneLoader.RegisterPlugin({
  19758. extensions: ".babylon",
  19759. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19760. var parsedData = JSON.parse(data);
  19761. var loadedSkeletonsIds = [];
  19762. var loadedMaterialsIds = [];
  19763. var hierarchyIds = [];
  19764. for (var index = 0; index < parsedData.meshes.length; index++) {
  19765. var parsedMesh = parsedData.meshes[index];
  19766. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19767. if (meshesNames instanceof Array) {
  19768. // Remove found mesh name from list.
  19769. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19770. }
  19771. // Material ?
  19772. if (parsedMesh.materialId) {
  19773. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19774. if (!materialFound) {
  19775. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19776. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19777. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19778. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19779. var subMatId = parsedMultiMaterial.materials[matIndex];
  19780. loadedMaterialsIds.push(subMatId);
  19781. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19782. }
  19783. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19784. parseMultiMaterial(parsedMultiMaterial, scene);
  19785. materialFound = true;
  19786. break;
  19787. }
  19788. }
  19789. }
  19790. if (!materialFound) {
  19791. loadedMaterialsIds.push(parsedMesh.materialId);
  19792. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19793. }
  19794. }
  19795. // Skeleton ?
  19796. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19797. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19798. if (!skeletonAlreadyLoaded) {
  19799. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19800. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19801. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19802. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19803. loadedSkeletonsIds.push(parsedSkeleton.id);
  19804. }
  19805. }
  19806. }
  19807. }
  19808. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19809. meshes.push(mesh);
  19810. }
  19811. }
  19812. for (index = 0; index < scene.meshes.length; index++) {
  19813. var currentMesh = scene.meshes[index];
  19814. if (currentMesh._waitingParentId) {
  19815. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19816. currentMesh._waitingParentId = undefined;
  19817. }
  19818. }
  19819. // Particles
  19820. if (parsedData.particleSystems) {
  19821. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19822. var parsedParticleSystem = parsedData.particleSystems[index];
  19823. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19824. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19825. }
  19826. }
  19827. }
  19828. return true;
  19829. },
  19830. load: function (scene, data, rootUrl) {
  19831. var parsedData = JSON.parse(data);
  19832. // Scene
  19833. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19834. scene.autoClear = parsedData.autoClear;
  19835. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19836. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19837. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19838. // Fog
  19839. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19840. scene.fogMode = parsedData.fogMode;
  19841. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19842. scene.fogStart = parsedData.fogStart;
  19843. scene.fogEnd = parsedData.fogEnd;
  19844. scene.fogDensity = parsedData.fogDensity;
  19845. }
  19846. for (var index = 0; index < parsedData.lights.length; index++) {
  19847. var parsedLight = parsedData.lights[index];
  19848. parseLight(parsedLight, scene);
  19849. }
  19850. // Materials
  19851. if (parsedData.materials) {
  19852. for (index = 0; index < parsedData.materials.length; index++) {
  19853. var parsedMaterial = parsedData.materials[index];
  19854. parseMaterial(parsedMaterial, scene, rootUrl);
  19855. }
  19856. }
  19857. if (parsedData.multiMaterials) {
  19858. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19859. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19860. parseMultiMaterial(parsedMultiMaterial, scene);
  19861. }
  19862. }
  19863. // Skeletons
  19864. if (parsedData.skeletons) {
  19865. for (index = 0; index < parsedData.skeletons.length; index++) {
  19866. var parsedSkeleton = parsedData.skeletons[index];
  19867. parseSkeleton(parsedSkeleton, scene);
  19868. }
  19869. }
  19870. // Geometries
  19871. var geometries = parsedData.geometries;
  19872. if (geometries) {
  19873. // Boxes
  19874. var boxes = geometries.boxes;
  19875. if (boxes) {
  19876. for (index = 0; index < boxes.length; index++) {
  19877. var parsedBox = boxes[index];
  19878. parseBox(parsedBox, scene);
  19879. }
  19880. }
  19881. // Spheres
  19882. var spheres = geometries.spheres;
  19883. if (spheres) {
  19884. for (index = 0; index < spheres.length; index++) {
  19885. var parsedSphere = spheres[index];
  19886. parseSphere(parsedSphere, scene);
  19887. }
  19888. }
  19889. // Cylinders
  19890. var cylinders = geometries.cylinders;
  19891. if (cylinders) {
  19892. for (index = 0; index < cylinders.length; index++) {
  19893. var parsedCylinder = cylinders[index];
  19894. parseCylinder(parsedCylinder, scene);
  19895. }
  19896. }
  19897. // Toruses
  19898. var toruses = geometries.toruses;
  19899. if (toruses) {
  19900. for (index = 0; index < toruses.length; index++) {
  19901. var parsedTorus = toruses[index];
  19902. parseTorus(parsedTorus, scene);
  19903. }
  19904. }
  19905. // Grounds
  19906. var grounds = geometries.grounds;
  19907. if (grounds) {
  19908. for (index = 0; index < grounds.length; index++) {
  19909. var parsedGround = grounds[index];
  19910. parseGround(parsedGround, scene);
  19911. }
  19912. }
  19913. // Planes
  19914. var planes = geometries.planes;
  19915. if (planes) {
  19916. for (index = 0; index < planes.length; index++) {
  19917. var parsedPlane = planes[index];
  19918. parsePlane(parsedPlane, scene);
  19919. }
  19920. }
  19921. // TorusKnots
  19922. var torusKnots = geometries.torusKnots;
  19923. if (torusKnots) {
  19924. for (index = 0; index < torusKnots.length; index++) {
  19925. var parsedTorusKnot = torusKnots[index];
  19926. parseTorusKnot(parsedTorusKnot, scene);
  19927. }
  19928. }
  19929. // VertexData
  19930. var vertexData = geometries.vertexData;
  19931. if (vertexData) {
  19932. for (index = 0; index < vertexData.length; index++) {
  19933. var parsedVertexData = vertexData[index];
  19934. parseVertexData(parsedVertexData, scene, rootUrl);
  19935. }
  19936. }
  19937. }
  19938. for (index = 0; index < parsedData.meshes.length; index++) {
  19939. var parsedMesh = parsedData.meshes[index];
  19940. parseMesh(parsedMesh, scene, rootUrl);
  19941. }
  19942. for (index = 0; index < parsedData.cameras.length; index++) {
  19943. var parsedCamera = parsedData.cameras[index];
  19944. parseCamera(parsedCamera, scene);
  19945. }
  19946. if (parsedData.activeCameraID) {
  19947. scene.setActiveCameraByID(parsedData.activeCameraID);
  19948. }
  19949. for (index = 0; index < scene.cameras.length; index++) {
  19950. var camera = scene.cameras[index];
  19951. if (camera._waitingParentId) {
  19952. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19953. camera._waitingParentId = undefined;
  19954. }
  19955. }
  19956. for (index = 0; index < scene.lights.length; index++) {
  19957. var light = scene.lights[index];
  19958. if (light._waitingParentId) {
  19959. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19960. light._waitingParentId = undefined;
  19961. }
  19962. }
  19963. // Sounds
  19964. if (parsedData.sounds) {
  19965. for (index = 0; index < parsedData.sounds.length; index++) {
  19966. var parsedSound = parsedData.sounds[index];
  19967. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19968. parseSound(parsedSound, scene, rootUrl);
  19969. }
  19970. else {
  19971. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19972. }
  19973. }
  19974. }
  19975. for (index = 0; index < scene.meshes.length; index++) {
  19976. var mesh = scene.meshes[index];
  19977. if (mesh._waitingParentId) {
  19978. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19979. mesh._waitingParentId = undefined;
  19980. }
  19981. if (mesh._waitingActions) {
  19982. parseActions(mesh._waitingActions, mesh, scene);
  19983. mesh._waitingActions = undefined;
  19984. }
  19985. }
  19986. // Particles Systems
  19987. if (parsedData.particleSystems) {
  19988. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19989. var parsedParticleSystem = parsedData.particleSystems[index];
  19990. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19991. }
  19992. }
  19993. // Lens flares
  19994. if (parsedData.lensFlareSystems) {
  19995. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19996. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19997. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19998. }
  19999. }
  20000. // Shadows
  20001. if (parsedData.shadowGenerators) {
  20002. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20003. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20004. parseShadowGenerator(parsedShadowGenerator, scene);
  20005. }
  20006. }
  20007. // Actions (scene)
  20008. if (parsedData.actions) {
  20009. parseActions(parsedData.actions, null, scene);
  20010. }
  20011. // Finish
  20012. return true;
  20013. }
  20014. });
  20015. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20016. })(BABYLON || (BABYLON = {}));
  20017. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20018. (function (BABYLON) {
  20019. // Unique ID when we import meshes from Babylon to CSG
  20020. var currentCSGMeshId = 0;
  20021. // # class Vertex
  20022. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20023. // one to provide additional features like texture coordinates and vertex
  20024. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20025. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20026. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20027. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20028. // is not used anywhere else.
  20029. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20030. var Vertex = (function () {
  20031. function Vertex(pos, normal, uv) {
  20032. this.pos = pos;
  20033. this.normal = normal;
  20034. this.uv = uv;
  20035. }
  20036. Vertex.prototype.clone = function () {
  20037. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20038. };
  20039. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20040. // orientation of a polygon is flipped.
  20041. Vertex.prototype.flip = function () {
  20042. this.normal = this.normal.scale(-1);
  20043. };
  20044. // Create a new vertex between this vertex and `other` by linearly
  20045. // interpolating all properties using a parameter of `t`. Subclasses should
  20046. // override this to interpolate additional properties.
  20047. Vertex.prototype.interpolate = function (other, t) {
  20048. 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));
  20049. };
  20050. return Vertex;
  20051. })();
  20052. // # class Plane
  20053. // Represents a plane in 3D space.
  20054. var Plane = (function () {
  20055. function Plane(normal, w) {
  20056. this.normal = normal;
  20057. this.w = w;
  20058. }
  20059. Plane.FromPoints = function (a, b, c) {
  20060. var v0 = c.subtract(a);
  20061. var v1 = b.subtract(a);
  20062. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20063. return null;
  20064. }
  20065. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20066. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20067. };
  20068. Plane.prototype.clone = function () {
  20069. return new Plane(this.normal.clone(), this.w);
  20070. };
  20071. Plane.prototype.flip = function () {
  20072. this.normal.scaleInPlace(-1);
  20073. this.w = -this.w;
  20074. };
  20075. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20076. // fragments in the appropriate lists. Coplanar polygons go into either
  20077. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20078. // respect to this plane. Polygons in front or in back of this plane go into
  20079. // either `front` or `back`.
  20080. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20081. var COPLANAR = 0;
  20082. var FRONT = 1;
  20083. var BACK = 2;
  20084. var SPANNING = 3;
  20085. // Classify each point as well as the entire polygon into one of the above
  20086. // four classes.
  20087. var polygonType = 0;
  20088. var types = [];
  20089. for (var i = 0; i < polygon.vertices.length; i++) {
  20090. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20091. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20092. polygonType |= type;
  20093. types.push(type);
  20094. }
  20095. switch (polygonType) {
  20096. case COPLANAR:
  20097. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20098. break;
  20099. case FRONT:
  20100. front.push(polygon);
  20101. break;
  20102. case BACK:
  20103. back.push(polygon);
  20104. break;
  20105. case SPANNING:
  20106. var f = [], b = [];
  20107. for (i = 0; i < polygon.vertices.length; i++) {
  20108. var j = (i + 1) % polygon.vertices.length;
  20109. var ti = types[i], tj = types[j];
  20110. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20111. if (ti != BACK)
  20112. f.push(vi);
  20113. if (ti != FRONT)
  20114. b.push(ti != BACK ? vi.clone() : vi);
  20115. if ((ti | tj) == SPANNING) {
  20116. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20117. var v = vi.interpolate(vj, t);
  20118. f.push(v);
  20119. b.push(v.clone());
  20120. }
  20121. }
  20122. if (f.length >= 3) {
  20123. var poly = new Polygon(f, polygon.shared);
  20124. if (poly.plane)
  20125. front.push(poly);
  20126. }
  20127. if (b.length >= 3) {
  20128. poly = new Polygon(b, polygon.shared);
  20129. if (poly.plane)
  20130. back.push(poly);
  20131. }
  20132. break;
  20133. }
  20134. };
  20135. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20136. // point is on the plane.
  20137. Plane.EPSILON = 1e-5;
  20138. return Plane;
  20139. })();
  20140. // # class Polygon
  20141. // Represents a convex polygon. The vertices used to initialize a polygon must
  20142. // be coplanar and form a convex loop.
  20143. //
  20144. // Each convex polygon has a `shared` property, which is shared between all
  20145. // polygons that are clones of each other or were split from the same polygon.
  20146. // This can be used to define per-polygon properties (such as surface color).
  20147. var Polygon = (function () {
  20148. function Polygon(vertices, shared) {
  20149. this.vertices = vertices;
  20150. this.shared = shared;
  20151. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20152. }
  20153. Polygon.prototype.clone = function () {
  20154. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20155. return new Polygon(vertices, this.shared);
  20156. };
  20157. Polygon.prototype.flip = function () {
  20158. this.vertices.reverse().map(function (v) {
  20159. v.flip();
  20160. });
  20161. this.plane.flip();
  20162. };
  20163. return Polygon;
  20164. })();
  20165. // # class Node
  20166. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20167. // by picking a polygon to split along. That polygon (and all other coplanar
  20168. // polygons) are added directly to that node and the other polygons are added to
  20169. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20170. // no distinction between internal and leaf nodes.
  20171. var Node = (function () {
  20172. function Node(polygons) {
  20173. this.plane = null;
  20174. this.front = null;
  20175. this.back = null;
  20176. this.polygons = [];
  20177. if (polygons) {
  20178. this.build(polygons);
  20179. }
  20180. }
  20181. Node.prototype.clone = function () {
  20182. var node = new Node();
  20183. node.plane = this.plane && this.plane.clone();
  20184. node.front = this.front && this.front.clone();
  20185. node.back = this.back && this.back.clone();
  20186. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20187. return node;
  20188. };
  20189. // Convert solid space to empty space and empty space to solid space.
  20190. Node.prototype.invert = function () {
  20191. for (var i = 0; i < this.polygons.length; i++) {
  20192. this.polygons[i].flip();
  20193. }
  20194. if (this.plane) {
  20195. this.plane.flip();
  20196. }
  20197. if (this.front) {
  20198. this.front.invert();
  20199. }
  20200. if (this.back) {
  20201. this.back.invert();
  20202. }
  20203. var temp = this.front;
  20204. this.front = this.back;
  20205. this.back = temp;
  20206. };
  20207. // Recursively remove all polygons in `polygons` that are inside this BSP
  20208. // tree.
  20209. Node.prototype.clipPolygons = function (polygons) {
  20210. if (!this.plane)
  20211. return polygons.slice();
  20212. var front = [], back = [];
  20213. for (var i = 0; i < polygons.length; i++) {
  20214. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20215. }
  20216. if (this.front) {
  20217. front = this.front.clipPolygons(front);
  20218. }
  20219. if (this.back) {
  20220. back = this.back.clipPolygons(back);
  20221. }
  20222. else {
  20223. back = [];
  20224. }
  20225. return front.concat(back);
  20226. };
  20227. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20228. // `bsp`.
  20229. Node.prototype.clipTo = function (bsp) {
  20230. this.polygons = bsp.clipPolygons(this.polygons);
  20231. if (this.front)
  20232. this.front.clipTo(bsp);
  20233. if (this.back)
  20234. this.back.clipTo(bsp);
  20235. };
  20236. // Return a list of all polygons in this BSP tree.
  20237. Node.prototype.allPolygons = function () {
  20238. var polygons = this.polygons.slice();
  20239. if (this.front)
  20240. polygons = polygons.concat(this.front.allPolygons());
  20241. if (this.back)
  20242. polygons = polygons.concat(this.back.allPolygons());
  20243. return polygons;
  20244. };
  20245. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20246. // new polygons are filtered down to the bottom of the tree and become new
  20247. // nodes there. Each set of polygons is partitioned using the first polygon
  20248. // (no heuristic is used to pick a good split).
  20249. Node.prototype.build = function (polygons) {
  20250. if (!polygons.length)
  20251. return;
  20252. if (!this.plane)
  20253. this.plane = polygons[0].plane.clone();
  20254. var front = [], back = [];
  20255. for (var i = 0; i < polygons.length; i++) {
  20256. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20257. }
  20258. if (front.length) {
  20259. if (!this.front)
  20260. this.front = new Node();
  20261. this.front.build(front);
  20262. }
  20263. if (back.length) {
  20264. if (!this.back)
  20265. this.back = new Node();
  20266. this.back.build(back);
  20267. }
  20268. };
  20269. return Node;
  20270. })();
  20271. var CSG = (function () {
  20272. function CSG() {
  20273. this.polygons = new Array();
  20274. }
  20275. // Convert BABYLON.Mesh to BABYLON.CSG
  20276. CSG.FromMesh = function (mesh) {
  20277. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20278. if (mesh instanceof BABYLON.Mesh) {
  20279. mesh.computeWorldMatrix(true);
  20280. var matrix = mesh.getWorldMatrix();
  20281. var meshPosition = mesh.position.clone();
  20282. var meshRotation = mesh.rotation.clone();
  20283. var meshScaling = mesh.scaling.clone();
  20284. }
  20285. else {
  20286. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20287. }
  20288. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20289. var subMeshes = mesh.subMeshes;
  20290. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20291. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20292. vertices = [];
  20293. for (var j = 0; j < 3; j++) {
  20294. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20295. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20296. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20297. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20298. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20299. vertex = new Vertex(position, normal, uv);
  20300. vertices.push(vertex);
  20301. }
  20302. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20303. // To handle the case of degenerated triangle
  20304. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20305. if (polygon.plane)
  20306. polygons.push(polygon);
  20307. }
  20308. }
  20309. var csg = CSG.FromPolygons(polygons);
  20310. csg.matrix = matrix;
  20311. csg.position = meshPosition;
  20312. csg.rotation = meshRotation;
  20313. csg.scaling = meshScaling;
  20314. currentCSGMeshId++;
  20315. return csg;
  20316. };
  20317. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20318. CSG.FromPolygons = function (polygons) {
  20319. var csg = new BABYLON.CSG();
  20320. csg.polygons = polygons;
  20321. return csg;
  20322. };
  20323. CSG.prototype.clone = function () {
  20324. var csg = new BABYLON.CSG();
  20325. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20326. csg.copyTransformAttributes(this);
  20327. return csg;
  20328. };
  20329. CSG.prototype.toPolygons = function () {
  20330. return this.polygons;
  20331. };
  20332. CSG.prototype.union = function (csg) {
  20333. var a = new Node(this.clone().polygons);
  20334. var b = new Node(csg.clone().polygons);
  20335. a.clipTo(b);
  20336. b.clipTo(a);
  20337. b.invert();
  20338. b.clipTo(a);
  20339. b.invert();
  20340. a.build(b.allPolygons());
  20341. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20342. };
  20343. CSG.prototype.unionInPlace = function (csg) {
  20344. var a = new Node(this.polygons);
  20345. var b = new Node(csg.polygons);
  20346. a.clipTo(b);
  20347. b.clipTo(a);
  20348. b.invert();
  20349. b.clipTo(a);
  20350. b.invert();
  20351. a.build(b.allPolygons());
  20352. this.polygons = a.allPolygons();
  20353. };
  20354. CSG.prototype.subtract = function (csg) {
  20355. var a = new Node(this.clone().polygons);
  20356. var b = new Node(csg.clone().polygons);
  20357. a.invert();
  20358. a.clipTo(b);
  20359. b.clipTo(a);
  20360. b.invert();
  20361. b.clipTo(a);
  20362. b.invert();
  20363. a.build(b.allPolygons());
  20364. a.invert();
  20365. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20366. };
  20367. CSG.prototype.subtractInPlace = function (csg) {
  20368. var a = new Node(this.polygons);
  20369. var b = new Node(csg.polygons);
  20370. a.invert();
  20371. a.clipTo(b);
  20372. b.clipTo(a);
  20373. b.invert();
  20374. b.clipTo(a);
  20375. b.invert();
  20376. a.build(b.allPolygons());
  20377. a.invert();
  20378. this.polygons = a.allPolygons();
  20379. };
  20380. CSG.prototype.intersect = function (csg) {
  20381. var a = new Node(this.clone().polygons);
  20382. var b = new Node(csg.clone().polygons);
  20383. a.invert();
  20384. b.clipTo(a);
  20385. b.invert();
  20386. a.clipTo(b);
  20387. b.clipTo(a);
  20388. a.build(b.allPolygons());
  20389. a.invert();
  20390. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20391. };
  20392. CSG.prototype.intersectInPlace = function (csg) {
  20393. var a = new Node(this.polygons);
  20394. var b = new Node(csg.polygons);
  20395. a.invert();
  20396. b.clipTo(a);
  20397. b.invert();
  20398. a.clipTo(b);
  20399. b.clipTo(a);
  20400. a.build(b.allPolygons());
  20401. a.invert();
  20402. this.polygons = a.allPolygons();
  20403. };
  20404. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20405. // not modified.
  20406. CSG.prototype.inverse = function () {
  20407. var csg = this.clone();
  20408. csg.inverseInPlace();
  20409. return csg;
  20410. };
  20411. CSG.prototype.inverseInPlace = function () {
  20412. this.polygons.map(function (p) {
  20413. p.flip();
  20414. });
  20415. };
  20416. // This is used to keep meshes transformations so they can be restored
  20417. // when we build back a Babylon Mesh
  20418. // NB : All CSG operations are performed in world coordinates
  20419. CSG.prototype.copyTransformAttributes = function (csg) {
  20420. this.matrix = csg.matrix;
  20421. this.position = csg.position;
  20422. this.rotation = csg.rotation;
  20423. this.scaling = csg.scaling;
  20424. return this;
  20425. };
  20426. // Build Raw mesh from CSG
  20427. // Coordinates here are in world space
  20428. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20429. var matrix = this.matrix.clone();
  20430. matrix.invert();
  20431. 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;
  20432. if (keepSubMeshes) {
  20433. // Sort Polygons, since subMeshes are indices range
  20434. polygons.sort(function (a, b) {
  20435. if (a.shared.meshId === b.shared.meshId) {
  20436. return a.shared.subMeshId - b.shared.subMeshId;
  20437. }
  20438. else {
  20439. return a.shared.meshId - b.shared.meshId;
  20440. }
  20441. });
  20442. }
  20443. for (var i = 0, il = polygons.length; i < il; i++) {
  20444. polygon = polygons[i];
  20445. // Building SubMeshes
  20446. if (!subMesh_dict[polygon.shared.meshId]) {
  20447. subMesh_dict[polygon.shared.meshId] = {};
  20448. }
  20449. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20450. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20451. indexStart: +Infinity,
  20452. indexEnd: -Infinity,
  20453. materialIndex: polygon.shared.materialIndex
  20454. };
  20455. }
  20456. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20457. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20458. polygonIndices[0] = 0;
  20459. polygonIndices[1] = j - 1;
  20460. polygonIndices[2] = j;
  20461. for (var k = 0; k < 3; k++) {
  20462. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20463. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20464. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20465. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20466. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20467. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20468. // Check if 2 points can be merged
  20469. 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)) {
  20470. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20471. uvs.push(uv.x, uv.y);
  20472. normals.push(normal.x, normal.y, normal.z);
  20473. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20474. }
  20475. indices.push(vertex_idx);
  20476. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20477. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20478. currentIndex++;
  20479. }
  20480. }
  20481. }
  20482. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20483. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20484. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20485. mesh.setIndices(indices);
  20486. if (keepSubMeshes) {
  20487. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20488. var materialIndexOffset = 0, materialMaxIndex;
  20489. mesh.subMeshes.length = 0;
  20490. for (var m in subMesh_dict) {
  20491. materialMaxIndex = -1;
  20492. for (var sm in subMesh_dict[m]) {
  20493. subMesh_obj = subMesh_dict[m][sm];
  20494. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20495. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20496. }
  20497. materialIndexOffset += ++materialMaxIndex;
  20498. }
  20499. }
  20500. return mesh;
  20501. };
  20502. // Build Mesh from CSG taking material and transforms into account
  20503. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20504. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20505. mesh.material = material;
  20506. mesh.position.copyFrom(this.position);
  20507. mesh.rotation.copyFrom(this.rotation);
  20508. mesh.scaling.copyFrom(this.scaling);
  20509. mesh.computeWorldMatrix(true);
  20510. return mesh;
  20511. };
  20512. return CSG;
  20513. })();
  20514. BABYLON.CSG = CSG;
  20515. })(BABYLON || (BABYLON = {}));
  20516. //# sourceMappingURL=babylon.csg.js.map
  20517. var BABYLON;
  20518. (function (BABYLON) {
  20519. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20520. __extends(OculusDistortionCorrectionPostProcess, _super);
  20521. //ANY
  20522. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20523. var _this = this;
  20524. _super.call(this, name, "oculusDistortionCorrection", [
  20525. 'LensCenter',
  20526. 'Scale',
  20527. 'ScaleIn',
  20528. 'HmdWarpParam'
  20529. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20530. this._isRightEye = isRightEye;
  20531. this._distortionFactors = cameraSettings.DistortionK;
  20532. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20533. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20534. this.onSizeChanged = function () {
  20535. _this.aspectRatio = _this.width * .5 / _this.height;
  20536. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20537. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20538. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20539. };
  20540. this.onApply = function (effect) {
  20541. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20542. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20543. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20544. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20545. };
  20546. }
  20547. return OculusDistortionCorrectionPostProcess;
  20548. })(BABYLON.PostProcess);
  20549. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20550. })(BABYLON || (BABYLON = {}));
  20551. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20552. // 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
  20553. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20554. var BABYLON;
  20555. (function (BABYLON) {
  20556. (function (JoystickAxis) {
  20557. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20558. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20559. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20560. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20561. var JoystickAxis = BABYLON.JoystickAxis;
  20562. var VirtualJoystick = (function () {
  20563. function VirtualJoystick(leftJoystick) {
  20564. var _this = this;
  20565. if (leftJoystick) {
  20566. this._leftJoystick = true;
  20567. }
  20568. else {
  20569. this._leftJoystick = false;
  20570. }
  20571. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20572. VirtualJoystick._globalJoystickIndex++;
  20573. // By default left & right arrow keys are moving the X
  20574. // and up & down keys are moving the Y
  20575. this._axisTargetedByLeftAndRight = 0 /* X */;
  20576. this._axisTargetedByUpAndDown = 1 /* Y */;
  20577. this.reverseLeftRight = false;
  20578. this.reverseUpDown = false;
  20579. // collections of pointers
  20580. this._touches = new BABYLON.VirtualJoystick.Collection();
  20581. this.deltaPosition = BABYLON.Vector3.Zero();
  20582. this._joystickSensibility = 25;
  20583. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20584. this._rotationSpeed = 25;
  20585. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20586. this._rotateOnAxisRelativeToMesh = false;
  20587. // injecting a canvas element on top of the canvas 3D game
  20588. if (!VirtualJoystick.vjCanvas) {
  20589. window.addEventListener("resize", function () {
  20590. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20591. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20592. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20593. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20594. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20595. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20596. }, false);
  20597. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20598. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20599. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20600. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20601. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20602. VirtualJoystick.vjCanvas.style.width = "100%";
  20603. VirtualJoystick.vjCanvas.style.height = "100%";
  20604. VirtualJoystick.vjCanvas.style.position = "absolute";
  20605. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20606. VirtualJoystick.vjCanvas.style.top = "0px";
  20607. VirtualJoystick.vjCanvas.style.left = "0px";
  20608. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20609. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20610. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20611. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20612. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20613. document.body.appendChild(VirtualJoystick.vjCanvas);
  20614. }
  20615. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20616. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20617. this.pressed = false;
  20618. // default joystick color
  20619. this._joystickColor = "cyan";
  20620. this._joystickPointerID = -1;
  20621. // current joystick position
  20622. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20623. // origin joystick position
  20624. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20625. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20626. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20627. _this._onPointerDown(evt);
  20628. }, false);
  20629. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20630. _this._onPointerMove(evt);
  20631. }, false);
  20632. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20633. _this._onPointerUp(evt);
  20634. }, false);
  20635. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20636. _this._onPointerUp(evt);
  20637. }, false);
  20638. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20639. evt.preventDefault(); // Disables system menu
  20640. }, false);
  20641. requestAnimationFrame(function () {
  20642. _this._drawVirtualJoystick();
  20643. });
  20644. }
  20645. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20646. this._joystickSensibility = newJoystickSensibility;
  20647. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20648. };
  20649. VirtualJoystick.prototype._onPointerDown = function (e) {
  20650. var positionOnScreenCondition;
  20651. e.preventDefault();
  20652. if (this._leftJoystick === true) {
  20653. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20654. }
  20655. else {
  20656. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20657. }
  20658. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20659. // First contact will be dedicated to the virtual joystick
  20660. this._joystickPointerID = e.pointerId;
  20661. this._joystickPointerStartPos.x = e.clientX;
  20662. this._joystickPointerStartPos.y = e.clientY;
  20663. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20664. this._deltaJoystickVector.x = 0;
  20665. this._deltaJoystickVector.y = 0;
  20666. this.pressed = true;
  20667. this._touches.add(e.pointerId.toString(), e);
  20668. }
  20669. else {
  20670. // You can only trigger the action buttons with a joystick declared
  20671. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20672. this._action();
  20673. this._touches.add(e.pointerId.toString(), e);
  20674. }
  20675. }
  20676. };
  20677. VirtualJoystick.prototype._onPointerMove = function (e) {
  20678. // If the current pointer is the one associated to the joystick (first touch contact)
  20679. if (this._joystickPointerID == e.pointerId) {
  20680. this._joystickPointerPos.x = e.clientX;
  20681. this._joystickPointerPos.y = e.clientY;
  20682. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20683. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20684. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20685. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20686. switch (this._axisTargetedByLeftAndRight) {
  20687. case 0 /* X */:
  20688. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20689. break;
  20690. case 1 /* Y */:
  20691. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20692. break;
  20693. case 2 /* Z */:
  20694. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20695. break;
  20696. }
  20697. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20698. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20699. switch (this._axisTargetedByUpAndDown) {
  20700. case 0 /* X */:
  20701. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20702. break;
  20703. case 1 /* Y */:
  20704. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20705. break;
  20706. case 2 /* Z */:
  20707. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20708. break;
  20709. }
  20710. }
  20711. else {
  20712. if (this._touches.item(e.pointerId.toString())) {
  20713. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20714. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20715. }
  20716. }
  20717. };
  20718. VirtualJoystick.prototype._onPointerUp = function (e) {
  20719. this._clearCanvas();
  20720. if (this._joystickPointerID == e.pointerId) {
  20721. this._joystickPointerID = -1;
  20722. this.pressed = false;
  20723. }
  20724. this._deltaJoystickVector.x = 0;
  20725. this._deltaJoystickVector.y = 0;
  20726. this._touches.remove(e.pointerId.toString());
  20727. };
  20728. /**
  20729. * Change the color of the virtual joystick
  20730. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20731. */
  20732. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20733. this._joystickColor = newColor;
  20734. };
  20735. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20736. this._action = action;
  20737. };
  20738. // Define which axis you'd like to control for left & right
  20739. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20740. switch (axis) {
  20741. case 0 /* X */:
  20742. case 1 /* Y */:
  20743. case 2 /* Z */:
  20744. this._axisTargetedByLeftAndRight = axis;
  20745. break;
  20746. default:
  20747. this._axisTargetedByLeftAndRight = 0 /* X */;
  20748. break;
  20749. }
  20750. };
  20751. // Define which axis you'd like to control for up & down
  20752. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20753. switch (axis) {
  20754. case 0 /* X */:
  20755. case 1 /* Y */:
  20756. case 2 /* Z */:
  20757. this._axisTargetedByUpAndDown = axis;
  20758. break;
  20759. default:
  20760. this._axisTargetedByUpAndDown = 1 /* Y */;
  20761. break;
  20762. }
  20763. };
  20764. VirtualJoystick.prototype._clearCanvas = function () {
  20765. if (this._leftJoystick) {
  20766. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20767. }
  20768. else {
  20769. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20770. }
  20771. };
  20772. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20773. var _this = this;
  20774. if (this.pressed) {
  20775. this._clearCanvas();
  20776. this._touches.forEach(function (touch) {
  20777. if (touch.pointerId === _this._joystickPointerID) {
  20778. VirtualJoystick.vjCanvasContext.beginPath();
  20779. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20780. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20781. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20782. VirtualJoystick.vjCanvasContext.stroke();
  20783. VirtualJoystick.vjCanvasContext.beginPath();
  20784. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20785. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20786. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20787. VirtualJoystick.vjCanvasContext.stroke();
  20788. VirtualJoystick.vjCanvasContext.beginPath();
  20789. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20790. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20791. VirtualJoystick.vjCanvasContext.stroke();
  20792. }
  20793. else {
  20794. VirtualJoystick.vjCanvasContext.beginPath();
  20795. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20796. VirtualJoystick.vjCanvasContext.beginPath();
  20797. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20798. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20799. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20800. VirtualJoystick.vjCanvasContext.stroke();
  20801. }
  20802. ;
  20803. });
  20804. }
  20805. requestAnimationFrame(function () {
  20806. _this._drawVirtualJoystick();
  20807. });
  20808. };
  20809. VirtualJoystick.prototype.releaseCanvas = function () {
  20810. if (VirtualJoystick.vjCanvas) {
  20811. document.body.removeChild(VirtualJoystick.vjCanvas);
  20812. VirtualJoystick.vjCanvas = null;
  20813. }
  20814. };
  20815. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20816. VirtualJoystick._globalJoystickIndex = 0;
  20817. return VirtualJoystick;
  20818. })();
  20819. BABYLON.VirtualJoystick = VirtualJoystick;
  20820. })(BABYLON || (BABYLON = {}));
  20821. var BABYLON;
  20822. (function (BABYLON) {
  20823. var VirtualJoystick;
  20824. (function (VirtualJoystick) {
  20825. var Collection = (function () {
  20826. function Collection() {
  20827. this._count = 0;
  20828. this._collection = new Array();
  20829. }
  20830. Collection.prototype.Count = function () {
  20831. return this._count;
  20832. };
  20833. Collection.prototype.add = function (key, item) {
  20834. if (this._collection[key] != undefined) {
  20835. return undefined;
  20836. }
  20837. this._collection[key] = item;
  20838. return ++this._count;
  20839. };
  20840. Collection.prototype.remove = function (key) {
  20841. if (this._collection[key] == undefined) {
  20842. return undefined;
  20843. }
  20844. delete this._collection[key];
  20845. return --this._count;
  20846. };
  20847. Collection.prototype.item = function (key) {
  20848. return this._collection[key];
  20849. };
  20850. Collection.prototype.forEach = function (block) {
  20851. var key;
  20852. for (key in this._collection) {
  20853. if (this._collection.hasOwnProperty(key)) {
  20854. block(this._collection[key]);
  20855. }
  20856. }
  20857. };
  20858. return Collection;
  20859. })();
  20860. VirtualJoystick.Collection = Collection;
  20861. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20862. })(BABYLON || (BABYLON = {}));
  20863. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20864. var BABYLON;
  20865. (function (BABYLON) {
  20866. var OculusRiftDevKit2013_Metric = {
  20867. HResolution: 1280,
  20868. VResolution: 800,
  20869. HScreenSize: 0.149759993,
  20870. VScreenSize: 0.0935999975,
  20871. VScreenCenter: 0.0467999987,
  20872. EyeToScreenDistance: 0.0410000011,
  20873. LensSeparationDistance: 0.0635000020,
  20874. InterpupillaryDistance: 0.0640000030,
  20875. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20876. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20877. PostProcessScaleFactor: 1.714605507808412,
  20878. LensCenterOffset: 0.151976421
  20879. };
  20880. var _OculusInnerCamera = (function (_super) {
  20881. __extends(_OculusInnerCamera, _super);
  20882. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20883. _super.call(this, name, position, scene);
  20884. this._workMatrix = new BABYLON.Matrix();
  20885. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20886. // Constants
  20887. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20888. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20889. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20890. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20891. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20892. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20893. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20894. // Postprocess
  20895. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20896. }
  20897. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20898. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20899. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20900. return this._projectionMatrix;
  20901. };
  20902. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20903. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20904. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20905. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20906. // Computing target and final matrix
  20907. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20908. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20909. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20910. return this._viewMatrix;
  20911. };
  20912. return _OculusInnerCamera;
  20913. })(BABYLON.FreeCamera);
  20914. var OculusCamera = (function (_super) {
  20915. __extends(OculusCamera, _super);
  20916. function OculusCamera(name, position, scene) {
  20917. _super.call(this, name, position, scene);
  20918. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20919. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20920. this.subCameras.push(this._leftCamera);
  20921. this.subCameras.push(this._rightCamera);
  20922. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20923. }
  20924. OculusCamera.prototype._update = function () {
  20925. this._leftCamera.position.copyFrom(this.position);
  20926. this._rightCamera.position.copyFrom(this.position);
  20927. this._updateCamera(this._leftCamera);
  20928. this._updateCamera(this._rightCamera);
  20929. _super.prototype._update.call(this);
  20930. };
  20931. OculusCamera.prototype._updateCamera = function (camera) {
  20932. camera.minZ = this.minZ;
  20933. camera.maxZ = this.maxZ;
  20934. camera.rotation.x = this.rotation.x;
  20935. camera.rotation.y = this.rotation.y;
  20936. camera.rotation.z = this.rotation.z;
  20937. };
  20938. // Oculus events
  20939. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20940. var yaw = evt.alpha / 180 * Math.PI;
  20941. var pitch = evt.beta / 180 * Math.PI;
  20942. var roll = evt.gamma / 180 * Math.PI;
  20943. if (!this._offsetOrientation) {
  20944. this._offsetOrientation = {
  20945. yaw: yaw,
  20946. pitch: pitch,
  20947. roll: roll
  20948. };
  20949. return;
  20950. }
  20951. else {
  20952. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20953. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20954. this.rotation.z += this._offsetOrientation.roll - roll;
  20955. this._offsetOrientation.yaw = yaw;
  20956. this._offsetOrientation.pitch = pitch;
  20957. this._offsetOrientation.roll = roll;
  20958. }
  20959. };
  20960. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20961. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20962. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20963. };
  20964. OculusCamera.prototype.detachControl = function (element) {
  20965. _super.prototype.detachControl.call(this, element);
  20966. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20967. };
  20968. return OculusCamera;
  20969. })(BABYLON.FreeCamera);
  20970. BABYLON.OculusCamera = OculusCamera;
  20971. })(BABYLON || (BABYLON = {}));
  20972. //# sourceMappingURL=babylon.oculusCamera.js.map
  20973. var BABYLON;
  20974. (function (BABYLON) {
  20975. var OculusRiftDevKit2013_Metric = {
  20976. HResolution: 1280,
  20977. VResolution: 800,
  20978. HScreenSize: 0.149759993,
  20979. VScreenSize: 0.0935999975,
  20980. VScreenCenter: 0.0467999987,
  20981. EyeToScreenDistance: 0.0410000011,
  20982. LensSeparationDistance: 0.0635000020,
  20983. InterpupillaryDistance: 0.0640000030,
  20984. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20985. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20986. PostProcessScaleFactor: 1.714605507808412,
  20987. LensCenterOffset: 0.151976421
  20988. };
  20989. var _OculusInnerGamepadCamera = (function (_super) {
  20990. __extends(_OculusInnerGamepadCamera, _super);
  20991. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20992. _super.call(this, name, position, scene);
  20993. this._workMatrix = new BABYLON.Matrix();
  20994. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20995. // Constants
  20996. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20997. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20998. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20999. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21000. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21001. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21002. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21003. // Postprocess
  21004. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21005. }
  21006. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21007. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21008. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21009. return this._projectionMatrix;
  21010. };
  21011. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21012. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21013. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21014. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21015. // Computing target and final matrix
  21016. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21017. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21018. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21019. return this._viewMatrix;
  21020. };
  21021. return _OculusInnerGamepadCamera;
  21022. })(BABYLON.FreeCamera);
  21023. var OculusGamepadCamera = (function (_super) {
  21024. __extends(OculusGamepadCamera, _super);
  21025. function OculusGamepadCamera(name, position, scene) {
  21026. var _this = this;
  21027. _super.call(this, name, position, scene);
  21028. this.angularSensibility = 200;
  21029. this.moveSensibility = 75;
  21030. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21031. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21032. this.subCameras.push(this._leftCamera);
  21033. this.subCameras.push(this._rightCamera);
  21034. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21035. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21036. _this._onNewGameConnected(gamepad);
  21037. });
  21038. }
  21039. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21040. // Only the first gamepad can control the camera
  21041. if (gamepad.index === 0) {
  21042. this._gamepad = gamepad;
  21043. }
  21044. };
  21045. OculusGamepadCamera.prototype._update = function () {
  21046. this._leftCamera.position.copyFrom(this.position);
  21047. this._rightCamera.position.copyFrom(this.position);
  21048. this._updateCamera(this._leftCamera);
  21049. this._updateCamera(this._rightCamera);
  21050. _super.prototype._update.call(this);
  21051. };
  21052. OculusGamepadCamera.prototype._checkInputs = function () {
  21053. if (!this._gamepad) {
  21054. return;
  21055. }
  21056. var LSValues = this._gamepad.leftStick;
  21057. var normalizedLX = LSValues.x / this.moveSensibility;
  21058. var normalizedLY = LSValues.y / this.moveSensibility;
  21059. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21060. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21061. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21062. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21063. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21064. };
  21065. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21066. camera.minZ = this.minZ;
  21067. camera.maxZ = this.maxZ;
  21068. camera.rotation.x = this.rotation.x;
  21069. camera.rotation.y = this.rotation.y;
  21070. camera.rotation.z = this.rotation.z;
  21071. };
  21072. // Oculus events
  21073. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21074. var yaw = evt.alpha / 180 * Math.PI;
  21075. var pitch = evt.beta / 180 * Math.PI;
  21076. var roll = evt.gamma / 180 * Math.PI;
  21077. if (!this._offsetOrientation) {
  21078. this._offsetOrientation = {
  21079. yaw: yaw,
  21080. pitch: pitch,
  21081. roll: roll
  21082. };
  21083. return;
  21084. }
  21085. else {
  21086. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21087. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21088. this.rotation.z += this._offsetOrientation.roll - roll;
  21089. this._offsetOrientation.yaw = yaw;
  21090. this._offsetOrientation.pitch = pitch;
  21091. this._offsetOrientation.roll = roll;
  21092. }
  21093. };
  21094. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21095. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21096. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21097. };
  21098. OculusGamepadCamera.prototype.detachControl = function (element) {
  21099. _super.prototype.detachControl.call(this, element);
  21100. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21101. };
  21102. OculusGamepadCamera.prototype.dispose = function () {
  21103. this._gamepads.dispose();
  21104. _super.prototype.dispose.call(this);
  21105. };
  21106. return OculusGamepadCamera;
  21107. })(BABYLON.FreeCamera);
  21108. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21109. })(BABYLON || (BABYLON = {}));
  21110. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21111. var BABYLON;
  21112. (function (BABYLON) {
  21113. // We're mainly based on the logic defined into the FreeCamera code
  21114. var VirtualJoysticksCamera = (function (_super) {
  21115. __extends(VirtualJoysticksCamera, _super);
  21116. function VirtualJoysticksCamera(name, position, scene) {
  21117. _super.call(this, name, position, scene);
  21118. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21119. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21120. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21121. this._leftjoystick.setJoystickSensibility(0.15);
  21122. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21123. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21124. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21125. this._rightjoystick.reverseUpDown = true;
  21126. this._rightjoystick.setJoystickSensibility(0.05);
  21127. this._rightjoystick.setJoystickColor("yellow");
  21128. }
  21129. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21130. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21131. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21132. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21133. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21134. if (!this._leftjoystick.pressed) {
  21135. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21136. }
  21137. if (!this._rightjoystick.pressed) {
  21138. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21139. }
  21140. };
  21141. VirtualJoysticksCamera.prototype.dispose = function () {
  21142. this._leftjoystick.releaseCanvas();
  21143. _super.prototype.dispose.call(this);
  21144. };
  21145. return VirtualJoysticksCamera;
  21146. })(BABYLON.FreeCamera);
  21147. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21148. })(BABYLON || (BABYLON = {}));
  21149. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21150. var BABYLON;
  21151. (function (BABYLON) {
  21152. var ShaderMaterial = (function (_super) {
  21153. __extends(ShaderMaterial, _super);
  21154. function ShaderMaterial(name, scene, shaderPath, options) {
  21155. _super.call(this, name, scene);
  21156. this._textures = new Array();
  21157. this._floats = new Array();
  21158. this._floatsArrays = {};
  21159. this._colors3 = new Array();
  21160. this._colors4 = new Array();
  21161. this._vectors2 = new Array();
  21162. this._vectors3 = new Array();
  21163. this._matrices = new Array();
  21164. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21165. this._shaderPath = shaderPath;
  21166. options.needAlphaBlending = options.needAlphaBlending || false;
  21167. options.needAlphaTesting = options.needAlphaTesting || false;
  21168. options.attributes = options.attributes || ["position", "normal", "uv"];
  21169. options.uniforms = options.uniforms || ["worldViewProjection"];
  21170. options.samplers = options.samplers || [];
  21171. this._options = options;
  21172. }
  21173. ShaderMaterial.prototype.needAlphaBlending = function () {
  21174. return this._options.needAlphaBlending;
  21175. };
  21176. ShaderMaterial.prototype.needAlphaTesting = function () {
  21177. return this._options.needAlphaTesting;
  21178. };
  21179. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21180. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21181. this._options.uniforms.push(uniformName);
  21182. }
  21183. };
  21184. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21185. if (this._options.samplers.indexOf(name) === -1) {
  21186. this._options.samplers.push(name);
  21187. }
  21188. this._textures[name] = texture;
  21189. return this;
  21190. };
  21191. ShaderMaterial.prototype.setFloat = function (name, value) {
  21192. this._checkUniform(name);
  21193. this._floats[name] = value;
  21194. return this;
  21195. };
  21196. ShaderMaterial.prototype.setFloats = function (name, value) {
  21197. this._checkUniform(name);
  21198. this._floatsArrays[name] = value;
  21199. return this;
  21200. };
  21201. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21202. this._checkUniform(name);
  21203. this._colors3[name] = value;
  21204. return this;
  21205. };
  21206. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21207. this._checkUniform(name);
  21208. this._colors4[name] = value;
  21209. return this;
  21210. };
  21211. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21212. this._checkUniform(name);
  21213. this._vectors2[name] = value;
  21214. return this;
  21215. };
  21216. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21217. this._checkUniform(name);
  21218. this._vectors3[name] = value;
  21219. return this;
  21220. };
  21221. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21222. this._checkUniform(name);
  21223. this._matrices[name] = value;
  21224. return this;
  21225. };
  21226. ShaderMaterial.prototype.isReady = function () {
  21227. var scene = this.getScene();
  21228. var engine = scene.getEngine();
  21229. if (!this.checkReadyOnEveryCall) {
  21230. if (this._renderId === scene.getRenderId()) {
  21231. return true;
  21232. }
  21233. }
  21234. var previousEffect = this._effect;
  21235. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21236. if (!this._effect.isReady()) {
  21237. return false;
  21238. }
  21239. if (previousEffect !== this._effect) {
  21240. scene.resetCachedMaterial();
  21241. }
  21242. this._renderId = scene.getRenderId();
  21243. return true;
  21244. };
  21245. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21246. var scene = this.getScene();
  21247. if (this._options.uniforms.indexOf("world") !== -1) {
  21248. this._effect.setMatrix("world", world);
  21249. }
  21250. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21251. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21252. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21253. }
  21254. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21255. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21256. }
  21257. };
  21258. ShaderMaterial.prototype.bind = function (world) {
  21259. // Std values
  21260. this.bindOnlyWorldMatrix(world);
  21261. if (this.getScene().getCachedMaterial() !== this) {
  21262. if (this._options.uniforms.indexOf("view") !== -1) {
  21263. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21264. }
  21265. if (this._options.uniforms.indexOf("projection") !== -1) {
  21266. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21267. }
  21268. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21269. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21270. }
  21271. for (var name in this._textures) {
  21272. this._effect.setTexture(name, this._textures[name]);
  21273. }
  21274. for (name in this._floats) {
  21275. this._effect.setFloat(name, this._floats[name]);
  21276. }
  21277. for (name in this._floatsArrays) {
  21278. this._effect.setArray(name, this._floatsArrays[name]);
  21279. }
  21280. for (name in this._colors3) {
  21281. this._effect.setColor3(name, this._colors3[name]);
  21282. }
  21283. for (name in this._colors4) {
  21284. var color = this._colors4[name];
  21285. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21286. }
  21287. for (name in this._vectors2) {
  21288. this._effect.setVector2(name, this._vectors2[name]);
  21289. }
  21290. for (name in this._vectors3) {
  21291. this._effect.setVector3(name, this._vectors3[name]);
  21292. }
  21293. for (name in this._matrices) {
  21294. this._effect.setMatrix(name, this._matrices[name]);
  21295. }
  21296. }
  21297. _super.prototype.bind.call(this, world, null);
  21298. };
  21299. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21300. for (var name in this._textures) {
  21301. this._textures[name].dispose();
  21302. }
  21303. this._textures = [];
  21304. _super.prototype.dispose.call(this, forceDisposeEffect);
  21305. };
  21306. return ShaderMaterial;
  21307. })(BABYLON.Material);
  21308. BABYLON.ShaderMaterial = ShaderMaterial;
  21309. })(BABYLON || (BABYLON = {}));
  21310. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21311. (function (BABYLON) {
  21312. var VertexData = (function () {
  21313. function VertexData() {
  21314. }
  21315. VertexData.prototype.set = function (data, kind) {
  21316. switch (kind) {
  21317. case BABYLON.VertexBuffer.PositionKind:
  21318. this.positions = data;
  21319. break;
  21320. case BABYLON.VertexBuffer.NormalKind:
  21321. this.normals = data;
  21322. break;
  21323. case BABYLON.VertexBuffer.UVKind:
  21324. this.uvs = data;
  21325. break;
  21326. case BABYLON.VertexBuffer.UV2Kind:
  21327. this.uv2s = data;
  21328. break;
  21329. case BABYLON.VertexBuffer.ColorKind:
  21330. this.colors = data;
  21331. break;
  21332. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21333. this.matricesIndices = data;
  21334. break;
  21335. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21336. this.matricesWeights = data;
  21337. break;
  21338. }
  21339. };
  21340. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21341. this._applyTo(mesh, updatable);
  21342. };
  21343. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21344. this._applyTo(geometry, updatable);
  21345. };
  21346. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21347. this._update(mesh);
  21348. };
  21349. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21350. this._update(geometry);
  21351. };
  21352. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21353. if (this.positions) {
  21354. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21355. }
  21356. if (this.normals) {
  21357. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21358. }
  21359. if (this.uvs) {
  21360. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21361. }
  21362. if (this.uv2s) {
  21363. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21364. }
  21365. if (this.colors) {
  21366. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21367. }
  21368. if (this.matricesIndices) {
  21369. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21370. }
  21371. if (this.matricesWeights) {
  21372. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21373. }
  21374. if (this.indices) {
  21375. meshOrGeometry.setIndices(this.indices);
  21376. }
  21377. };
  21378. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21379. if (this.positions) {
  21380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21381. }
  21382. if (this.normals) {
  21383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21384. }
  21385. if (this.uvs) {
  21386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21387. }
  21388. if (this.uv2s) {
  21389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21390. }
  21391. if (this.colors) {
  21392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21393. }
  21394. if (this.matricesIndices) {
  21395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21396. }
  21397. if (this.matricesWeights) {
  21398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21399. }
  21400. if (this.indices) {
  21401. meshOrGeometry.setIndices(this.indices);
  21402. }
  21403. };
  21404. VertexData.prototype.transform = function (matrix) {
  21405. var transformed = BABYLON.Vector3.Zero();
  21406. if (this.positions) {
  21407. var position = BABYLON.Vector3.Zero();
  21408. for (var index = 0; index < this.positions.length; index += 3) {
  21409. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21410. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21411. this.positions[index] = transformed.x;
  21412. this.positions[index + 1] = transformed.y;
  21413. this.positions[index + 2] = transformed.z;
  21414. }
  21415. }
  21416. if (this.normals) {
  21417. var normal = BABYLON.Vector3.Zero();
  21418. for (index = 0; index < this.normals.length; index += 3) {
  21419. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21420. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21421. this.normals[index] = transformed.x;
  21422. this.normals[index + 1] = transformed.y;
  21423. this.normals[index + 2] = transformed.z;
  21424. }
  21425. }
  21426. };
  21427. VertexData.prototype.merge = function (other) {
  21428. if (other.indices) {
  21429. if (!this.indices) {
  21430. this.indices = [];
  21431. }
  21432. var offset = this.positions ? this.positions.length / 3 : 0;
  21433. for (var index = 0; index < other.indices.length; index++) {
  21434. this.indices.push(other.indices[index] + offset);
  21435. }
  21436. }
  21437. if (other.positions) {
  21438. if (!this.positions) {
  21439. this.positions = [];
  21440. }
  21441. for (index = 0; index < other.positions.length; index++) {
  21442. this.positions.push(other.positions[index]);
  21443. }
  21444. }
  21445. if (other.normals) {
  21446. if (!this.normals) {
  21447. this.normals = [];
  21448. }
  21449. for (index = 0; index < other.normals.length; index++) {
  21450. this.normals.push(other.normals[index]);
  21451. }
  21452. }
  21453. if (other.uvs) {
  21454. if (!this.uvs) {
  21455. this.uvs = [];
  21456. }
  21457. for (index = 0; index < other.uvs.length; index++) {
  21458. this.uvs.push(other.uvs[index]);
  21459. }
  21460. }
  21461. if (other.uv2s) {
  21462. if (!this.uv2s) {
  21463. this.uv2s = [];
  21464. }
  21465. for (index = 0; index < other.uv2s.length; index++) {
  21466. this.uv2s.push(other.uv2s[index]);
  21467. }
  21468. }
  21469. if (other.matricesIndices) {
  21470. if (!this.matricesIndices) {
  21471. this.matricesIndices = [];
  21472. }
  21473. for (index = 0; index < other.matricesIndices.length; index++) {
  21474. this.matricesIndices.push(other.matricesIndices[index]);
  21475. }
  21476. }
  21477. if (other.matricesWeights) {
  21478. if (!this.matricesWeights) {
  21479. this.matricesWeights = [];
  21480. }
  21481. for (index = 0; index < other.matricesWeights.length; index++) {
  21482. this.matricesWeights.push(other.matricesWeights[index]);
  21483. }
  21484. }
  21485. if (other.colors) {
  21486. if (!this.colors) {
  21487. this.colors = [];
  21488. }
  21489. for (index = 0; index < other.colors.length; index++) {
  21490. this.colors.push(other.colors[index]);
  21491. }
  21492. }
  21493. };
  21494. // Statics
  21495. VertexData.ExtractFromMesh = function (mesh) {
  21496. return VertexData._ExtractFrom(mesh);
  21497. };
  21498. VertexData.ExtractFromGeometry = function (geometry) {
  21499. return VertexData._ExtractFrom(geometry);
  21500. };
  21501. VertexData._ExtractFrom = function (meshOrGeometry) {
  21502. var result = new VertexData();
  21503. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21504. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21505. }
  21506. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21507. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21508. }
  21509. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21510. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21511. }
  21512. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21513. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21514. }
  21515. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21516. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21517. }
  21518. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21519. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21520. }
  21521. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21522. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21523. }
  21524. result.indices = meshOrGeometry.getIndices();
  21525. return result;
  21526. };
  21527. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21528. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21529. closeArray = closeArray || false;
  21530. closePath = closePath || false;
  21531. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21532. offset = offset || defaultOffset;
  21533. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21534. var positions = [];
  21535. var indices = [];
  21536. var normals = [];
  21537. var uvs = [];
  21538. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21539. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21540. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21541. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21542. var minlg; // minimal length among all paths from pathArray
  21543. var lg = []; // array of path lengths : nb of vertex per path
  21544. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21545. var p; // path iterator
  21546. var i; // point iterator
  21547. var j; // point iterator
  21548. // if single path in pathArray
  21549. if (pathArray.length < 2) {
  21550. var ar1 = [];
  21551. var ar2 = [];
  21552. for (i = 0; i < pathArray[0].length - offset; i++) {
  21553. ar1.push(pathArray[0][i]);
  21554. ar2.push(pathArray[0][i + offset]);
  21555. }
  21556. pathArray = [ar1, ar2];
  21557. }
  21558. // positions and horizontal distances (u)
  21559. var idc = 0;
  21560. minlg = pathArray[0].length;
  21561. for (p = 0; p < pathArray.length; p++) {
  21562. uTotalDistance[p] = 0;
  21563. us[p] = [0];
  21564. var path = pathArray[p];
  21565. var l = path.length;
  21566. minlg = (minlg < l) ? minlg : l;
  21567. lg[p] = l;
  21568. idx[p] = idc;
  21569. j = 0;
  21570. while (j < l) {
  21571. positions.push(path[j].x, path[j].y, path[j].z);
  21572. if (j > 0) {
  21573. var vectlg = path[j].subtract(path[j - 1]).length();
  21574. var dist = vectlg + uTotalDistance[p];
  21575. us[p].push(dist);
  21576. uTotalDistance[p] = dist;
  21577. }
  21578. j++;
  21579. }
  21580. if (closePath) {
  21581. vectlg = path[0].subtract(path[j - 1]).length();
  21582. dist = vectlg + uTotalDistance[p];
  21583. uTotalDistance[p] = dist;
  21584. }
  21585. idc += l;
  21586. }
  21587. for (i = 0; i < minlg; i++) {
  21588. vTotalDistance[i] = 0;
  21589. vs[i] = [0];
  21590. var path1;
  21591. var path2;
  21592. for (p = 0; p < pathArray.length - 1; p++) {
  21593. path1 = pathArray[p];
  21594. path2 = pathArray[p + 1];
  21595. vectlg = path2[i].subtract(path1[i]).length();
  21596. dist = vectlg + vTotalDistance[i];
  21597. vs[i].push(dist);
  21598. vTotalDistance[i] = dist;
  21599. }
  21600. if (closeArray) {
  21601. path1 = pathArray[p];
  21602. path2 = pathArray[0];
  21603. vectlg = path2[i].subtract(path1[i]).length();
  21604. dist = vectlg + vTotalDistance[i];
  21605. vTotalDistance[i] = dist;
  21606. }
  21607. }
  21608. // uvs
  21609. var u;
  21610. var v;
  21611. for (p = 0; p < pathArray.length; p++) {
  21612. for (i = 0; i < minlg; i++) {
  21613. u = us[p][i] / uTotalDistance[p];
  21614. v = vs[i][p] / vTotalDistance[i];
  21615. uvs.push(u, v);
  21616. }
  21617. }
  21618. // indices
  21619. p = 0; // path index
  21620. var pi = 0; // positions array index
  21621. var l1 = lg[p] - 1; // path1 length
  21622. var l2 = lg[p + 1] - 1; // path2 length
  21623. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21624. var shft = idx[1] - idx[0]; // shift
  21625. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21626. var t1; // two consecutive triangles, so 4 points : point1
  21627. var t2; // point2
  21628. var t3; // point3
  21629. var t4; // point4
  21630. while (pi <= min && p < path1nb) {
  21631. // draw two triangles between path1 (p1) and path2 (p2) : (p1.pi, p2.pi, p1.pi+1) and (p2.pi+1, p1.pi+1, p2.pi) clockwise
  21632. t1 = pi;
  21633. t2 = pi + shft;
  21634. t3 = pi + 1;
  21635. t4 = pi + shft + 1;
  21636. indices.push(pi, pi + shft, pi + 1);
  21637. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21638. pi += 1;
  21639. if (pi === min) {
  21640. if (closePath) {
  21641. indices.push(pi, pi + shft, idx[p]);
  21642. indices.push(idx[p] + shft, idx[p], pi + shft);
  21643. t3 = idx[p];
  21644. t4 = idx[p] + shft;
  21645. }
  21646. p++;
  21647. if (p === lg.length - 1) {
  21648. shft = idx[0] - idx[p];
  21649. l1 = lg[p] - 1;
  21650. l2 = lg[0] - 1;
  21651. }
  21652. else {
  21653. shft = idx[p + 1] - idx[p];
  21654. l1 = lg[p] - 1;
  21655. l2 = lg[p + 1] - 1;
  21656. }
  21657. pi = idx[p];
  21658. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21659. }
  21660. }
  21661. // normals
  21662. VertexData.ComputeNormals(positions, indices, normals);
  21663. // sides
  21664. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21665. // Result
  21666. var vertexData = new VertexData();
  21667. vertexData.indices = indices;
  21668. vertexData.positions = positions;
  21669. vertexData.normals = normals;
  21670. vertexData.uvs = uvs;
  21671. return vertexData;
  21672. };
  21673. VertexData.CreateBox = function (size, sideOrientation) {
  21674. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21675. var normalsSource = [
  21676. new BABYLON.Vector3(0, 0, 1),
  21677. new BABYLON.Vector3(0, 0, -1),
  21678. new BABYLON.Vector3(1, 0, 0),
  21679. new BABYLON.Vector3(-1, 0, 0),
  21680. new BABYLON.Vector3(0, 1, 0),
  21681. new BABYLON.Vector3(0, -1, 0)
  21682. ];
  21683. var indices = [];
  21684. var positions = [];
  21685. var normals = [];
  21686. var uvs = [];
  21687. size = size || 1;
  21688. for (var index = 0; index < normalsSource.length; index++) {
  21689. var normal = normalsSource[index];
  21690. // Get two vectors perpendicular to the face normal and to each other.
  21691. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21692. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21693. // Six indices (two triangles) per face.
  21694. var verticesLength = positions.length / 3;
  21695. indices.push(verticesLength);
  21696. indices.push(verticesLength + 1);
  21697. indices.push(verticesLength + 2);
  21698. indices.push(verticesLength);
  21699. indices.push(verticesLength + 2);
  21700. indices.push(verticesLength + 3);
  21701. // Four vertices per face.
  21702. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21703. positions.push(vertex.x, vertex.y, vertex.z);
  21704. normals.push(normal.x, normal.y, normal.z);
  21705. uvs.push(1.0, 1.0);
  21706. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21707. positions.push(vertex.x, vertex.y, vertex.z);
  21708. normals.push(normal.x, normal.y, normal.z);
  21709. uvs.push(0.0, 1.0);
  21710. vertex = normal.add(side1).add(side2).scale(size / 2);
  21711. positions.push(vertex.x, vertex.y, vertex.z);
  21712. normals.push(normal.x, normal.y, normal.z);
  21713. uvs.push(0.0, 0.0);
  21714. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21715. positions.push(vertex.x, vertex.y, vertex.z);
  21716. normals.push(normal.x, normal.y, normal.z);
  21717. uvs.push(1.0, 0.0);
  21718. }
  21719. // sides
  21720. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21721. // Result
  21722. var vertexData = new VertexData();
  21723. vertexData.indices = indices;
  21724. vertexData.positions = positions;
  21725. vertexData.normals = normals;
  21726. vertexData.uvs = uvs;
  21727. return vertexData;
  21728. };
  21729. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21730. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21731. segments = segments || 32;
  21732. diameter = diameter || 1;
  21733. var radius = diameter / 2;
  21734. var totalZRotationSteps = 2 + segments;
  21735. var totalYRotationSteps = 2 * totalZRotationSteps;
  21736. var indices = [];
  21737. var positions = [];
  21738. var normals = [];
  21739. var uvs = [];
  21740. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21741. var normalizedZ = zRotationStep / totalZRotationSteps;
  21742. var angleZ = (normalizedZ * Math.PI);
  21743. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21744. var normalizedY = yRotationStep / totalYRotationSteps;
  21745. var angleY = normalizedY * Math.PI * 2;
  21746. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21747. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21748. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21749. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21750. var vertex = complete.scale(radius);
  21751. var normal = BABYLON.Vector3.Normalize(vertex);
  21752. positions.push(vertex.x, vertex.y, vertex.z);
  21753. normals.push(normal.x, normal.y, normal.z);
  21754. uvs.push(normalizedZ, normalizedY);
  21755. }
  21756. if (zRotationStep > 0) {
  21757. var verticesCount = positions.length / 3;
  21758. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21759. indices.push((firstIndex));
  21760. indices.push((firstIndex + 1));
  21761. indices.push(firstIndex + totalYRotationSteps + 1);
  21762. indices.push((firstIndex + totalYRotationSteps + 1));
  21763. indices.push((firstIndex + 1));
  21764. indices.push((firstIndex + totalYRotationSteps + 2));
  21765. }
  21766. }
  21767. }
  21768. // Sides
  21769. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21770. // Result
  21771. var vertexData = new VertexData();
  21772. vertexData.indices = indices;
  21773. vertexData.positions = positions;
  21774. vertexData.normals = normals;
  21775. vertexData.uvs = uvs;
  21776. return vertexData;
  21777. };
  21778. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21779. if (subdivisions === void 0) { subdivisions = 1; }
  21780. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21781. var radiusTop = diameterTop / 2;
  21782. var radiusBottom = diameterBottom / 2;
  21783. var indices = [];
  21784. var positions = [];
  21785. var normals = [];
  21786. var uvs = [];
  21787. height = height || 1;
  21788. diameterTop = diameterTop || 0.5;
  21789. diameterBottom = diameterBottom || 1;
  21790. tessellation = tessellation || 16;
  21791. subdivisions = subdivisions || 1;
  21792. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21793. var getCircleVector = function (i) {
  21794. var angle = (i * 2.0 * Math.PI / tessellation);
  21795. var dx = Math.cos(angle);
  21796. var dz = Math.sin(angle);
  21797. return new BABYLON.Vector3(dx, 0, dz);
  21798. };
  21799. var createCylinderCap = function (isTop) {
  21800. var radius = isTop ? radiusTop : radiusBottom;
  21801. if (radius === 0) {
  21802. return;
  21803. }
  21804. var vbase = positions.length / 3;
  21805. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21806. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21807. if (!isTop) {
  21808. offset.scaleInPlace(-1);
  21809. textureScale.x = -textureScale.x;
  21810. }
  21811. for (var i = 0; i < tessellation; i++) {
  21812. var circleVector = getCircleVector(i);
  21813. var position = circleVector.scale(radius).add(offset);
  21814. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21815. positions.push(position.x, position.y, position.z);
  21816. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21817. }
  21818. for (i = 0; i < tessellation - 2; i++) {
  21819. if (!isTop) {
  21820. indices.push(vbase);
  21821. indices.push(vbase + (i + 2) % tessellation);
  21822. indices.push(vbase + (i + 1) % tessellation);
  21823. }
  21824. else {
  21825. indices.push(vbase);
  21826. indices.push(vbase + (i + 1) % tessellation);
  21827. indices.push(vbase + (i + 2) % tessellation);
  21828. }
  21829. }
  21830. };
  21831. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21832. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21833. var stride = tessellation + 1;
  21834. for (var i = 0; i <= tessellation; i++) {
  21835. var circleVector = getCircleVector(i);
  21836. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21837. var position, radius = radiusBottom;
  21838. for (var s = 0; s <= subdivisions; s++) {
  21839. // Update variables
  21840. position = circleVector.scale(radius);
  21841. position.addInPlace(base.add(offset.scale(s)));
  21842. textureCoordinate.y += 1 / subdivisions;
  21843. radius += (radiusTop - radiusBottom) / subdivisions;
  21844. // Push in arrays
  21845. positions.push(position.x, position.y, position.z);
  21846. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21847. }
  21848. }
  21849. subdivisions += 1;
  21850. for (s = 0; s < subdivisions - 1; s++) {
  21851. for (i = 0; i <= tessellation; i++) {
  21852. indices.push(i * subdivisions + s);
  21853. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21854. indices.push(i * subdivisions + (s + 1));
  21855. indices.push(i * subdivisions + (s + 1));
  21856. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21857. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21858. }
  21859. }
  21860. // Create flat triangle fan caps to seal the top and bottom.
  21861. createCylinderCap(true);
  21862. createCylinderCap(false);
  21863. // Normals
  21864. VertexData.ComputeNormals(positions, indices, normals);
  21865. // Sides
  21866. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21867. // Result
  21868. var vertexData = new VertexData();
  21869. vertexData.indices = indices;
  21870. vertexData.positions = positions;
  21871. vertexData.normals = normals;
  21872. vertexData.uvs = uvs;
  21873. return vertexData;
  21874. };
  21875. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21876. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21877. var indices = [];
  21878. var positions = [];
  21879. var normals = [];
  21880. var uvs = [];
  21881. diameter = diameter || 1;
  21882. thickness = thickness || 0.5;
  21883. tessellation = tessellation || 16;
  21884. var stride = tessellation + 1;
  21885. for (var i = 0; i <= tessellation; i++) {
  21886. var u = i / tessellation;
  21887. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21888. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21889. for (var j = 0; j <= tessellation; j++) {
  21890. var v = 1 - j / tessellation;
  21891. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21892. var dx = Math.cos(innerAngle);
  21893. var dy = Math.sin(innerAngle);
  21894. // Create a vertex.
  21895. var normal = new BABYLON.Vector3(dx, dy, 0);
  21896. var position = normal.scale(thickness / 2);
  21897. var textureCoordinate = new BABYLON.Vector2(u, v);
  21898. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21899. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21900. positions.push(position.x, position.y, position.z);
  21901. normals.push(normal.x, normal.y, normal.z);
  21902. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21903. // And create indices for two triangles.
  21904. var nextI = (i + 1) % stride;
  21905. var nextJ = (j + 1) % stride;
  21906. indices.push(i * stride + j);
  21907. indices.push(i * stride + nextJ);
  21908. indices.push(nextI * stride + j);
  21909. indices.push(i * stride + nextJ);
  21910. indices.push(nextI * stride + nextJ);
  21911. indices.push(nextI * stride + j);
  21912. }
  21913. }
  21914. // Sides
  21915. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21916. // Result
  21917. var vertexData = new VertexData();
  21918. vertexData.indices = indices;
  21919. vertexData.positions = positions;
  21920. vertexData.normals = normals;
  21921. vertexData.uvs = uvs;
  21922. return vertexData;
  21923. };
  21924. VertexData.CreateLines = function (points) {
  21925. var indices = [];
  21926. var positions = [];
  21927. for (var index = 0; index < points.length; index++) {
  21928. positions.push(points[index].x, points[index].y, points[index].z);
  21929. if (index > 0) {
  21930. indices.push(index - 1);
  21931. indices.push(index);
  21932. }
  21933. }
  21934. // Result
  21935. var vertexData = new VertexData();
  21936. vertexData.indices = indices;
  21937. vertexData.positions = positions;
  21938. return vertexData;
  21939. };
  21940. VertexData.CreateGround = function (width, height, subdivisions) {
  21941. var indices = [];
  21942. var positions = [];
  21943. var normals = [];
  21944. var uvs = [];
  21945. var row, col;
  21946. width = width || 1;
  21947. height = height || 1;
  21948. subdivisions = subdivisions || 1;
  21949. for (row = 0; row <= subdivisions; row++) {
  21950. for (col = 0; col <= subdivisions; col++) {
  21951. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21952. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21953. positions.push(position.x, position.y, position.z);
  21954. normals.push(normal.x, normal.y, normal.z);
  21955. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21956. }
  21957. }
  21958. for (row = 0; row < subdivisions; row++) {
  21959. for (col = 0; col < subdivisions; col++) {
  21960. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21961. indices.push(col + 1 + row * (subdivisions + 1));
  21962. indices.push(col + row * (subdivisions + 1));
  21963. indices.push(col + (row + 1) * (subdivisions + 1));
  21964. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21965. indices.push(col + row * (subdivisions + 1));
  21966. }
  21967. }
  21968. // Result
  21969. var vertexData = new VertexData();
  21970. vertexData.indices = indices;
  21971. vertexData.positions = positions;
  21972. vertexData.normals = normals;
  21973. vertexData.uvs = uvs;
  21974. return vertexData;
  21975. };
  21976. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21977. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21978. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21979. var indices = [];
  21980. var positions = [];
  21981. var normals = [];
  21982. var uvs = [];
  21983. var row, col, tileRow, tileCol;
  21984. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21985. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21986. precision.w = (precision.w < 1) ? 1 : precision.w;
  21987. precision.h = (precision.h < 1) ? 1 : precision.h;
  21988. var tileSize = {
  21989. 'w': (xmax - xmin) / subdivisions.w,
  21990. 'h': (zmax - zmin) / subdivisions.h
  21991. };
  21992. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21993. // Indices
  21994. var base = positions.length / 3;
  21995. var rowLength = precision.w + 1;
  21996. for (row = 0; row < precision.h; row++) {
  21997. for (col = 0; col < precision.w; col++) {
  21998. var square = [
  21999. base + col + row * rowLength,
  22000. base + (col + 1) + row * rowLength,
  22001. base + (col + 1) + (row + 1) * rowLength,
  22002. base + col + (row + 1) * rowLength
  22003. ];
  22004. indices.push(square[1]);
  22005. indices.push(square[2]);
  22006. indices.push(square[3]);
  22007. indices.push(square[0]);
  22008. indices.push(square[1]);
  22009. indices.push(square[3]);
  22010. }
  22011. }
  22012. // Position, normals and uvs
  22013. var position = BABYLON.Vector3.Zero();
  22014. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22015. for (row = 0; row <= precision.h; row++) {
  22016. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22017. for (col = 0; col <= precision.w; col++) {
  22018. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22019. position.y = 0;
  22020. positions.push(position.x, position.y, position.z);
  22021. normals.push(normal.x, normal.y, normal.z);
  22022. uvs.push(col / precision.w, row / precision.h);
  22023. }
  22024. }
  22025. }
  22026. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22027. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22028. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22029. }
  22030. }
  22031. // Result
  22032. var vertexData = new VertexData();
  22033. vertexData.indices = indices;
  22034. vertexData.positions = positions;
  22035. vertexData.normals = normals;
  22036. vertexData.uvs = uvs;
  22037. return vertexData;
  22038. };
  22039. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22040. var indices = [];
  22041. var positions = [];
  22042. var normals = [];
  22043. var uvs = [];
  22044. var row, col;
  22045. for (row = 0; row <= subdivisions; row++) {
  22046. for (col = 0; col <= subdivisions; col++) {
  22047. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22048. // Compute height
  22049. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22050. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22051. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22052. var r = buffer[pos] / 255.0;
  22053. var g = buffer[pos + 1] / 255.0;
  22054. var b = buffer[pos + 2] / 255.0;
  22055. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22056. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22057. // Add vertex
  22058. positions.push(position.x, position.y, position.z);
  22059. normals.push(0, 0, 0);
  22060. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22061. }
  22062. }
  22063. for (row = 0; row < subdivisions; row++) {
  22064. for (col = 0; col < subdivisions; col++) {
  22065. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22066. indices.push(col + 1 + row * (subdivisions + 1));
  22067. indices.push(col + row * (subdivisions + 1));
  22068. indices.push(col + (row + 1) * (subdivisions + 1));
  22069. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22070. indices.push(col + row * (subdivisions + 1));
  22071. }
  22072. }
  22073. // Normals
  22074. VertexData.ComputeNormals(positions, indices, normals);
  22075. // Result
  22076. var vertexData = new VertexData();
  22077. vertexData.indices = indices;
  22078. vertexData.positions = positions;
  22079. vertexData.normals = normals;
  22080. vertexData.uvs = uvs;
  22081. return vertexData;
  22082. };
  22083. VertexData.CreatePlane = function (size, sideOrientation) {
  22084. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22085. var indices = [];
  22086. var positions = [];
  22087. var normals = [];
  22088. var uvs = [];
  22089. size = size || 1;
  22090. // Vertices
  22091. var halfSize = size / 2.0;
  22092. positions.push(-halfSize, -halfSize, 0);
  22093. normals.push(0, 0, -1.0);
  22094. uvs.push(0.0, 0.0);
  22095. positions.push(halfSize, -halfSize, 0);
  22096. normals.push(0, 0, -1.0);
  22097. uvs.push(1.0, 0.0);
  22098. positions.push(halfSize, halfSize, 0);
  22099. normals.push(0, 0, -1.0);
  22100. uvs.push(1.0, 1.0);
  22101. positions.push(-halfSize, halfSize, 0);
  22102. normals.push(0, 0, -1.0);
  22103. uvs.push(0.0, 1.0);
  22104. // Indices
  22105. indices.push(0);
  22106. indices.push(1);
  22107. indices.push(2);
  22108. indices.push(0);
  22109. indices.push(2);
  22110. indices.push(3);
  22111. // Sides
  22112. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22113. // Result
  22114. var vertexData = new VertexData();
  22115. vertexData.indices = indices;
  22116. vertexData.positions = positions;
  22117. vertexData.normals = normals;
  22118. vertexData.uvs = uvs;
  22119. return vertexData;
  22120. };
  22121. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22122. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22123. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22124. var indices = [];
  22125. var positions = [];
  22126. var normals = [];
  22127. var uvs = [];
  22128. radius = radius || 2;
  22129. tube = tube || 0.5;
  22130. radialSegments = radialSegments || 32;
  22131. tubularSegments = tubularSegments || 32;
  22132. p = p || 2;
  22133. q = q || 3;
  22134. // Helper
  22135. var getPos = function (angle) {
  22136. var cu = Math.cos(angle);
  22137. var su = Math.sin(angle);
  22138. var quOverP = q / p * angle;
  22139. var cs = Math.cos(quOverP);
  22140. var tx = radius * (2 + cs) * 0.5 * cu;
  22141. var ty = radius * (2 + cs) * su * 0.5;
  22142. var tz = radius * Math.sin(quOverP) * 0.5;
  22143. return new BABYLON.Vector3(tx, ty, tz);
  22144. };
  22145. for (var i = 0; i <= radialSegments; i++) {
  22146. var modI = i % radialSegments;
  22147. var u = modI / radialSegments * 2 * p * Math.PI;
  22148. var p1 = getPos(u);
  22149. var p2 = getPos(u + 0.01);
  22150. var tang = p2.subtract(p1);
  22151. var n = p2.add(p1);
  22152. var bitan = BABYLON.Vector3.Cross(tang, n);
  22153. n = BABYLON.Vector3.Cross(bitan, tang);
  22154. bitan.normalize();
  22155. n.normalize();
  22156. for (var j = 0; j < tubularSegments; j++) {
  22157. var modJ = j % tubularSegments;
  22158. var v = modJ / tubularSegments * 2 * Math.PI;
  22159. var cx = -tube * Math.cos(v);
  22160. var cy = tube * Math.sin(v);
  22161. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22162. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22163. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22164. uvs.push(i / radialSegments);
  22165. uvs.push(j / tubularSegments);
  22166. }
  22167. }
  22168. for (i = 0; i < radialSegments; i++) {
  22169. for (j = 0; j < tubularSegments; j++) {
  22170. var jNext = (j + 1) % tubularSegments;
  22171. var a = i * tubularSegments + j;
  22172. var b = (i + 1) * tubularSegments + j;
  22173. var c = (i + 1) * tubularSegments + jNext;
  22174. var d = i * tubularSegments + jNext;
  22175. indices.push(d);
  22176. indices.push(b);
  22177. indices.push(a);
  22178. indices.push(d);
  22179. indices.push(c);
  22180. indices.push(b);
  22181. }
  22182. }
  22183. // Normals
  22184. VertexData.ComputeNormals(positions, indices, normals);
  22185. // Sides
  22186. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22187. // Result
  22188. var vertexData = new VertexData();
  22189. vertexData.indices = indices;
  22190. vertexData.positions = positions;
  22191. vertexData.normals = normals;
  22192. vertexData.uvs = uvs;
  22193. return vertexData;
  22194. };
  22195. // Tools
  22196. VertexData.ComputeNormals = function (positions, indices, normals) {
  22197. var positionVectors = [];
  22198. var facesOfVertices = [];
  22199. var index;
  22200. for (index = 0; index < positions.length; index += 3) {
  22201. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22202. positionVectors.push(vector3);
  22203. facesOfVertices.push([]);
  22204. }
  22205. // Compute normals
  22206. var facesNormals = [];
  22207. for (index = 0; index < indices.length / 3; index++) {
  22208. var i1 = indices[index * 3];
  22209. var i2 = indices[index * 3 + 1];
  22210. var i3 = indices[index * 3 + 2];
  22211. var p1 = positionVectors[i1];
  22212. var p2 = positionVectors[i2];
  22213. var p3 = positionVectors[i3];
  22214. var p1p2 = p1.subtract(p2);
  22215. var p3p2 = p3.subtract(p2);
  22216. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22217. facesOfVertices[i1].push(index);
  22218. facesOfVertices[i2].push(index);
  22219. facesOfVertices[i3].push(index);
  22220. }
  22221. for (index = 0; index < positionVectors.length; index++) {
  22222. var faces = facesOfVertices[index];
  22223. var normal = BABYLON.Vector3.Zero();
  22224. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22225. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22226. }
  22227. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22228. normals[index * 3] = normal.x;
  22229. normals[index * 3 + 1] = normal.y;
  22230. normals[index * 3 + 2] = normal.z;
  22231. }
  22232. };
  22233. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22234. var li = indices.length;
  22235. var ln = normals.length;
  22236. var i;
  22237. var n;
  22238. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22239. switch (sideOrientation) {
  22240. case BABYLON.Mesh.FRONTSIDE:
  22241. break;
  22242. case BABYLON.Mesh.BACKSIDE:
  22243. var tmp;
  22244. for (i = 0; i < li; i += 3) {
  22245. tmp = indices[i];
  22246. indices[i] = indices[i + 2];
  22247. indices[i + 2] = tmp;
  22248. }
  22249. for (n = 0; n < ln; n++) {
  22250. normals[n] = -normals[n];
  22251. }
  22252. break;
  22253. case BABYLON.Mesh.DOUBLESIDE:
  22254. // positions
  22255. var lp = positions.length;
  22256. var l = lp / 3;
  22257. for (var p = 0; p < lp; p++) {
  22258. positions[lp + p] = positions[p];
  22259. }
  22260. for (i = 0; i < li; i += 3) {
  22261. indices[i + li] = indices[i + 2] + l;
  22262. indices[i + 1 + li] = indices[i + 1] + l;
  22263. indices[i + 2 + li] = indices[i] + l;
  22264. }
  22265. for (n = 0; n < ln; n++) {
  22266. normals[ln + n] = -normals[n];
  22267. }
  22268. // uvs
  22269. var lu = uvs.length;
  22270. for (var u = 0; u < lu; u++) {
  22271. uvs[u + lu] = uvs[u];
  22272. }
  22273. break;
  22274. }
  22275. };
  22276. return VertexData;
  22277. })();
  22278. BABYLON.VertexData = VertexData;
  22279. })(BABYLON || (BABYLON = {}));
  22280. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22281. var BABYLON;
  22282. (function (BABYLON) {
  22283. var buildCamera = function (that, name) {
  22284. that._leftCamera.isIntermediate = true;
  22285. that.subCameras.push(that._leftCamera);
  22286. that.subCameras.push(that._rightCamera);
  22287. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22288. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22289. that._anaglyphPostProcess.onApply = function (effect) {
  22290. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22291. };
  22292. that._update();
  22293. };
  22294. var AnaglyphArcRotateCamera = (function (_super) {
  22295. __extends(AnaglyphArcRotateCamera, _super);
  22296. // ANY
  22297. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22298. _super.call(this, name, alpha, beta, radius, target, scene);
  22299. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22300. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22301. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22302. buildCamera(this, name);
  22303. }
  22304. AnaglyphArcRotateCamera.prototype._update = function () {
  22305. this._updateCamera(this._leftCamera);
  22306. this._updateCamera(this._rightCamera);
  22307. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22308. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22309. _super.prototype._update.call(this);
  22310. };
  22311. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22312. camera.beta = this.beta;
  22313. camera.radius = this.radius;
  22314. camera.minZ = this.minZ;
  22315. camera.maxZ = this.maxZ;
  22316. camera.fov = this.fov;
  22317. camera.target = this.target;
  22318. };
  22319. return AnaglyphArcRotateCamera;
  22320. })(BABYLON.ArcRotateCamera);
  22321. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22322. var AnaglyphFreeCamera = (function (_super) {
  22323. __extends(AnaglyphFreeCamera, _super);
  22324. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22325. _super.call(this, name, position, scene);
  22326. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22327. this._transformMatrix = new BABYLON.Matrix();
  22328. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22329. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22330. buildCamera(this, name);
  22331. }
  22332. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22333. var target = this.getTarget();
  22334. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22335. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22336. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22337. };
  22338. AnaglyphFreeCamera.prototype._update = function () {
  22339. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22340. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22341. this._updateCamera(this._leftCamera);
  22342. this._updateCamera(this._rightCamera);
  22343. _super.prototype._update.call(this);
  22344. };
  22345. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22346. camera.minZ = this.minZ;
  22347. camera.maxZ = this.maxZ;
  22348. camera.fov = this.fov;
  22349. camera.viewport = this.viewport;
  22350. camera.setTarget(this.getTarget());
  22351. };
  22352. return AnaglyphFreeCamera;
  22353. })(BABYLON.FreeCamera);
  22354. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22355. })(BABYLON || (BABYLON = {}));
  22356. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22357. var BABYLON;
  22358. (function (BABYLON) {
  22359. var AnaglyphPostProcess = (function (_super) {
  22360. __extends(AnaglyphPostProcess, _super);
  22361. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22362. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22363. }
  22364. return AnaglyphPostProcess;
  22365. })(BABYLON.PostProcess);
  22366. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22367. })(BABYLON || (BABYLON = {}));
  22368. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22369. (function (BABYLON) {
  22370. var Tags = (function () {
  22371. function Tags() {
  22372. }
  22373. Tags.EnableFor = function (obj) {
  22374. obj._tags = obj._tags || {};
  22375. obj.hasTags = function () {
  22376. return Tags.HasTags(obj);
  22377. };
  22378. obj.addTags = function (tagsString) {
  22379. return Tags.AddTagsTo(obj, tagsString);
  22380. };
  22381. obj.removeTags = function (tagsString) {
  22382. return Tags.RemoveTagsFrom(obj, tagsString);
  22383. };
  22384. obj.matchesTagsQuery = function (tagsQuery) {
  22385. return Tags.MatchesQuery(obj, tagsQuery);
  22386. };
  22387. };
  22388. Tags.DisableFor = function (obj) {
  22389. delete obj._tags;
  22390. delete obj.hasTags;
  22391. delete obj.addTags;
  22392. delete obj.removeTags;
  22393. delete obj.matchesTagsQuery;
  22394. };
  22395. Tags.HasTags = function (obj) {
  22396. if (!obj._tags) {
  22397. return false;
  22398. }
  22399. return !BABYLON.Tools.IsEmpty(obj._tags);
  22400. };
  22401. Tags.GetTags = function (obj) {
  22402. if (!obj._tags) {
  22403. return null;
  22404. }
  22405. return obj._tags;
  22406. };
  22407. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22408. // a tag cannot start with '||', '&&', and '!'
  22409. // it cannot contain whitespaces
  22410. Tags.AddTagsTo = function (obj, tagsString) {
  22411. if (!tagsString) {
  22412. return;
  22413. }
  22414. var tags = tagsString.split(" ");
  22415. for (var t in tags) {
  22416. Tags._AddTagTo(obj, tags[t]);
  22417. }
  22418. };
  22419. Tags._AddTagTo = function (obj, tag) {
  22420. tag = tag.trim();
  22421. if (tag === "" || tag === "true" || tag === "false") {
  22422. return;
  22423. }
  22424. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22425. return;
  22426. }
  22427. Tags.EnableFor(obj);
  22428. obj._tags[tag] = true;
  22429. };
  22430. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22431. if (!Tags.HasTags(obj)) {
  22432. return;
  22433. }
  22434. var tags = tagsString.split(" ");
  22435. for (var t in tags) {
  22436. Tags._RemoveTagFrom(obj, tags[t]);
  22437. }
  22438. };
  22439. Tags._RemoveTagFrom = function (obj, tag) {
  22440. delete obj._tags[tag];
  22441. };
  22442. Tags.MatchesQuery = function (obj, tagsQuery) {
  22443. if (tagsQuery === undefined) {
  22444. return true;
  22445. }
  22446. if (tagsQuery === "") {
  22447. return Tags.HasTags(obj);
  22448. }
  22449. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22450. };
  22451. return Tags;
  22452. })();
  22453. BABYLON.Tags = Tags;
  22454. })(BABYLON || (BABYLON = {}));
  22455. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22456. (function (BABYLON) {
  22457. var Internals;
  22458. (function (Internals) {
  22459. var AndOrNotEvaluator = (function () {
  22460. function AndOrNotEvaluator() {
  22461. }
  22462. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22463. if (!query.match(/\([^\(\)]*\)/g)) {
  22464. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22465. }
  22466. else {
  22467. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22468. // remove parenthesis
  22469. r = r.slice(1, r.length - 1);
  22470. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22471. });
  22472. }
  22473. if (query === "true") {
  22474. return true;
  22475. }
  22476. if (query === "false") {
  22477. return false;
  22478. }
  22479. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22480. };
  22481. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22482. evaluateCallback = evaluateCallback || (function (r) {
  22483. return r === "true" ? true : false;
  22484. });
  22485. var result;
  22486. var or = parenthesisContent.split("||");
  22487. for (var i in or) {
  22488. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22489. var and = ori.split("&&");
  22490. if (and.length > 1) {
  22491. for (var j = 0; j < and.length; ++j) {
  22492. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22493. if (andj !== "true" && andj !== "false") {
  22494. if (andj[0] === "!") {
  22495. result = !evaluateCallback(andj.substring(1));
  22496. }
  22497. else {
  22498. result = evaluateCallback(andj);
  22499. }
  22500. }
  22501. else {
  22502. result = andj === "true" ? true : false;
  22503. }
  22504. if (!result) {
  22505. ori = "false";
  22506. break;
  22507. }
  22508. }
  22509. }
  22510. if (result || ori === "true") {
  22511. result = true;
  22512. break;
  22513. }
  22514. // result equals false (or undefined)
  22515. if (ori !== "true" && ori !== "false") {
  22516. if (ori[0] === "!") {
  22517. result = !evaluateCallback(ori.substring(1));
  22518. }
  22519. else {
  22520. result = evaluateCallback(ori);
  22521. }
  22522. }
  22523. else {
  22524. result = ori === "true" ? true : false;
  22525. }
  22526. }
  22527. // the whole parenthesis scope is replaced by 'true' or 'false'
  22528. return result ? "true" : "false";
  22529. };
  22530. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22531. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22532. // remove whitespaces
  22533. r = r.replace(/[\s]/g, function () { return ""; });
  22534. return r.length % 2 ? "!" : "";
  22535. });
  22536. booleanString = booleanString.trim();
  22537. if (booleanString === "!true") {
  22538. booleanString = "false";
  22539. }
  22540. else if (booleanString === "!false") {
  22541. booleanString = "true";
  22542. }
  22543. return booleanString;
  22544. };
  22545. return AndOrNotEvaluator;
  22546. })();
  22547. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22548. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22549. })(BABYLON || (BABYLON = {}));
  22550. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22551. (function (BABYLON) {
  22552. var PostProcessRenderPass = (function () {
  22553. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22554. this._enabled = true;
  22555. this._refCount = 0;
  22556. this._name = name;
  22557. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22558. this.setRenderList(renderList);
  22559. this._renderTexture.onBeforeRender = beforeRender;
  22560. this._renderTexture.onAfterRender = afterRender;
  22561. this._scene = scene;
  22562. this._renderList = renderList;
  22563. }
  22564. // private
  22565. PostProcessRenderPass.prototype._incRefCount = function () {
  22566. if (this._refCount === 0) {
  22567. this._scene.customRenderTargets.push(this._renderTexture);
  22568. }
  22569. return ++this._refCount;
  22570. };
  22571. PostProcessRenderPass.prototype._decRefCount = function () {
  22572. this._refCount--;
  22573. if (this._refCount <= 0) {
  22574. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22575. }
  22576. return this._refCount;
  22577. };
  22578. PostProcessRenderPass.prototype._update = function () {
  22579. this.setRenderList(this._renderList);
  22580. };
  22581. // public
  22582. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22583. this._renderTexture.renderList = renderList;
  22584. };
  22585. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22586. return this._renderTexture;
  22587. };
  22588. return PostProcessRenderPass;
  22589. })();
  22590. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22591. })(BABYLON || (BABYLON = {}));
  22592. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22593. (function (BABYLON) {
  22594. var PostProcessRenderEffect = (function () {
  22595. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22596. this._engine = engine;
  22597. this._name = name;
  22598. this._singleInstance = singleInstance || true;
  22599. this._getPostProcess = getPostProcess;
  22600. this._cameras = [];
  22601. this._indicesForCamera = [];
  22602. this._postProcesses = {};
  22603. this._renderPasses = {};
  22604. this._renderEffectAsPasses = {};
  22605. }
  22606. PostProcessRenderEffect.prototype._update = function () {
  22607. for (var renderPassName in this._renderPasses) {
  22608. this._renderPasses[renderPassName]._update();
  22609. }
  22610. };
  22611. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22612. this._renderPasses[renderPass._name] = renderPass;
  22613. this._linkParameters();
  22614. };
  22615. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22616. delete this._renderPasses[renderPass._name];
  22617. this._linkParameters();
  22618. };
  22619. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22620. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22621. this._linkParameters();
  22622. };
  22623. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22624. for (var renderPassName in this._renderPasses) {
  22625. if (renderPassName === passName) {
  22626. return this._renderPasses[passName];
  22627. }
  22628. }
  22629. };
  22630. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22631. this._renderPasses = {};
  22632. this._linkParameters();
  22633. };
  22634. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22635. var cameraKey;
  22636. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22637. for (var i = 0; i < _cam.length; i++) {
  22638. var camera = _cam[i];
  22639. var cameraName = camera.name;
  22640. if (this._singleInstance) {
  22641. cameraKey = 0;
  22642. }
  22643. else {
  22644. cameraKey = cameraName;
  22645. }
  22646. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22647. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22648. if (!this._indicesForCamera[cameraName]) {
  22649. this._indicesForCamera[cameraName] = [];
  22650. }
  22651. this._indicesForCamera[cameraName].push(index);
  22652. if (this._cameras.indexOf(camera) === -1) {
  22653. this._cameras[cameraName] = camera;
  22654. }
  22655. for (var passName in this._renderPasses) {
  22656. this._renderPasses[passName]._incRefCount();
  22657. }
  22658. }
  22659. this._linkParameters();
  22660. };
  22661. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22663. for (var i = 0; i < _cam.length; i++) {
  22664. var camera = _cam[i];
  22665. var cameraName = camera.name;
  22666. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22667. var index = this._cameras.indexOf(cameraName);
  22668. this._indicesForCamera.splice(index, 1);
  22669. this._cameras.splice(index, 1);
  22670. for (var passName in this._renderPasses) {
  22671. this._renderPasses[passName]._decRefCount();
  22672. }
  22673. }
  22674. };
  22675. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22676. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22677. for (var i = 0; i < _cam.length; i++) {
  22678. var camera = _cam[i];
  22679. var cameraName = camera.name;
  22680. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22681. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22682. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22683. }
  22684. }
  22685. for (var passName in this._renderPasses) {
  22686. this._renderPasses[passName]._incRefCount();
  22687. }
  22688. }
  22689. };
  22690. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22691. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22692. for (var i = 0; i < _cam.length; i++) {
  22693. var camera = _cam[i];
  22694. var cameraName = camera.Name;
  22695. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22696. for (var passName in this._renderPasses) {
  22697. this._renderPasses[passName]._decRefCount();
  22698. }
  22699. }
  22700. };
  22701. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22702. if (this._singleInstance) {
  22703. return this._postProcesses[0];
  22704. }
  22705. else {
  22706. return this._postProcesses[camera.name];
  22707. }
  22708. };
  22709. PostProcessRenderEffect.prototype._linkParameters = function () {
  22710. var _this = this;
  22711. for (var index in this._postProcesses) {
  22712. if (this.applyParameters) {
  22713. this.applyParameters(this._postProcesses[index]);
  22714. }
  22715. this._postProcesses[index].onBeforeRender = function (effect) {
  22716. _this._linkTextures(effect);
  22717. };
  22718. }
  22719. };
  22720. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22721. for (var renderPassName in this._renderPasses) {
  22722. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22723. }
  22724. for (var renderEffectName in this._renderEffectAsPasses) {
  22725. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22726. }
  22727. };
  22728. return PostProcessRenderEffect;
  22729. })();
  22730. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22731. })(BABYLON || (BABYLON = {}));
  22732. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22733. (function (BABYLON) {
  22734. var PostProcessRenderPipeline = (function () {
  22735. function PostProcessRenderPipeline(engine, name) {
  22736. this._engine = engine;
  22737. this._name = name;
  22738. this._renderEffects = {};
  22739. this._renderEffectsForIsolatedPass = {};
  22740. this._cameras = [];
  22741. }
  22742. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22743. this._renderEffects[renderEffect._name] = renderEffect;
  22744. };
  22745. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22746. var renderEffects = this._renderEffects[renderEffectName];
  22747. if (!renderEffects) {
  22748. return;
  22749. }
  22750. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22751. };
  22752. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22753. var renderEffects = this._renderEffects[renderEffectName];
  22754. if (!renderEffects) {
  22755. return;
  22756. }
  22757. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22758. };
  22759. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22760. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22761. var indicesToDelete = [];
  22762. for (var i = 0; i < _cam.length; i++) {
  22763. var camera = _cam[i];
  22764. var cameraName = camera.name;
  22765. if (this._cameras.indexOf(camera) === -1) {
  22766. this._cameras[cameraName] = camera;
  22767. }
  22768. else if (unique) {
  22769. indicesToDelete.push(i);
  22770. }
  22771. }
  22772. for (var i = 0; i < indicesToDelete.length; i++) {
  22773. cameras.splice(indicesToDelete[i], 1);
  22774. }
  22775. for (var renderEffectName in this._renderEffects) {
  22776. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22777. }
  22778. };
  22779. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22780. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22781. for (var renderEffectName in this._renderEffects) {
  22782. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22783. }
  22784. for (var i = 0; i < _cam.length; i++) {
  22785. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22786. }
  22787. };
  22788. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22789. var _this = this;
  22790. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22791. var pass = null;
  22792. for (var renderEffectName in this._renderEffects) {
  22793. pass = this._renderEffects[renderEffectName].getPass(passName);
  22794. if (pass != null) {
  22795. break;
  22796. }
  22797. }
  22798. if (pass === null) {
  22799. return;
  22800. }
  22801. for (var renderEffectName in this._renderEffects) {
  22802. this._renderEffects[renderEffectName]._disable(_cam);
  22803. }
  22804. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22805. for (var i = 0; i < _cam.length; i++) {
  22806. var camera = _cam[i];
  22807. var cameraName = camera.name;
  22808. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22809. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22810. });
  22811. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22812. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22813. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22814. }
  22815. };
  22816. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22817. var _this = this;
  22818. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22819. for (var i = 0; i < _cam.length; i++) {
  22820. var camera = _cam[i];
  22821. var cameraName = camera.name;
  22822. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22823. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22824. });
  22825. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22826. }
  22827. for (var renderEffectName in this._renderEffects) {
  22828. this._renderEffects[renderEffectName]._enable(_cam);
  22829. }
  22830. };
  22831. PostProcessRenderPipeline.prototype._update = function () {
  22832. for (var renderEffectName in this._renderEffects) {
  22833. this._renderEffects[renderEffectName]._update();
  22834. }
  22835. for (var i = 0; i < this._cameras.length; i++) {
  22836. var cameraName = this._cameras[i].name;
  22837. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22838. this._renderEffectsForIsolatedPass[cameraName]._update();
  22839. }
  22840. }
  22841. };
  22842. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22843. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22844. return PostProcessRenderPipeline;
  22845. })();
  22846. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22847. })(BABYLON || (BABYLON = {}));
  22848. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22849. (function (BABYLON) {
  22850. var PostProcessRenderPipelineManager = (function () {
  22851. function PostProcessRenderPipelineManager() {
  22852. this._renderPipelines = {};
  22853. }
  22854. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22855. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22856. };
  22857. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22858. var renderPipeline = this._renderPipelines[renderPipelineName];
  22859. if (!renderPipeline) {
  22860. return;
  22861. }
  22862. renderPipeline._attachCameras(cameras, unique);
  22863. };
  22864. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22865. var renderPipeline = this._renderPipelines[renderPipelineName];
  22866. if (!renderPipeline) {
  22867. return;
  22868. }
  22869. renderPipeline._detachCameras(cameras);
  22870. };
  22871. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22872. var renderPipeline = this._renderPipelines[renderPipelineName];
  22873. if (!renderPipeline) {
  22874. return;
  22875. }
  22876. renderPipeline._enableEffect(renderEffectName, cameras);
  22877. };
  22878. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22879. var renderPipeline = this._renderPipelines[renderPipelineName];
  22880. if (!renderPipeline) {
  22881. return;
  22882. }
  22883. renderPipeline._disableEffect(renderEffectName, cameras);
  22884. };
  22885. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22886. var renderPipeline = this._renderPipelines[renderPipelineName];
  22887. if (!renderPipeline) {
  22888. return;
  22889. }
  22890. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22891. };
  22892. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22893. var renderPipeline = this._renderPipelines[renderPipelineName];
  22894. if (!renderPipeline) {
  22895. return;
  22896. }
  22897. renderPipeline._disableDisplayOnlyPass(cameras);
  22898. };
  22899. PostProcessRenderPipelineManager.prototype.update = function () {
  22900. for (var renderPipelineName in this._renderPipelines) {
  22901. this._renderPipelines[renderPipelineName]._update();
  22902. }
  22903. };
  22904. return PostProcessRenderPipelineManager;
  22905. })();
  22906. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22907. })(BABYLON || (BABYLON = {}));
  22908. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22909. var BABYLON;
  22910. (function (BABYLON) {
  22911. var DisplayPassPostProcess = (function (_super) {
  22912. __extends(DisplayPassPostProcess, _super);
  22913. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22914. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22915. }
  22916. return DisplayPassPostProcess;
  22917. })(BABYLON.PostProcess);
  22918. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22919. })(BABYLON || (BABYLON = {}));
  22920. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22921. (function (BABYLON) {
  22922. var BoundingBoxRenderer = (function () {
  22923. function BoundingBoxRenderer(scene) {
  22924. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22925. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22926. this.showBackLines = true;
  22927. this.renderList = new BABYLON.SmartArray(32);
  22928. this._scene = scene;
  22929. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22930. attributes: ["position"],
  22931. uniforms: ["worldViewProjection", "color"]
  22932. });
  22933. var engine = this._scene.getEngine();
  22934. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22935. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22936. 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]);
  22937. }
  22938. BoundingBoxRenderer.prototype.reset = function () {
  22939. this.renderList.reset();
  22940. };
  22941. BoundingBoxRenderer.prototype.render = function () {
  22942. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22943. return;
  22944. }
  22945. var engine = this._scene.getEngine();
  22946. engine.setDepthWrite(false);
  22947. this._colorShader._preBind();
  22948. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22949. var boundingBox = this.renderList.data[boundingBoxIndex];
  22950. var min = boundingBox.minimum;
  22951. var max = boundingBox.maximum;
  22952. var diff = max.subtract(min);
  22953. var median = min.add(diff.scale(0.5));
  22954. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22955. // VBOs
  22956. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22957. if (this.showBackLines) {
  22958. // Back
  22959. engine.setDepthFunctionToGreaterOrEqual();
  22960. this._scene.resetCachedMaterial();
  22961. this._colorShader.setColor4("color", this.backColor.toColor4());
  22962. this._colorShader.bind(worldMatrix);
  22963. // Draw order
  22964. engine.draw(false, 0, 24);
  22965. }
  22966. // Front
  22967. engine.setDepthFunctionToLess();
  22968. this._scene.resetCachedMaterial();
  22969. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22970. this._colorShader.bind(worldMatrix);
  22971. // Draw order
  22972. engine.draw(false, 0, 24);
  22973. }
  22974. this._colorShader.unbind();
  22975. engine.setDepthFunctionToLessOrEqual();
  22976. engine.setDepthWrite(true);
  22977. };
  22978. BoundingBoxRenderer.prototype.dispose = function () {
  22979. this._colorShader.dispose();
  22980. this._vb.dispose();
  22981. this._scene.getEngine()._releaseBuffer(this._ib);
  22982. };
  22983. return BoundingBoxRenderer;
  22984. })();
  22985. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22986. })(BABYLON || (BABYLON = {}));
  22987. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22988. (function (BABYLON) {
  22989. var Internals;
  22990. (function (Internals) {
  22991. /*
  22992. * Based on jsTGALoader - Javascript loader for TGA file
  22993. * By Vincent Thibault
  22994. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22995. */
  22996. var TGATools = (function () {
  22997. function TGATools() {
  22998. }
  22999. TGATools.GetTGAHeader = function (data) {
  23000. var offset = 0;
  23001. var header = {
  23002. id_length: data[offset++],
  23003. colormap_type: data[offset++],
  23004. image_type: data[offset++],
  23005. colormap_index: data[offset++] | data[offset++] << 8,
  23006. colormap_length: data[offset++] | data[offset++] << 8,
  23007. colormap_size: data[offset++],
  23008. origin: [
  23009. data[offset++] | data[offset++] << 8,
  23010. data[offset++] | data[offset++] << 8
  23011. ],
  23012. width: data[offset++] | data[offset++] << 8,
  23013. height: data[offset++] | data[offset++] << 8,
  23014. pixel_size: data[offset++],
  23015. flags: data[offset++]
  23016. };
  23017. return header;
  23018. };
  23019. TGATools.UploadContent = function (gl, data) {
  23020. // Not enough data to contain header ?
  23021. if (data.length < 19) {
  23022. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23023. return;
  23024. }
  23025. // Read Header
  23026. var offset = 18;
  23027. var header = TGATools.GetTGAHeader(data);
  23028. // Assume it's a valid Targa file.
  23029. if (header.id_length + offset > data.length) {
  23030. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23031. return;
  23032. }
  23033. // Skip not needed data
  23034. offset += header.id_length;
  23035. var use_rle = false;
  23036. var use_pal = false;
  23037. var use_rgb = false;
  23038. var use_grey = false;
  23039. switch (header.image_type) {
  23040. case TGATools._TYPE_RLE_INDEXED:
  23041. use_rle = true;
  23042. case TGATools._TYPE_INDEXED:
  23043. use_pal = true;
  23044. break;
  23045. case TGATools._TYPE_RLE_RGB:
  23046. use_rle = true;
  23047. case TGATools._TYPE_RGB:
  23048. use_rgb = true;
  23049. break;
  23050. case TGATools._TYPE_RLE_GREY:
  23051. use_rle = true;
  23052. case TGATools._TYPE_GREY:
  23053. use_grey = true;
  23054. break;
  23055. }
  23056. var pixel_data;
  23057. var numAlphaBits = header.flags & 0xf;
  23058. var pixel_size = header.pixel_size >> 3;
  23059. var pixel_total = header.width * header.height * pixel_size;
  23060. // Read palettes
  23061. var palettes;
  23062. if (use_pal) {
  23063. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23064. }
  23065. // Read LRE
  23066. if (use_rle) {
  23067. pixel_data = new Uint8Array(pixel_total);
  23068. var c, count, i;
  23069. var localOffset = 0;
  23070. var pixels = new Uint8Array(pixel_size);
  23071. while (offset < pixel_total && localOffset < pixel_total) {
  23072. c = data[offset++];
  23073. count = (c & 0x7f) + 1;
  23074. // RLE pixels
  23075. if (c & 0x80) {
  23076. for (i = 0; i < pixel_size; ++i) {
  23077. pixels[i] = data[offset++];
  23078. }
  23079. for (i = 0; i < count; ++i) {
  23080. pixel_data.set(pixels, localOffset + i * pixel_size);
  23081. }
  23082. localOffset += pixel_size * count;
  23083. }
  23084. else {
  23085. count *= pixel_size;
  23086. for (i = 0; i < count; ++i) {
  23087. pixel_data[localOffset + i] = data[offset++];
  23088. }
  23089. localOffset += count;
  23090. }
  23091. }
  23092. }
  23093. else {
  23094. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23095. }
  23096. // Load to texture
  23097. var x_start, y_start, x_step, y_step, y_end, x_end;
  23098. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23099. default:
  23100. case TGATools._ORIGIN_UL:
  23101. x_start = 0;
  23102. x_step = 1;
  23103. x_end = header.width;
  23104. y_start = 0;
  23105. y_step = 1;
  23106. y_end = header.height;
  23107. break;
  23108. case TGATools._ORIGIN_BL:
  23109. x_start = 0;
  23110. x_step = 1;
  23111. x_end = header.width;
  23112. y_start = header.height - 1;
  23113. y_step = -1;
  23114. y_end = -1;
  23115. break;
  23116. case TGATools._ORIGIN_UR:
  23117. x_start = header.width - 1;
  23118. x_step = -1;
  23119. x_end = -1;
  23120. y_start = 0;
  23121. y_step = 1;
  23122. y_end = header.height;
  23123. break;
  23124. case TGATools._ORIGIN_BR:
  23125. x_start = header.width - 1;
  23126. x_step = -1;
  23127. x_end = -1;
  23128. y_start = header.height - 1;
  23129. y_step = -1;
  23130. y_end = -1;
  23131. break;
  23132. }
  23133. // Load the specify method
  23134. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23135. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23136. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23137. };
  23138. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23139. var image = pixel_data, colormap = palettes;
  23140. var width = header.width, height = header.height;
  23141. var color, i = 0, x, y;
  23142. var imageData = new Uint8Array(width * height * 4);
  23143. for (y = y_start; y !== y_end; y += y_step) {
  23144. for (x = x_start; x !== x_end; x += x_step, i++) {
  23145. color = image[i];
  23146. imageData[(x + width * y) * 4 + 3] = 255;
  23147. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23148. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23149. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23150. }
  23151. }
  23152. return imageData;
  23153. };
  23154. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23155. var image = pixel_data;
  23156. var width = header.width, height = header.height;
  23157. var color, i = 0, x, y;
  23158. var imageData = new Uint8Array(width * height * 4);
  23159. for (y = y_start; y !== y_end; y += y_step) {
  23160. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23161. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23162. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23163. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23164. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23165. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23166. }
  23167. }
  23168. return imageData;
  23169. };
  23170. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23171. var image = pixel_data;
  23172. var width = header.width, height = header.height;
  23173. var i = 0, x, y;
  23174. var imageData = new Uint8Array(width * height * 4);
  23175. for (y = y_start; y !== y_end; y += y_step) {
  23176. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23177. imageData[(x + width * y) * 4 + 3] = 255;
  23178. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23179. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23180. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23181. }
  23182. }
  23183. return imageData;
  23184. };
  23185. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23186. var image = pixel_data;
  23187. var width = header.width, height = header.height;
  23188. var i = 0, x, y;
  23189. var imageData = new Uint8Array(width * height * 4);
  23190. for (y = y_start; y !== y_end; y += y_step) {
  23191. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23192. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23193. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23194. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23195. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23196. }
  23197. }
  23198. return imageData;
  23199. };
  23200. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23201. var image = pixel_data;
  23202. var width = header.width, height = header.height;
  23203. var color, i = 0, x, y;
  23204. var imageData = new Uint8Array(width * height * 4);
  23205. for (y = y_start; y !== y_end; y += y_step) {
  23206. for (x = x_start; x !== x_end; x += x_step, i++) {
  23207. color = image[i];
  23208. imageData[(x + width * y) * 4 + 0] = color;
  23209. imageData[(x + width * y) * 4 + 1] = color;
  23210. imageData[(x + width * y) * 4 + 2] = color;
  23211. imageData[(x + width * y) * 4 + 3] = 255;
  23212. }
  23213. }
  23214. return imageData;
  23215. };
  23216. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23217. var image = pixel_data;
  23218. var width = header.width, height = header.height;
  23219. var i = 0, x, y;
  23220. var imageData = new Uint8Array(width * height * 4);
  23221. for (y = y_start; y !== y_end; y += y_step) {
  23222. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23223. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23224. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23225. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23226. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23227. }
  23228. }
  23229. return imageData;
  23230. };
  23231. TGATools._TYPE_NO_DATA = 0;
  23232. TGATools._TYPE_INDEXED = 1;
  23233. TGATools._TYPE_RGB = 2;
  23234. TGATools._TYPE_GREY = 3;
  23235. TGATools._TYPE_RLE_INDEXED = 9;
  23236. TGATools._TYPE_RLE_RGB = 10;
  23237. TGATools._TYPE_RLE_GREY = 11;
  23238. TGATools._ORIGIN_MASK = 0x30;
  23239. TGATools._ORIGIN_SHIFT = 0x04;
  23240. TGATools._ORIGIN_BL = 0x00;
  23241. TGATools._ORIGIN_BR = 0x01;
  23242. TGATools._ORIGIN_UL = 0x02;
  23243. TGATools._ORIGIN_UR = 0x03;
  23244. return TGATools;
  23245. })();
  23246. Internals.TGATools = TGATools;
  23247. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23248. })(BABYLON || (BABYLON = {}));
  23249. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23250. (function (BABYLON) {
  23251. var Internals;
  23252. (function (Internals) {
  23253. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23254. // All values and structures referenced from:
  23255. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23256. var DDS_MAGIC = 0x20534444;
  23257. 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;
  23258. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23259. 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;
  23260. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23261. function FourCCToInt32(value) {
  23262. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23263. }
  23264. function Int32ToFourCC(value) {
  23265. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23266. }
  23267. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23268. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23269. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23270. var headerLengthInt = 31; // The header length in 32 bit ints
  23271. // Offsets into the header array
  23272. var off_magic = 0;
  23273. var off_size = 1;
  23274. var off_flags = 2;
  23275. var off_height = 3;
  23276. var off_width = 4;
  23277. var off_mipmapCount = 7;
  23278. var off_pfFlags = 20;
  23279. var off_pfFourCC = 21;
  23280. var off_RGBbpp = 22;
  23281. var off_RMask = 23;
  23282. var off_GMask = 24;
  23283. var off_BMask = 25;
  23284. var off_AMask = 26;
  23285. var off_caps1 = 27;
  23286. var off_caps2 = 28;
  23287. ;
  23288. var DDSTools = (function () {
  23289. function DDSTools() {
  23290. }
  23291. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23292. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23293. var mipmapCount = 1;
  23294. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23295. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23296. }
  23297. return {
  23298. width: header[off_width],
  23299. height: header[off_height],
  23300. mipmapCount: mipmapCount,
  23301. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23302. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23303. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23304. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23305. };
  23306. };
  23307. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23308. var byteArray = new Uint8Array(dataLength);
  23309. var srcData = new Uint8Array(arrayBuffer);
  23310. var index = 0;
  23311. for (var y = height - 1; y >= 0; y--) {
  23312. for (var x = 0; x < width; x++) {
  23313. var srcPos = dataOffset + (x + y * width) * 4;
  23314. byteArray[index + 2] = srcData[srcPos];
  23315. byteArray[index + 1] = srcData[srcPos + 1];
  23316. byteArray[index] = srcData[srcPos + 2];
  23317. byteArray[index + 3] = srcData[srcPos + 3];
  23318. index += 4;
  23319. }
  23320. }
  23321. return byteArray;
  23322. };
  23323. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23324. var byteArray = new Uint8Array(dataLength);
  23325. var srcData = new Uint8Array(arrayBuffer);
  23326. var index = 0;
  23327. for (var y = height - 1; y >= 0; y--) {
  23328. for (var x = 0; x < width; x++) {
  23329. var srcPos = dataOffset + (x + y * width) * 3;
  23330. byteArray[index + 2] = srcData[srcPos];
  23331. byteArray[index + 1] = srcData[srcPos + 1];
  23332. byteArray[index] = srcData[srcPos + 2];
  23333. index += 3;
  23334. }
  23335. }
  23336. return byteArray;
  23337. };
  23338. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23339. var byteArray = new Uint8Array(dataLength);
  23340. var srcData = new Uint8Array(arrayBuffer);
  23341. var index = 0;
  23342. for (var y = height - 1; y >= 0; y--) {
  23343. for (var x = 0; x < width; x++) {
  23344. var srcPos = dataOffset + (x + y * width);
  23345. byteArray[index] = srcData[srcPos];
  23346. index++;
  23347. }
  23348. }
  23349. return byteArray;
  23350. };
  23351. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23352. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23353. if (header[off_magic] != DDS_MAGIC) {
  23354. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23355. return;
  23356. }
  23357. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23358. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23359. return;
  23360. }
  23361. if (info.isFourCC) {
  23362. fourCC = header[off_pfFourCC];
  23363. switch (fourCC) {
  23364. case FOURCC_DXT1:
  23365. blockBytes = 8;
  23366. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23367. break;
  23368. case FOURCC_DXT3:
  23369. blockBytes = 16;
  23370. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23371. break;
  23372. case FOURCC_DXT5:
  23373. blockBytes = 16;
  23374. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23375. break;
  23376. default:
  23377. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23378. return;
  23379. }
  23380. }
  23381. mipmapCount = 1;
  23382. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23383. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23384. }
  23385. var bpp = header[off_RGBbpp];
  23386. for (var face = 0; face < faces; face++) {
  23387. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23388. width = header[off_width];
  23389. height = header[off_height];
  23390. dataOffset = header[off_size] + 4;
  23391. for (i = 0; i < mipmapCount; ++i) {
  23392. if (info.isRGB) {
  23393. if (bpp == 24) {
  23394. dataLength = width * height * 3;
  23395. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23396. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23397. }
  23398. else {
  23399. dataLength = width * height * 4;
  23400. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23401. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23402. }
  23403. }
  23404. else if (info.isLuminance) {
  23405. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23406. var unpaddedRowSize = width;
  23407. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23408. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23409. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23410. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23411. }
  23412. else {
  23413. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23414. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23415. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23416. }
  23417. dataOffset += dataLength;
  23418. width *= 0.5;
  23419. height *= 0.5;
  23420. width = Math.max(1.0, width);
  23421. height = Math.max(1.0, height);
  23422. }
  23423. }
  23424. };
  23425. return DDSTools;
  23426. })();
  23427. Internals.DDSTools = DDSTools;
  23428. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23429. })(BABYLON || (BABYLON = {}));
  23430. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23431. (function (BABYLON) {
  23432. var SmartArray = (function () {
  23433. function SmartArray(capacity) {
  23434. this.length = 0;
  23435. this._duplicateId = 0;
  23436. this.data = new Array(capacity);
  23437. this._id = SmartArray._GlobalId++;
  23438. }
  23439. SmartArray.prototype.push = function (value) {
  23440. this.data[this.length++] = value;
  23441. if (this.length > this.data.length) {
  23442. this.data.length *= 2;
  23443. }
  23444. if (!value.__smartArrayFlags) {
  23445. value.__smartArrayFlags = {};
  23446. }
  23447. value.__smartArrayFlags[this._id] = this._duplicateId;
  23448. };
  23449. SmartArray.prototype.pushNoDuplicate = function (value) {
  23450. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23451. return;
  23452. }
  23453. this.push(value);
  23454. };
  23455. SmartArray.prototype.sort = function (compareFn) {
  23456. this.data.sort(compareFn);
  23457. };
  23458. SmartArray.prototype.reset = function () {
  23459. this.length = 0;
  23460. this._duplicateId++;
  23461. };
  23462. SmartArray.prototype.concat = function (array) {
  23463. if (array.length === 0) {
  23464. return;
  23465. }
  23466. if (this.length + array.length > this.data.length) {
  23467. this.data.length = (this.length + array.length) * 2;
  23468. }
  23469. for (var index = 0; index < array.length; index++) {
  23470. this.data[this.length++] = (array.data || array)[index];
  23471. }
  23472. };
  23473. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23474. if (array.length === 0) {
  23475. return;
  23476. }
  23477. if (this.length + array.length > this.data.length) {
  23478. this.data.length = (this.length + array.length) * 2;
  23479. }
  23480. for (var index = 0; index < array.length; index++) {
  23481. var item = (array.data || array)[index];
  23482. this.pushNoDuplicate(item);
  23483. }
  23484. };
  23485. SmartArray.prototype.indexOf = function (value) {
  23486. var position = this.data.indexOf(value);
  23487. if (position >= this.length) {
  23488. return -1;
  23489. }
  23490. return position;
  23491. };
  23492. // Statics
  23493. SmartArray._GlobalId = 0;
  23494. return SmartArray;
  23495. })();
  23496. BABYLON.SmartArray = SmartArray;
  23497. })(BABYLON || (BABYLON = {}));
  23498. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23499. (function (BABYLON) {
  23500. var CannonJSPlugin = (function () {
  23501. function CannonJSPlugin() {
  23502. this._registeredMeshes = [];
  23503. this._physicsMaterials = [];
  23504. this.updateBodyPosition = function (mesh) {
  23505. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23506. var registeredMesh = this._registeredMeshes[index];
  23507. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23508. var body = registeredMesh.body;
  23509. var center = mesh.getBoundingInfo().boundingBox.center;
  23510. body.position.set(center.x, center.z, center.y);
  23511. body.quaternion.x = mesh.rotationQuaternion.x;
  23512. body.quaternion.z = mesh.rotationQuaternion.y;
  23513. body.quaternion.y = mesh.rotationQuaternion.z;
  23514. body.quaternion.w = -mesh.rotationQuaternion.w;
  23515. return;
  23516. }
  23517. }
  23518. };
  23519. }
  23520. CannonJSPlugin.prototype.initialize = function (iterations) {
  23521. if (iterations === void 0) { iterations = 10; }
  23522. this._world = new CANNON.World();
  23523. this._world.broadphase = new CANNON.NaiveBroadphase();
  23524. this._world.solver.iterations = iterations;
  23525. };
  23526. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23527. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23528. };
  23529. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23530. this._world.step(delta);
  23531. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23532. var registeredMesh = this._registeredMeshes[index];
  23533. if (registeredMesh.isChild) {
  23534. continue;
  23535. }
  23536. // Body position
  23537. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23538. var deltaPos = registeredMesh.delta;
  23539. if (deltaPos) {
  23540. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23541. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23542. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23543. }
  23544. else {
  23545. registeredMesh.mesh.position.x = bodyX;
  23546. registeredMesh.mesh.position.y = bodyZ;
  23547. registeredMesh.mesh.position.z = bodyY;
  23548. }
  23549. if (!registeredMesh.mesh.rotationQuaternion) {
  23550. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23551. }
  23552. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23553. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23554. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23555. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23556. }
  23557. };
  23558. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23559. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23560. };
  23561. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23562. this.unregisterMesh(mesh);
  23563. mesh.computeWorldMatrix(true);
  23564. switch (impostor) {
  23565. case BABYLON.PhysicsEngine.SphereImpostor:
  23566. var bbox = mesh.getBoundingInfo().boundingBox;
  23567. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23568. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23569. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23570. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23571. case BABYLON.PhysicsEngine.BoxImpostor:
  23572. bbox = mesh.getBoundingInfo().boundingBox;
  23573. var min = bbox.minimumWorld;
  23574. var max = bbox.maximumWorld;
  23575. var box = max.subtract(min).scale(0.5);
  23576. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23577. case BABYLON.PhysicsEngine.PlaneImpostor:
  23578. return this._createPlane(mesh, options);
  23579. case BABYLON.PhysicsEngine.MeshImpostor:
  23580. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23581. var rawFaces = mesh.getIndices();
  23582. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23583. }
  23584. return null;
  23585. };
  23586. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23587. var shape = new CANNON.Sphere(radius);
  23588. if (!options) {
  23589. return shape;
  23590. }
  23591. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23592. };
  23593. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23594. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23595. if (!options) {
  23596. return shape;
  23597. }
  23598. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23599. };
  23600. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23601. var shape = new CANNON.Plane();
  23602. if (!options) {
  23603. return shape;
  23604. }
  23605. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23606. };
  23607. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23608. var verts = [], faces = [];
  23609. mesh.computeWorldMatrix(true);
  23610. for (var i = 0; i < rawVerts.length; i += 3) {
  23611. var transformed = BABYLON.Vector3.Zero();
  23612. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23613. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23614. }
  23615. for (var j = 0; j < rawFaces.length; j += 3) {
  23616. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23617. }
  23618. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23619. if (!options) {
  23620. return shape;
  23621. }
  23622. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23623. };
  23624. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23625. var index;
  23626. var mat;
  23627. for (index = 0; index < this._physicsMaterials.length; index++) {
  23628. mat = this._physicsMaterials[index];
  23629. if (mat.friction === friction && mat.restitution === restitution) {
  23630. return mat;
  23631. }
  23632. }
  23633. var currentMat = new CANNON.Material();
  23634. currentMat.friction = friction;
  23635. currentMat.restitution = restitution;
  23636. this._physicsMaterials.push(currentMat);
  23637. for (index = 0; index < this._physicsMaterials.length; index++) {
  23638. mat = this._physicsMaterials[index];
  23639. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23640. contactMaterial.contactEquationStiffness = 1e10;
  23641. contactMaterial.contactEquationRegularizationTime = 10;
  23642. this._world.addContactMaterial(contactMaterial);
  23643. }
  23644. return currentMat;
  23645. };
  23646. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23647. var initialRotation = null;
  23648. if (mesh.rotationQuaternion) {
  23649. initialRotation = mesh.rotationQuaternion.clone();
  23650. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23651. }
  23652. // The delta between the mesh position and the mesh bounding box center
  23653. var bbox = mesh.getBoundingInfo().boundingBox;
  23654. var deltaPosition = mesh.position.subtract(bbox.center);
  23655. var material = this._addMaterial(friction, restitution);
  23656. var body = new CANNON.RigidBody(mass, shape, material);
  23657. if (initialRotation) {
  23658. body.quaternion.x = initialRotation.x;
  23659. body.quaternion.z = initialRotation.y;
  23660. body.quaternion.y = initialRotation.z;
  23661. body.quaternion.w = -initialRotation.w;
  23662. }
  23663. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23664. this._world.add(body);
  23665. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23666. return body;
  23667. };
  23668. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23669. var compoundShape = new CANNON.Compound();
  23670. for (var index = 0; index < parts.length; index++) {
  23671. var mesh = parts[index].mesh;
  23672. var shape = this.registerMesh(mesh, parts[index].impostor);
  23673. if (index == 0) {
  23674. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23675. }
  23676. else {
  23677. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23678. }
  23679. }
  23680. var initialMesh = parts[0].mesh;
  23681. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23682. body.parts = parts;
  23683. return body;
  23684. };
  23685. CannonJSPlugin.prototype._unbindBody = function (body) {
  23686. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23687. var registeredMesh = this._registeredMeshes[index];
  23688. if (registeredMesh.body === body) {
  23689. registeredMesh.body = null;
  23690. registeredMesh.delta = 0;
  23691. }
  23692. }
  23693. };
  23694. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23695. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23696. var registeredMesh = this._registeredMeshes[index];
  23697. if (registeredMesh.mesh === mesh) {
  23698. // Remove body
  23699. if (registeredMesh.body) {
  23700. this._world.remove(registeredMesh.body);
  23701. this._unbindBody(registeredMesh.body);
  23702. }
  23703. this._registeredMeshes.splice(index, 1);
  23704. return;
  23705. }
  23706. }
  23707. };
  23708. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23709. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23710. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23711. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23712. var registeredMesh = this._registeredMeshes[index];
  23713. if (registeredMesh.mesh === mesh) {
  23714. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23715. return;
  23716. }
  23717. }
  23718. };
  23719. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23720. var body1 = null, body2 = null;
  23721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23722. var registeredMesh = this._registeredMeshes[index];
  23723. if (registeredMesh.mesh === mesh1) {
  23724. body1 = registeredMesh.body;
  23725. }
  23726. else if (registeredMesh.mesh === mesh2) {
  23727. body2 = registeredMesh.body;
  23728. }
  23729. }
  23730. if (!body1 || !body2) {
  23731. return false;
  23732. }
  23733. 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));
  23734. this._world.addConstraint(constraint);
  23735. return true;
  23736. };
  23737. CannonJSPlugin.prototype.dispose = function () {
  23738. while (this._registeredMeshes.length) {
  23739. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23740. }
  23741. };
  23742. CannonJSPlugin.prototype.isSupported = function () {
  23743. return window.CANNON !== undefined;
  23744. };
  23745. return CannonJSPlugin;
  23746. })();
  23747. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23748. })(BABYLON || (BABYLON = {}));
  23749. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23750. var BABYLON;
  23751. (function (BABYLON) {
  23752. var Condition = (function () {
  23753. function Condition(actionManager) {
  23754. this._actionManager = actionManager;
  23755. }
  23756. Condition.prototype.isValid = function () {
  23757. return true;
  23758. };
  23759. Condition.prototype._getProperty = function (propertyPath) {
  23760. return this._actionManager._getProperty(propertyPath);
  23761. };
  23762. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23763. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23764. };
  23765. return Condition;
  23766. })();
  23767. BABYLON.Condition = Condition;
  23768. var ValueCondition = (function (_super) {
  23769. __extends(ValueCondition, _super);
  23770. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23771. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23772. _super.call(this, actionManager);
  23773. this.propertyPath = propertyPath;
  23774. this.value = value;
  23775. this.operator = operator;
  23776. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23777. this._property = this._getProperty(this.propertyPath);
  23778. }
  23779. Object.defineProperty(ValueCondition, "IsEqual", {
  23780. get: function () {
  23781. return ValueCondition._IsEqual;
  23782. },
  23783. enumerable: true,
  23784. configurable: true
  23785. });
  23786. Object.defineProperty(ValueCondition, "IsDifferent", {
  23787. get: function () {
  23788. return ValueCondition._IsDifferent;
  23789. },
  23790. enumerable: true,
  23791. configurable: true
  23792. });
  23793. Object.defineProperty(ValueCondition, "IsGreater", {
  23794. get: function () {
  23795. return ValueCondition._IsGreater;
  23796. },
  23797. enumerable: true,
  23798. configurable: true
  23799. });
  23800. Object.defineProperty(ValueCondition, "IsLesser", {
  23801. get: function () {
  23802. return ValueCondition._IsLesser;
  23803. },
  23804. enumerable: true,
  23805. configurable: true
  23806. });
  23807. // Methods
  23808. ValueCondition.prototype.isValid = function () {
  23809. switch (this.operator) {
  23810. case ValueCondition.IsGreater:
  23811. return this._target[this._property] > this.value;
  23812. case ValueCondition.IsLesser:
  23813. return this._target[this._property] < this.value;
  23814. case ValueCondition.IsEqual:
  23815. case ValueCondition.IsDifferent:
  23816. var check;
  23817. if (this.value.equals) {
  23818. check = this.value.equals(this._target[this._property]);
  23819. }
  23820. else {
  23821. check = this.value === this._target[this._property];
  23822. }
  23823. return this.operator === ValueCondition.IsEqual ? check : !check;
  23824. }
  23825. return false;
  23826. };
  23827. // Statics
  23828. ValueCondition._IsEqual = 0;
  23829. ValueCondition._IsDifferent = 1;
  23830. ValueCondition._IsGreater = 2;
  23831. ValueCondition._IsLesser = 3;
  23832. return ValueCondition;
  23833. })(Condition);
  23834. BABYLON.ValueCondition = ValueCondition;
  23835. var PredicateCondition = (function (_super) {
  23836. __extends(PredicateCondition, _super);
  23837. function PredicateCondition(actionManager, predicate) {
  23838. _super.call(this, actionManager);
  23839. this.predicate = predicate;
  23840. }
  23841. PredicateCondition.prototype.isValid = function () {
  23842. return this.predicate();
  23843. };
  23844. return PredicateCondition;
  23845. })(Condition);
  23846. BABYLON.PredicateCondition = PredicateCondition;
  23847. var StateCondition = (function (_super) {
  23848. __extends(StateCondition, _super);
  23849. function StateCondition(actionManager, target, value) {
  23850. _super.call(this, actionManager);
  23851. this.value = value;
  23852. this._target = target;
  23853. }
  23854. // Methods
  23855. StateCondition.prototype.isValid = function () {
  23856. return this._target.state === this.value;
  23857. };
  23858. return StateCondition;
  23859. })(Condition);
  23860. BABYLON.StateCondition = StateCondition;
  23861. })(BABYLON || (BABYLON = {}));
  23862. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23863. (function (BABYLON) {
  23864. var Action = (function () {
  23865. function Action(triggerOptions, condition) {
  23866. this.triggerOptions = triggerOptions;
  23867. if (triggerOptions.parameter) {
  23868. this.trigger = triggerOptions.trigger;
  23869. this._triggerParameter = triggerOptions.parameter;
  23870. }
  23871. else {
  23872. this.trigger = triggerOptions;
  23873. }
  23874. this._nextActiveAction = this;
  23875. this._condition = condition;
  23876. }
  23877. // Methods
  23878. Action.prototype._prepare = function () {
  23879. };
  23880. Action.prototype.getTriggerParameter = function () {
  23881. return this._triggerParameter;
  23882. };
  23883. Action.prototype._executeCurrent = function (evt) {
  23884. if (this._nextActiveAction._condition) {
  23885. var condition = this._nextActiveAction._condition;
  23886. var currentRenderId = this._actionManager.getScene().getRenderId();
  23887. // We cache the current evaluation for the current frame
  23888. if (condition._evaluationId === currentRenderId) {
  23889. if (!condition._currentResult) {
  23890. return;
  23891. }
  23892. }
  23893. else {
  23894. condition._evaluationId = currentRenderId;
  23895. if (!condition.isValid()) {
  23896. condition._currentResult = false;
  23897. return;
  23898. }
  23899. condition._currentResult = true;
  23900. }
  23901. }
  23902. this._nextActiveAction.execute(evt);
  23903. if (this._nextActiveAction._child) {
  23904. if (!this._nextActiveAction._child._actionManager) {
  23905. this._nextActiveAction._child._actionManager = this._actionManager;
  23906. }
  23907. this._nextActiveAction = this._nextActiveAction._child;
  23908. }
  23909. else {
  23910. this._nextActiveAction = this;
  23911. }
  23912. };
  23913. Action.prototype.execute = function (evt) {
  23914. };
  23915. Action.prototype.then = function (action) {
  23916. this._child = action;
  23917. action._actionManager = this._actionManager;
  23918. action._prepare();
  23919. return action;
  23920. };
  23921. Action.prototype._getProperty = function (propertyPath) {
  23922. return this._actionManager._getProperty(propertyPath);
  23923. };
  23924. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23925. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23926. };
  23927. return Action;
  23928. })();
  23929. BABYLON.Action = Action;
  23930. })(BABYLON || (BABYLON = {}));
  23931. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23932. (function (BABYLON) {
  23933. /**
  23934. * ActionEvent is the event beint sent when an action is triggered.
  23935. */
  23936. var ActionEvent = (function () {
  23937. /**
  23938. * @constructor
  23939. * @param source The mesh that triggered the action.
  23940. * @param pointerX the X mouse cursor position at the time of the event
  23941. * @param pointerY the Y mouse cursor position at the time of the event
  23942. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23943. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23944. */
  23945. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23946. this.source = source;
  23947. this.pointerX = pointerX;
  23948. this.pointerY = pointerY;
  23949. this.meshUnderPointer = meshUnderPointer;
  23950. this.sourceEvent = sourceEvent;
  23951. }
  23952. /**
  23953. * Helper function to auto-create an ActionEvent from a source mesh.
  23954. * @param source the source mesh that triggered the event
  23955. * @param evt {Event} The original (browser) event
  23956. */
  23957. ActionEvent.CreateNew = function (source, evt) {
  23958. var scene = source.getScene();
  23959. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23960. };
  23961. /**
  23962. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23963. * @param scene the scene where the event occurred
  23964. * @param evt {Event} The original (browser) event
  23965. */
  23966. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23967. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23968. };
  23969. return ActionEvent;
  23970. })();
  23971. BABYLON.ActionEvent = ActionEvent;
  23972. /**
  23973. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23974. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23975. */
  23976. var ActionManager = (function () {
  23977. function ActionManager(scene) {
  23978. // Members
  23979. this.actions = new Array();
  23980. this._scene = scene;
  23981. scene._actionManagers.push(this);
  23982. }
  23983. Object.defineProperty(ActionManager, "NothingTrigger", {
  23984. get: function () {
  23985. return ActionManager._NothingTrigger;
  23986. },
  23987. enumerable: true,
  23988. configurable: true
  23989. });
  23990. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23991. get: function () {
  23992. return ActionManager._OnPickTrigger;
  23993. },
  23994. enumerable: true,
  23995. configurable: true
  23996. });
  23997. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23998. get: function () {
  23999. return ActionManager._OnLeftPickTrigger;
  24000. },
  24001. enumerable: true,
  24002. configurable: true
  24003. });
  24004. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24005. get: function () {
  24006. return ActionManager._OnRightPickTrigger;
  24007. },
  24008. enumerable: true,
  24009. configurable: true
  24010. });
  24011. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24012. get: function () {
  24013. return ActionManager._OnCenterPickTrigger;
  24014. },
  24015. enumerable: true,
  24016. configurable: true
  24017. });
  24018. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24019. get: function () {
  24020. return ActionManager._OnPointerOverTrigger;
  24021. },
  24022. enumerable: true,
  24023. configurable: true
  24024. });
  24025. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24026. get: function () {
  24027. return ActionManager._OnPointerOutTrigger;
  24028. },
  24029. enumerable: true,
  24030. configurable: true
  24031. });
  24032. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24033. get: function () {
  24034. return ActionManager._OnEveryFrameTrigger;
  24035. },
  24036. enumerable: true,
  24037. configurable: true
  24038. });
  24039. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24040. get: function () {
  24041. return ActionManager._OnIntersectionEnterTrigger;
  24042. },
  24043. enumerable: true,
  24044. configurable: true
  24045. });
  24046. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24047. get: function () {
  24048. return ActionManager._OnIntersectionExitTrigger;
  24049. },
  24050. enumerable: true,
  24051. configurable: true
  24052. });
  24053. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24054. get: function () {
  24055. return ActionManager._OnKeyDownTrigger;
  24056. },
  24057. enumerable: true,
  24058. configurable: true
  24059. });
  24060. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24061. get: function () {
  24062. return ActionManager._OnKeyUpTrigger;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. // Methods
  24068. ActionManager.prototype.dispose = function () {
  24069. var index = this._scene._actionManagers.indexOf(this);
  24070. if (index > -1) {
  24071. this._scene._actionManagers.splice(index, 1);
  24072. }
  24073. };
  24074. ActionManager.prototype.getScene = function () {
  24075. return this._scene;
  24076. };
  24077. /**
  24078. * Does this action manager handles actions of any of the given triggers
  24079. * @param {number[]} triggers - the triggers to be tested
  24080. * @return {boolean} whether one (or more) of the triggers is handeled
  24081. */
  24082. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24083. for (var index = 0; index < this.actions.length; index++) {
  24084. var action = this.actions[index];
  24085. if (triggers.indexOf(action.trigger) > -1) {
  24086. return true;
  24087. }
  24088. }
  24089. return false;
  24090. };
  24091. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24092. /**
  24093. * Does this action manager has pointer triggers
  24094. * @return {boolean} whether or not it has pointer triggers
  24095. */
  24096. get: function () {
  24097. for (var index = 0; index < this.actions.length; index++) {
  24098. var action = this.actions[index];
  24099. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24100. return true;
  24101. }
  24102. }
  24103. return false;
  24104. },
  24105. enumerable: true,
  24106. configurable: true
  24107. });
  24108. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24109. /**
  24110. * Does this action manager has pick triggers
  24111. * @return {boolean} whether or not it has pick triggers
  24112. */
  24113. get: function () {
  24114. for (var index = 0; index < this.actions.length; index++) {
  24115. var action = this.actions[index];
  24116. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24117. return true;
  24118. }
  24119. }
  24120. return false;
  24121. },
  24122. enumerable: true,
  24123. configurable: true
  24124. });
  24125. /**
  24126. * Registers an action to this action manager
  24127. * @param {BABYLON.Action} action - the action to be registered
  24128. * @return {BABYLON.Action} the action amended (prepared) after registration
  24129. */
  24130. ActionManager.prototype.registerAction = function (action) {
  24131. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24132. if (this.getScene().actionManager !== this) {
  24133. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24134. return null;
  24135. }
  24136. }
  24137. this.actions.push(action);
  24138. action._actionManager = this;
  24139. action._prepare();
  24140. return action;
  24141. };
  24142. /**
  24143. * Process a specific trigger
  24144. * @param {number} trigger - the trigger to process
  24145. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24146. */
  24147. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24148. for (var index = 0; index < this.actions.length; index++) {
  24149. var action = this.actions[index];
  24150. if (action.trigger === trigger) {
  24151. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24152. var parameter = action.getTriggerParameter();
  24153. if (parameter) {
  24154. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24155. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24156. if (actualkey !== parameter.toLowerCase()) {
  24157. continue;
  24158. }
  24159. }
  24160. }
  24161. action._executeCurrent(evt);
  24162. }
  24163. }
  24164. };
  24165. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24166. var properties = propertyPath.split(".");
  24167. for (var index = 0; index < properties.length - 1; index++) {
  24168. target = target[properties[index]];
  24169. }
  24170. return target;
  24171. };
  24172. ActionManager.prototype._getProperty = function (propertyPath) {
  24173. var properties = propertyPath.split(".");
  24174. return properties[properties.length - 1];
  24175. };
  24176. // Statics
  24177. ActionManager._NothingTrigger = 0;
  24178. ActionManager._OnPickTrigger = 1;
  24179. ActionManager._OnLeftPickTrigger = 2;
  24180. ActionManager._OnRightPickTrigger = 3;
  24181. ActionManager._OnCenterPickTrigger = 4;
  24182. ActionManager._OnPointerOverTrigger = 5;
  24183. ActionManager._OnPointerOutTrigger = 6;
  24184. ActionManager._OnEveryFrameTrigger = 7;
  24185. ActionManager._OnIntersectionEnterTrigger = 8;
  24186. ActionManager._OnIntersectionExitTrigger = 9;
  24187. ActionManager._OnKeyDownTrigger = 10;
  24188. ActionManager._OnKeyUpTrigger = 11;
  24189. return ActionManager;
  24190. })();
  24191. BABYLON.ActionManager = ActionManager;
  24192. })(BABYLON || (BABYLON = {}));
  24193. //# sourceMappingURL=babylon.actionManager.js.map
  24194. var BABYLON;
  24195. (function (BABYLON) {
  24196. var InterpolateValueAction = (function (_super) {
  24197. __extends(InterpolateValueAction, _super);
  24198. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24199. if (duration === void 0) { duration = 1000; }
  24200. _super.call(this, triggerOptions, condition);
  24201. this.propertyPath = propertyPath;
  24202. this.value = value;
  24203. this.duration = duration;
  24204. this.stopOtherAnimations = stopOtherAnimations;
  24205. this._target = target;
  24206. }
  24207. InterpolateValueAction.prototype._prepare = function () {
  24208. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24209. this._property = this._getProperty(this.propertyPath);
  24210. };
  24211. InterpolateValueAction.prototype.execute = function () {
  24212. var scene = this._actionManager.getScene();
  24213. var keys = [
  24214. {
  24215. frame: 0,
  24216. value: this._target[this._property]
  24217. },
  24218. {
  24219. frame: 100,
  24220. value: this.value
  24221. }
  24222. ];
  24223. var dataType;
  24224. if (typeof this.value === "number") {
  24225. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24226. }
  24227. else if (this.value instanceof BABYLON.Color3) {
  24228. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24229. }
  24230. else if (this.value instanceof BABYLON.Vector3) {
  24231. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24232. }
  24233. else if (this.value instanceof BABYLON.Matrix) {
  24234. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24235. }
  24236. else if (this.value instanceof BABYLON.Quaternion) {
  24237. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24238. }
  24239. else {
  24240. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24241. return;
  24242. }
  24243. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24244. animation.setKeys(keys);
  24245. if (this.stopOtherAnimations) {
  24246. scene.stopAnimation(this._target);
  24247. }
  24248. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24249. };
  24250. return InterpolateValueAction;
  24251. })(BABYLON.Action);
  24252. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24253. })(BABYLON || (BABYLON = {}));
  24254. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24255. var BABYLON;
  24256. (function (BABYLON) {
  24257. var SwitchBooleanAction = (function (_super) {
  24258. __extends(SwitchBooleanAction, _super);
  24259. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24260. _super.call(this, triggerOptions, condition);
  24261. this.propertyPath = propertyPath;
  24262. this._target = target;
  24263. }
  24264. SwitchBooleanAction.prototype._prepare = function () {
  24265. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24266. this._property = this._getProperty(this.propertyPath);
  24267. };
  24268. SwitchBooleanAction.prototype.execute = function () {
  24269. this._target[this._property] = !this._target[this._property];
  24270. };
  24271. return SwitchBooleanAction;
  24272. })(BABYLON.Action);
  24273. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24274. var SetStateAction = (function (_super) {
  24275. __extends(SetStateAction, _super);
  24276. function SetStateAction(triggerOptions, target, value, condition) {
  24277. _super.call(this, triggerOptions, condition);
  24278. this.value = value;
  24279. this._target = target;
  24280. }
  24281. SetStateAction.prototype.execute = function () {
  24282. this._target.state = this.value;
  24283. };
  24284. return SetStateAction;
  24285. })(BABYLON.Action);
  24286. BABYLON.SetStateAction = SetStateAction;
  24287. var SetValueAction = (function (_super) {
  24288. __extends(SetValueAction, _super);
  24289. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24290. _super.call(this, triggerOptions, condition);
  24291. this.propertyPath = propertyPath;
  24292. this.value = value;
  24293. this._target = target;
  24294. }
  24295. SetValueAction.prototype._prepare = function () {
  24296. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24297. this._property = this._getProperty(this.propertyPath);
  24298. };
  24299. SetValueAction.prototype.execute = function () {
  24300. this._target[this._property] = this.value;
  24301. };
  24302. return SetValueAction;
  24303. })(BABYLON.Action);
  24304. BABYLON.SetValueAction = SetValueAction;
  24305. var IncrementValueAction = (function (_super) {
  24306. __extends(IncrementValueAction, _super);
  24307. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24308. _super.call(this, triggerOptions, condition);
  24309. this.propertyPath = propertyPath;
  24310. this.value = value;
  24311. this._target = target;
  24312. }
  24313. IncrementValueAction.prototype._prepare = function () {
  24314. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24315. this._property = this._getProperty(this.propertyPath);
  24316. if (typeof this._target[this._property] !== "number") {
  24317. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24318. }
  24319. };
  24320. IncrementValueAction.prototype.execute = function () {
  24321. this._target[this._property] += this.value;
  24322. };
  24323. return IncrementValueAction;
  24324. })(BABYLON.Action);
  24325. BABYLON.IncrementValueAction = IncrementValueAction;
  24326. var PlayAnimationAction = (function (_super) {
  24327. __extends(PlayAnimationAction, _super);
  24328. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24329. _super.call(this, triggerOptions, condition);
  24330. this.from = from;
  24331. this.to = to;
  24332. this.loop = loop;
  24333. this._target = target;
  24334. }
  24335. PlayAnimationAction.prototype._prepare = function () {
  24336. };
  24337. PlayAnimationAction.prototype.execute = function () {
  24338. var scene = this._actionManager.getScene();
  24339. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24340. };
  24341. return PlayAnimationAction;
  24342. })(BABYLON.Action);
  24343. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24344. var StopAnimationAction = (function (_super) {
  24345. __extends(StopAnimationAction, _super);
  24346. function StopAnimationAction(triggerOptions, target, condition) {
  24347. _super.call(this, triggerOptions, condition);
  24348. this._target = target;
  24349. }
  24350. StopAnimationAction.prototype._prepare = function () {
  24351. };
  24352. StopAnimationAction.prototype.execute = function () {
  24353. var scene = this._actionManager.getScene();
  24354. scene.stopAnimation(this._target);
  24355. };
  24356. return StopAnimationAction;
  24357. })(BABYLON.Action);
  24358. BABYLON.StopAnimationAction = StopAnimationAction;
  24359. var DoNothingAction = (function (_super) {
  24360. __extends(DoNothingAction, _super);
  24361. function DoNothingAction(triggerOptions, condition) {
  24362. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24363. _super.call(this, triggerOptions, condition);
  24364. }
  24365. DoNothingAction.prototype.execute = function () {
  24366. };
  24367. return DoNothingAction;
  24368. })(BABYLON.Action);
  24369. BABYLON.DoNothingAction = DoNothingAction;
  24370. var CombineAction = (function (_super) {
  24371. __extends(CombineAction, _super);
  24372. function CombineAction(triggerOptions, children, condition) {
  24373. _super.call(this, triggerOptions, condition);
  24374. this.children = children;
  24375. }
  24376. CombineAction.prototype._prepare = function () {
  24377. for (var index = 0; index < this.children.length; index++) {
  24378. this.children[index]._actionManager = this._actionManager;
  24379. this.children[index]._prepare();
  24380. }
  24381. };
  24382. CombineAction.prototype.execute = function (evt) {
  24383. for (var index = 0; index < this.children.length; index++) {
  24384. this.children[index].execute(evt);
  24385. }
  24386. };
  24387. return CombineAction;
  24388. })(BABYLON.Action);
  24389. BABYLON.CombineAction = CombineAction;
  24390. var ExecuteCodeAction = (function (_super) {
  24391. __extends(ExecuteCodeAction, _super);
  24392. function ExecuteCodeAction(triggerOptions, func, condition) {
  24393. _super.call(this, triggerOptions, condition);
  24394. this.func = func;
  24395. }
  24396. ExecuteCodeAction.prototype.execute = function (evt) {
  24397. this.func(evt);
  24398. };
  24399. return ExecuteCodeAction;
  24400. })(BABYLON.Action);
  24401. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24402. var SetParentAction = (function (_super) {
  24403. __extends(SetParentAction, _super);
  24404. function SetParentAction(triggerOptions, target, parent, condition) {
  24405. _super.call(this, triggerOptions, condition);
  24406. this._target = target;
  24407. this._parent = parent;
  24408. }
  24409. SetParentAction.prototype._prepare = function () {
  24410. };
  24411. SetParentAction.prototype.execute = function () {
  24412. if (this._target.parent === this._parent) {
  24413. return;
  24414. }
  24415. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24416. invertParentWorldMatrix.invert();
  24417. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24418. this._target.parent = this._parent;
  24419. };
  24420. return SetParentAction;
  24421. })(BABYLON.Action);
  24422. BABYLON.SetParentAction = SetParentAction;
  24423. var PlaySoundAction = (function (_super) {
  24424. __extends(PlaySoundAction, _super);
  24425. function PlaySoundAction(triggerOptions, sound, condition) {
  24426. _super.call(this, triggerOptions, condition);
  24427. this._sound = sound;
  24428. }
  24429. PlaySoundAction.prototype._prepare = function () {
  24430. };
  24431. PlaySoundAction.prototype.execute = function () {
  24432. if (this._sound !== undefined)
  24433. this._sound.play();
  24434. };
  24435. return PlaySoundAction;
  24436. })(BABYLON.Action);
  24437. BABYLON.PlaySoundAction = PlaySoundAction;
  24438. var StopSoundAction = (function (_super) {
  24439. __extends(StopSoundAction, _super);
  24440. function StopSoundAction(triggerOptions, sound, condition) {
  24441. _super.call(this, triggerOptions, condition);
  24442. this._sound = sound;
  24443. }
  24444. StopSoundAction.prototype._prepare = function () {
  24445. };
  24446. StopSoundAction.prototype.execute = function () {
  24447. if (this._sound !== undefined)
  24448. this._sound.stop();
  24449. };
  24450. return StopSoundAction;
  24451. })(BABYLON.Action);
  24452. BABYLON.StopSoundAction = StopSoundAction;
  24453. })(BABYLON || (BABYLON = {}));
  24454. //# sourceMappingURL=babylon.directActions.js.map
  24455. var BABYLON;
  24456. (function (BABYLON) {
  24457. var Geometry = (function () {
  24458. function Geometry(id, scene, vertexData, updatable, mesh) {
  24459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24460. this._totalVertices = 0;
  24461. this._indices = [];
  24462. this.id = id;
  24463. this._engine = scene.getEngine();
  24464. this._meshes = [];
  24465. this._scene = scene;
  24466. // vertexData
  24467. if (vertexData) {
  24468. this.setAllVerticesData(vertexData, updatable);
  24469. }
  24470. else {
  24471. this._totalVertices = 0;
  24472. this._indices = [];
  24473. }
  24474. // applyToMesh
  24475. if (mesh) {
  24476. this.applyToMesh(mesh);
  24477. mesh.computeWorldMatrix(true);
  24478. }
  24479. }
  24480. Geometry.prototype.getScene = function () {
  24481. return this._scene;
  24482. };
  24483. Geometry.prototype.getEngine = function () {
  24484. return this._engine;
  24485. };
  24486. Geometry.prototype.isReady = function () {
  24487. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24488. };
  24489. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24490. vertexData.applyToGeometry(this, updatable);
  24491. };
  24492. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24493. this._vertexBuffers = this._vertexBuffers || {};
  24494. if (this._vertexBuffers[kind]) {
  24495. this._vertexBuffers[kind].dispose();
  24496. }
  24497. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24498. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24499. stride = this._vertexBuffers[kind].getStrideSize();
  24500. this._totalVertices = data.length / stride;
  24501. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24502. var meshes = this._meshes;
  24503. var numOfMeshes = meshes.length;
  24504. for (var index = 0; index < numOfMeshes; index++) {
  24505. var mesh = meshes[index];
  24506. mesh._resetPointsArrayCache();
  24507. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24508. mesh._createGlobalSubMesh();
  24509. mesh.computeWorldMatrix(true);
  24510. }
  24511. }
  24512. };
  24513. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24514. var vertexBuffer = this.getVertexBuffer(kind);
  24515. if (!vertexBuffer) {
  24516. return;
  24517. }
  24518. vertexBuffer.updateDirectly(data, offset);
  24519. };
  24520. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24521. var vertexBuffer = this.getVertexBuffer(kind);
  24522. if (!vertexBuffer) {
  24523. return;
  24524. }
  24525. vertexBuffer.update(data);
  24526. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24527. var extend;
  24528. var stride = vertexBuffer.getStrideSize();
  24529. this._totalVertices = data.length / stride;
  24530. if (updateExtends) {
  24531. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24532. }
  24533. var meshes = this._meshes;
  24534. var numOfMeshes = meshes.length;
  24535. for (var index = 0; index < numOfMeshes; index++) {
  24536. var mesh = meshes[index];
  24537. mesh._resetPointsArrayCache();
  24538. if (updateExtends) {
  24539. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24540. }
  24541. }
  24542. }
  24543. };
  24544. Geometry.prototype.getTotalVertices = function () {
  24545. if (!this.isReady()) {
  24546. return 0;
  24547. }
  24548. return this._totalVertices;
  24549. };
  24550. Geometry.prototype.getVerticesData = function (kind) {
  24551. var vertexBuffer = this.getVertexBuffer(kind);
  24552. if (!vertexBuffer) {
  24553. return null;
  24554. }
  24555. return vertexBuffer.getData();
  24556. };
  24557. Geometry.prototype.getVertexBuffer = function (kind) {
  24558. if (!this.isReady()) {
  24559. return null;
  24560. }
  24561. return this._vertexBuffers[kind];
  24562. };
  24563. Geometry.prototype.getVertexBuffers = function () {
  24564. if (!this.isReady()) {
  24565. return null;
  24566. }
  24567. return this._vertexBuffers;
  24568. };
  24569. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24570. if (!this._vertexBuffers) {
  24571. if (this._delayInfo) {
  24572. return this._delayInfo.indexOf(kind) !== -1;
  24573. }
  24574. return false;
  24575. }
  24576. return this._vertexBuffers[kind] !== undefined;
  24577. };
  24578. Geometry.prototype.getVerticesDataKinds = function () {
  24579. var result = [];
  24580. if (!this._vertexBuffers && this._delayInfo) {
  24581. for (var kind in this._delayInfo) {
  24582. result.push(kind);
  24583. }
  24584. }
  24585. else {
  24586. for (kind in this._vertexBuffers) {
  24587. result.push(kind);
  24588. }
  24589. }
  24590. return result;
  24591. };
  24592. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24593. if (this._indexBuffer) {
  24594. this._engine._releaseBuffer(this._indexBuffer);
  24595. }
  24596. this._indices = indices;
  24597. if (this._meshes.length !== 0 && this._indices) {
  24598. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24599. }
  24600. if (totalVertices !== undefined) {
  24601. this._totalVertices = totalVertices;
  24602. }
  24603. var meshes = this._meshes;
  24604. var numOfMeshes = meshes.length;
  24605. for (var index = 0; index < numOfMeshes; index++) {
  24606. meshes[index]._createGlobalSubMesh();
  24607. }
  24608. };
  24609. Geometry.prototype.getTotalIndices = function () {
  24610. if (!this.isReady()) {
  24611. return 0;
  24612. }
  24613. return this._indices.length;
  24614. };
  24615. Geometry.prototype.getIndices = function () {
  24616. if (!this.isReady()) {
  24617. return null;
  24618. }
  24619. return this._indices;
  24620. };
  24621. Geometry.prototype.getIndexBuffer = function () {
  24622. if (!this.isReady()) {
  24623. return null;
  24624. }
  24625. return this._indexBuffer;
  24626. };
  24627. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24628. var meshes = this._meshes;
  24629. var index = meshes.indexOf(mesh);
  24630. if (index === -1) {
  24631. return;
  24632. }
  24633. for (var kind in this._vertexBuffers) {
  24634. this._vertexBuffers[kind].dispose();
  24635. }
  24636. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24637. this._indexBuffer = null;
  24638. }
  24639. meshes.splice(index, 1);
  24640. mesh._geometry = null;
  24641. if (meshes.length === 0 && shouldDispose) {
  24642. this.dispose();
  24643. }
  24644. };
  24645. Geometry.prototype.applyToMesh = function (mesh) {
  24646. if (mesh._geometry === this) {
  24647. return;
  24648. }
  24649. var previousGeometry = mesh._geometry;
  24650. if (previousGeometry) {
  24651. previousGeometry.releaseForMesh(mesh);
  24652. }
  24653. var meshes = this._meshes;
  24654. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24655. mesh._geometry = this;
  24656. this._scene.pushGeometry(this);
  24657. meshes.push(mesh);
  24658. if (this.isReady()) {
  24659. this._applyToMesh(mesh);
  24660. }
  24661. else {
  24662. mesh._boundingInfo = this._boundingInfo;
  24663. }
  24664. };
  24665. Geometry.prototype._applyToMesh = function (mesh) {
  24666. var numOfMeshes = this._meshes.length;
  24667. for (var kind in this._vertexBuffers) {
  24668. if (numOfMeshes === 1) {
  24669. this._vertexBuffers[kind].create();
  24670. }
  24671. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24672. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24673. mesh._resetPointsArrayCache();
  24674. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24675. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24676. mesh._createGlobalSubMesh();
  24677. //bounding info was just created again, world matrix should be applied again.
  24678. mesh._updateBoundingInfo();
  24679. }
  24680. }
  24681. // indexBuffer
  24682. if (numOfMeshes === 1 && this._indices) {
  24683. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24684. }
  24685. if (this._indexBuffer) {
  24686. this._indexBuffer.references = numOfMeshes;
  24687. }
  24688. };
  24689. Geometry.prototype.load = function (scene, onLoaded) {
  24690. var _this = this;
  24691. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24692. return;
  24693. }
  24694. if (this.isReady()) {
  24695. if (onLoaded) {
  24696. onLoaded();
  24697. }
  24698. return;
  24699. }
  24700. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24701. scene._addPendingData(this);
  24702. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24703. _this._delayLoadingFunction(JSON.parse(data), _this);
  24704. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24705. _this._delayInfo = [];
  24706. scene._removePendingData(_this);
  24707. var meshes = _this._meshes;
  24708. var numOfMeshes = meshes.length;
  24709. for (var index = 0; index < numOfMeshes; index++) {
  24710. _this._applyToMesh(meshes[index]);
  24711. }
  24712. if (onLoaded) {
  24713. onLoaded();
  24714. }
  24715. }, function () {
  24716. }, scene.database);
  24717. };
  24718. Geometry.prototype.dispose = function () {
  24719. var meshes = this._meshes;
  24720. var numOfMeshes = meshes.length;
  24721. var index;
  24722. for (index = 0; index < numOfMeshes; index++) {
  24723. this.releaseForMesh(meshes[index]);
  24724. }
  24725. this._meshes = [];
  24726. for (var kind in this._vertexBuffers) {
  24727. this._vertexBuffers[kind].dispose();
  24728. }
  24729. this._vertexBuffers = [];
  24730. this._totalVertices = 0;
  24731. if (this._indexBuffer) {
  24732. this._engine._releaseBuffer(this._indexBuffer);
  24733. }
  24734. this._indexBuffer = null;
  24735. this._indices = [];
  24736. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24737. this.delayLoadingFile = null;
  24738. this._delayLoadingFunction = null;
  24739. this._delayInfo = [];
  24740. this._boundingInfo = null; // todo: .dispose()
  24741. var geometries = this._scene.getGeometries();
  24742. index = geometries.indexOf(this);
  24743. if (index > -1) {
  24744. geometries.splice(index, 1);
  24745. }
  24746. };
  24747. Geometry.prototype.copy = function (id) {
  24748. var vertexData = new BABYLON.VertexData();
  24749. vertexData.indices = [];
  24750. var indices = this.getIndices();
  24751. for (var index = 0; index < indices.length; index++) {
  24752. vertexData.indices.push(indices[index]);
  24753. }
  24754. var updatable = false;
  24755. var stopChecking = false;
  24756. for (var kind in this._vertexBuffers) {
  24757. vertexData.set(this.getVerticesData(kind), kind);
  24758. if (!stopChecking) {
  24759. updatable = this.getVertexBuffer(kind).isUpdatable();
  24760. stopChecking = !updatable;
  24761. }
  24762. }
  24763. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24764. geometry.delayLoadState = this.delayLoadState;
  24765. geometry.delayLoadingFile = this.delayLoadingFile;
  24766. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24767. for (kind in this._delayInfo) {
  24768. geometry._delayInfo = geometry._delayInfo || [];
  24769. geometry._delayInfo.push(kind);
  24770. }
  24771. // Bounding info
  24772. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24773. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24774. return geometry;
  24775. };
  24776. // Statics
  24777. Geometry.ExtractFromMesh = function (mesh, id) {
  24778. var geometry = mesh._geometry;
  24779. if (!geometry) {
  24780. return null;
  24781. }
  24782. return geometry.copy(id);
  24783. };
  24784. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24785. // be aware Math.random() could cause collisions
  24786. Geometry.RandomId = function () {
  24787. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24788. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24789. return v.toString(16);
  24790. });
  24791. };
  24792. return Geometry;
  24793. })();
  24794. BABYLON.Geometry = Geometry;
  24795. /////// Primitives //////////////////////////////////////////////
  24796. var Geometry;
  24797. (function (Geometry) {
  24798. var Primitives;
  24799. (function (Primitives) {
  24800. /// Abstract class
  24801. var _Primitive = (function (_super) {
  24802. __extends(_Primitive, _super);
  24803. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24804. this._beingRegenerated = true;
  24805. this._canBeRegenerated = canBeRegenerated;
  24806. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24807. this._beingRegenerated = false;
  24808. }
  24809. _Primitive.prototype.canBeRegenerated = function () {
  24810. return this._canBeRegenerated;
  24811. };
  24812. _Primitive.prototype.regenerate = function () {
  24813. if (!this._canBeRegenerated) {
  24814. return;
  24815. }
  24816. this._beingRegenerated = true;
  24817. this.setAllVerticesData(this._regenerateVertexData(), false);
  24818. this._beingRegenerated = false;
  24819. };
  24820. _Primitive.prototype.asNewGeometry = function (id) {
  24821. return _super.prototype.copy.call(this, id);
  24822. };
  24823. // overrides
  24824. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24825. if (!this._beingRegenerated) {
  24826. return;
  24827. }
  24828. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24829. };
  24830. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24831. if (!this._beingRegenerated) {
  24832. return;
  24833. }
  24834. _super.prototype.setVerticesData.call(this, kind, data, false);
  24835. };
  24836. // to override
  24837. // protected
  24838. _Primitive.prototype._regenerateVertexData = function () {
  24839. throw new Error("Abstract method");
  24840. };
  24841. _Primitive.prototype.copy = function (id) {
  24842. throw new Error("Must be overriden in sub-classes.");
  24843. };
  24844. return _Primitive;
  24845. })(Geometry);
  24846. Primitives._Primitive = _Primitive;
  24847. var Ribbon = (function (_super) {
  24848. __extends(Ribbon, _super);
  24849. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24850. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24851. this.pathArray = pathArray;
  24852. this.closeArray = closeArray;
  24853. this.closePath = closePath;
  24854. this.offset = offset;
  24855. this.side = side;
  24856. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24857. }
  24858. Ribbon.prototype._regenerateVertexData = function () {
  24859. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24860. };
  24861. Ribbon.prototype.copy = function (id) {
  24862. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24863. };
  24864. return Ribbon;
  24865. })(_Primitive);
  24866. Primitives.Ribbon = Ribbon;
  24867. var Box = (function (_super) {
  24868. __extends(Box, _super);
  24869. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24870. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24871. this.size = size;
  24872. this.side = side;
  24873. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24874. }
  24875. Box.prototype._regenerateVertexData = function () {
  24876. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24877. };
  24878. Box.prototype.copy = function (id) {
  24879. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24880. };
  24881. return Box;
  24882. })(_Primitive);
  24883. Primitives.Box = Box;
  24884. var Sphere = (function (_super) {
  24885. __extends(Sphere, _super);
  24886. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24887. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24888. this.segments = segments;
  24889. this.diameter = diameter;
  24890. this.side = side;
  24891. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24892. }
  24893. Sphere.prototype._regenerateVertexData = function () {
  24894. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24895. };
  24896. Sphere.prototype.copy = function (id) {
  24897. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24898. };
  24899. return Sphere;
  24900. })(_Primitive);
  24901. Primitives.Sphere = Sphere;
  24902. var Cylinder = (function (_super) {
  24903. __extends(Cylinder, _super);
  24904. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24905. if (subdivisions === void 0) { subdivisions = 1; }
  24906. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24907. this.height = height;
  24908. this.diameterTop = diameterTop;
  24909. this.diameterBottom = diameterBottom;
  24910. this.tessellation = tessellation;
  24911. this.subdivisions = subdivisions;
  24912. this.side = side;
  24913. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24914. }
  24915. Cylinder.prototype._regenerateVertexData = function () {
  24916. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24917. };
  24918. Cylinder.prototype.copy = function (id) {
  24919. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24920. };
  24921. return Cylinder;
  24922. })(_Primitive);
  24923. Primitives.Cylinder = Cylinder;
  24924. var Torus = (function (_super) {
  24925. __extends(Torus, _super);
  24926. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24927. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24928. this.diameter = diameter;
  24929. this.thickness = thickness;
  24930. this.tessellation = tessellation;
  24931. this.side = side;
  24932. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24933. }
  24934. Torus.prototype._regenerateVertexData = function () {
  24935. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24936. };
  24937. Torus.prototype.copy = function (id) {
  24938. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24939. };
  24940. return Torus;
  24941. })(_Primitive);
  24942. Primitives.Torus = Torus;
  24943. var Ground = (function (_super) {
  24944. __extends(Ground, _super);
  24945. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24946. this.width = width;
  24947. this.height = height;
  24948. this.subdivisions = subdivisions;
  24949. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24950. }
  24951. Ground.prototype._regenerateVertexData = function () {
  24952. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24953. };
  24954. Ground.prototype.copy = function (id) {
  24955. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24956. };
  24957. return Ground;
  24958. })(_Primitive);
  24959. Primitives.Ground = Ground;
  24960. var TiledGround = (function (_super) {
  24961. __extends(TiledGround, _super);
  24962. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24963. this.xmin = xmin;
  24964. this.zmin = zmin;
  24965. this.xmax = xmax;
  24966. this.zmax = zmax;
  24967. this.subdivisions = subdivisions;
  24968. this.precision = precision;
  24969. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24970. }
  24971. TiledGround.prototype._regenerateVertexData = function () {
  24972. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24973. };
  24974. TiledGround.prototype.copy = function (id) {
  24975. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24976. };
  24977. return TiledGround;
  24978. })(_Primitive);
  24979. Primitives.TiledGround = TiledGround;
  24980. var Plane = (function (_super) {
  24981. __extends(Plane, _super);
  24982. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24983. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24984. this.size = size;
  24985. this.side = side;
  24986. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24987. }
  24988. Plane.prototype._regenerateVertexData = function () {
  24989. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24990. };
  24991. Plane.prototype.copy = function (id) {
  24992. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24993. };
  24994. return Plane;
  24995. })(_Primitive);
  24996. Primitives.Plane = Plane;
  24997. var TorusKnot = (function (_super) {
  24998. __extends(TorusKnot, _super);
  24999. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25000. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25001. this.radius = radius;
  25002. this.tube = tube;
  25003. this.radialSegments = radialSegments;
  25004. this.tubularSegments = tubularSegments;
  25005. this.p = p;
  25006. this.q = q;
  25007. this.side = side;
  25008. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25009. }
  25010. TorusKnot.prototype._regenerateVertexData = function () {
  25011. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25012. };
  25013. TorusKnot.prototype.copy = function (id) {
  25014. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25015. };
  25016. return TorusKnot;
  25017. })(_Primitive);
  25018. Primitives.TorusKnot = TorusKnot;
  25019. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25020. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25021. })(BABYLON || (BABYLON = {}));
  25022. //# sourceMappingURL=babylon.geometry.js.map
  25023. var BABYLON;
  25024. (function (BABYLON) {
  25025. var Gamepads = (function () {
  25026. function Gamepads(ongamedpadconnected) {
  25027. var _this = this;
  25028. this.babylonGamepads = [];
  25029. this.oneGamepadConnected = false;
  25030. this.isMonitoring = false;
  25031. this.gamepadEventSupported = 'GamepadEvent' in window;
  25032. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25033. 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=";
  25034. this._callbackGamepadConnected = ongamedpadconnected;
  25035. if (this.gamepadSupportAvailable) {
  25036. // Checking if the gamepad connected event is supported (like in Firefox)
  25037. if (this.gamepadEventSupported) {
  25038. window.addEventListener('gamepadconnected', function (evt) {
  25039. _this._onGamepadConnected(evt);
  25040. }, false);
  25041. window.addEventListener('gamepaddisconnected', function (evt) {
  25042. _this._onGamepadDisconnected(evt);
  25043. }, false);
  25044. }
  25045. else {
  25046. this._startMonitoringGamepads();
  25047. }
  25048. if (!this.oneGamepadConnected) {
  25049. this._insertGamepadDOMInstructions();
  25050. }
  25051. }
  25052. else {
  25053. this._insertGamepadDOMNotSupported();
  25054. }
  25055. }
  25056. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25057. Gamepads.gamepadDOMInfo = document.createElement("div");
  25058. var buttonAImage = document.createElement("img");
  25059. buttonAImage.src = this.buttonADataURL;
  25060. var spanMessage = document.createElement("span");
  25061. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25062. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25063. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25064. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25065. Gamepads.gamepadDOMInfo.style.width = "100%";
  25066. Gamepads.gamepadDOMInfo.style.height = "48px";
  25067. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25068. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25069. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25070. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25071. buttonAImage.style.position = "relative";
  25072. buttonAImage.style.bottom = "8px";
  25073. spanMessage.style.position = "relative";
  25074. spanMessage.style.fontSize = "32px";
  25075. spanMessage.style.bottom = "32px";
  25076. spanMessage.style.color = "green";
  25077. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25078. };
  25079. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25080. Gamepads.gamepadDOMInfo = document.createElement("div");
  25081. var spanMessage = document.createElement("span");
  25082. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25083. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25084. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25085. Gamepads.gamepadDOMInfo.style.width = "100%";
  25086. Gamepads.gamepadDOMInfo.style.height = "40px";
  25087. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25088. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25089. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25090. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25091. spanMessage.style.position = "relative";
  25092. spanMessage.style.fontSize = "32px";
  25093. spanMessage.style.color = "red";
  25094. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25095. };
  25096. Gamepads.prototype.dispose = function () {
  25097. if (Gamepads.gamepadDOMInfo) {
  25098. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25099. }
  25100. };
  25101. Gamepads.prototype._onGamepadConnected = function (evt) {
  25102. var newGamepad = this._addNewGamepad(evt.gamepad);
  25103. if (this._callbackGamepadConnected)
  25104. this._callbackGamepadConnected(newGamepad);
  25105. this._startMonitoringGamepads();
  25106. };
  25107. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25108. if (!this.oneGamepadConnected) {
  25109. this.oneGamepadConnected = true;
  25110. if (Gamepads.gamepadDOMInfo) {
  25111. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25112. Gamepads.gamepadDOMInfo = null;
  25113. }
  25114. }
  25115. var newGamepad;
  25116. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25117. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25118. }
  25119. else {
  25120. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25121. }
  25122. this.babylonGamepads.push(newGamepad);
  25123. return newGamepad;
  25124. };
  25125. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25126. for (var i in this.babylonGamepads) {
  25127. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25128. this.babylonGamepads.splice(i, 1);
  25129. break;
  25130. }
  25131. }
  25132. // If no gamepads are left, stop the polling loop.
  25133. if (this.babylonGamepads.length == 0) {
  25134. this._stopMonitoringGamepads();
  25135. }
  25136. };
  25137. Gamepads.prototype._startMonitoringGamepads = function () {
  25138. if (!this.isMonitoring) {
  25139. this.isMonitoring = true;
  25140. this._checkGamepadsStatus();
  25141. }
  25142. };
  25143. Gamepads.prototype._stopMonitoringGamepads = function () {
  25144. this.isMonitoring = false;
  25145. };
  25146. Gamepads.prototype._checkGamepadsStatus = function () {
  25147. var _this = this;
  25148. // updating gamepad objects
  25149. this._updateGamepadObjects();
  25150. for (var i in this.babylonGamepads) {
  25151. this.babylonGamepads[i].update();
  25152. }
  25153. if (this.isMonitoring) {
  25154. if (window.requestAnimationFrame) {
  25155. window.requestAnimationFrame(function () {
  25156. _this._checkGamepadsStatus();
  25157. });
  25158. }
  25159. else if (window.mozRequestAnimationFrame) {
  25160. window.mozRequestAnimationFrame(function () {
  25161. _this._checkGamepadsStatus();
  25162. });
  25163. }
  25164. else if (window.webkitRequestAnimationFrame) {
  25165. window.webkitRequestAnimationFrame(function () {
  25166. _this._checkGamepadsStatus();
  25167. });
  25168. }
  25169. }
  25170. };
  25171. // This function is called only on Chrome, which does not yet support
  25172. // connection/disconnection events, but requires you to monitor
  25173. // an array for changes.
  25174. Gamepads.prototype._updateGamepadObjects = function () {
  25175. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25176. for (var i = 0; i < gamepads.length; i++) {
  25177. if (gamepads[i]) {
  25178. if (!(gamepads[i].index in this.babylonGamepads)) {
  25179. var newGamepad = this._addNewGamepad(gamepads[i]);
  25180. if (this._callbackGamepadConnected) {
  25181. this._callbackGamepadConnected(newGamepad);
  25182. }
  25183. }
  25184. else {
  25185. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25186. }
  25187. }
  25188. }
  25189. };
  25190. return Gamepads;
  25191. })();
  25192. BABYLON.Gamepads = Gamepads;
  25193. var StickValues = (function () {
  25194. function StickValues(x, y) {
  25195. this.x = x;
  25196. this.y = y;
  25197. }
  25198. return StickValues;
  25199. })();
  25200. BABYLON.StickValues = StickValues;
  25201. var Gamepad = (function () {
  25202. function Gamepad(id, index, browserGamepad) {
  25203. this.id = id;
  25204. this.index = index;
  25205. this.browserGamepad = browserGamepad;
  25206. if (this.browserGamepad.axes.length >= 2) {
  25207. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25208. }
  25209. if (this.browserGamepad.axes.length >= 4) {
  25210. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25211. }
  25212. }
  25213. Gamepad.prototype.onleftstickchanged = function (callback) {
  25214. this._onleftstickchanged = callback;
  25215. };
  25216. Gamepad.prototype.onrightstickchanged = function (callback) {
  25217. this._onrightstickchanged = callback;
  25218. };
  25219. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25220. get: function () {
  25221. return this._leftStick;
  25222. },
  25223. set: function (newValues) {
  25224. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25225. this._onleftstickchanged(newValues);
  25226. }
  25227. this._leftStick = newValues;
  25228. },
  25229. enumerable: true,
  25230. configurable: true
  25231. });
  25232. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25233. get: function () {
  25234. return this._rightStick;
  25235. },
  25236. set: function (newValues) {
  25237. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25238. this._onrightstickchanged(newValues);
  25239. }
  25240. this._rightStick = newValues;
  25241. },
  25242. enumerable: true,
  25243. configurable: true
  25244. });
  25245. Gamepad.prototype.update = function () {
  25246. if (this._leftStick) {
  25247. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25248. }
  25249. if (this._rightStick) {
  25250. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25251. }
  25252. };
  25253. return Gamepad;
  25254. })();
  25255. BABYLON.Gamepad = Gamepad;
  25256. var GenericPad = (function (_super) {
  25257. __extends(GenericPad, _super);
  25258. function GenericPad(id, index, gamepad) {
  25259. _super.call(this, id, index, gamepad);
  25260. this.id = id;
  25261. this.index = index;
  25262. this.gamepad = gamepad;
  25263. this._buttons = new Array(gamepad.buttons.length);
  25264. }
  25265. GenericPad.prototype.onbuttondown = function (callback) {
  25266. this._onbuttondown = callback;
  25267. };
  25268. GenericPad.prototype.onbuttonup = function (callback) {
  25269. this._onbuttonup = callback;
  25270. };
  25271. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25272. if (newValue !== currentValue) {
  25273. if (this._onbuttondown && newValue === 1) {
  25274. this._onbuttondown(buttonIndex);
  25275. }
  25276. if (this._onbuttonup && newValue === 0) {
  25277. this._onbuttonup(buttonIndex);
  25278. }
  25279. }
  25280. return newValue;
  25281. };
  25282. GenericPad.prototype.update = function () {
  25283. _super.prototype.update.call(this);
  25284. for (var index = 0; index < this._buttons.length; index++) {
  25285. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25286. }
  25287. };
  25288. return GenericPad;
  25289. })(Gamepad);
  25290. BABYLON.GenericPad = GenericPad;
  25291. (function (Xbox360Button) {
  25292. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25293. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25294. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25295. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25296. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25297. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25298. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25299. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25300. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25301. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25302. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25303. var Xbox360Button = BABYLON.Xbox360Button;
  25304. (function (Xbox360Dpad) {
  25305. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25306. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25307. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25308. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25309. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25310. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25311. var Xbox360Pad = (function (_super) {
  25312. __extends(Xbox360Pad, _super);
  25313. function Xbox360Pad() {
  25314. _super.apply(this, arguments);
  25315. this._leftTrigger = 0;
  25316. this._rightTrigger = 0;
  25317. this._buttonA = 0;
  25318. this._buttonB = 0;
  25319. this._buttonX = 0;
  25320. this._buttonY = 0;
  25321. this._buttonBack = 0;
  25322. this._buttonStart = 0;
  25323. this._buttonLB = 0;
  25324. this._buttonRB = 0;
  25325. this._buttonLeftStick = 0;
  25326. this._buttonRightStick = 0;
  25327. this._dPadUp = 0;
  25328. this._dPadDown = 0;
  25329. this._dPadLeft = 0;
  25330. this._dPadRight = 0;
  25331. }
  25332. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25333. this._onlefttriggerchanged = callback;
  25334. };
  25335. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25336. this._onrighttriggerchanged = callback;
  25337. };
  25338. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25339. get: function () {
  25340. return this._leftTrigger;
  25341. },
  25342. set: function (newValue) {
  25343. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25344. this._onlefttriggerchanged(newValue);
  25345. }
  25346. this._leftTrigger = newValue;
  25347. },
  25348. enumerable: true,
  25349. configurable: true
  25350. });
  25351. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25352. get: function () {
  25353. return this._rightTrigger;
  25354. },
  25355. set: function (newValue) {
  25356. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25357. this._onrighttriggerchanged(newValue);
  25358. }
  25359. this._rightTrigger = newValue;
  25360. },
  25361. enumerable: true,
  25362. configurable: true
  25363. });
  25364. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25365. this._onbuttondown = callback;
  25366. };
  25367. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25368. this._onbuttonup = callback;
  25369. };
  25370. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25371. this._ondpaddown = callback;
  25372. };
  25373. Xbox360Pad.prototype.ondpadup = function (callback) {
  25374. this._ondpadup = callback;
  25375. };
  25376. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25377. if (newValue !== currentValue) {
  25378. if (this._onbuttondown && newValue === 1) {
  25379. this._onbuttondown(buttonType);
  25380. }
  25381. if (this._onbuttonup && newValue === 0) {
  25382. this._onbuttonup(buttonType);
  25383. }
  25384. }
  25385. return newValue;
  25386. };
  25387. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25388. if (newValue !== currentValue) {
  25389. if (this._ondpaddown && newValue === 1) {
  25390. this._ondpaddown(buttonType);
  25391. }
  25392. if (this._ondpadup && newValue === 0) {
  25393. this._ondpadup(buttonType);
  25394. }
  25395. }
  25396. return newValue;
  25397. };
  25398. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25399. get: function () {
  25400. return this._buttonA;
  25401. },
  25402. set: function (value) {
  25403. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25404. },
  25405. enumerable: true,
  25406. configurable: true
  25407. });
  25408. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25409. get: function () {
  25410. return this._buttonB;
  25411. },
  25412. set: function (value) {
  25413. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25414. },
  25415. enumerable: true,
  25416. configurable: true
  25417. });
  25418. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25419. get: function () {
  25420. return this._buttonX;
  25421. },
  25422. set: function (value) {
  25423. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25424. },
  25425. enumerable: true,
  25426. configurable: true
  25427. });
  25428. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25429. get: function () {
  25430. return this._buttonY;
  25431. },
  25432. set: function (value) {
  25433. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25434. },
  25435. enumerable: true,
  25436. configurable: true
  25437. });
  25438. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25439. get: function () {
  25440. return this._buttonStart;
  25441. },
  25442. set: function (value) {
  25443. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25444. },
  25445. enumerable: true,
  25446. configurable: true
  25447. });
  25448. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25449. get: function () {
  25450. return this._buttonBack;
  25451. },
  25452. set: function (value) {
  25453. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25454. },
  25455. enumerable: true,
  25456. configurable: true
  25457. });
  25458. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25459. get: function () {
  25460. return this._buttonLB;
  25461. },
  25462. set: function (value) {
  25463. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25464. },
  25465. enumerable: true,
  25466. configurable: true
  25467. });
  25468. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25469. get: function () {
  25470. return this._buttonRB;
  25471. },
  25472. set: function (value) {
  25473. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25474. },
  25475. enumerable: true,
  25476. configurable: true
  25477. });
  25478. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25479. get: function () {
  25480. return this._buttonLeftStick;
  25481. },
  25482. set: function (value) {
  25483. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25484. },
  25485. enumerable: true,
  25486. configurable: true
  25487. });
  25488. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25489. get: function () {
  25490. return this._buttonRightStick;
  25491. },
  25492. set: function (value) {
  25493. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25494. },
  25495. enumerable: true,
  25496. configurable: true
  25497. });
  25498. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25499. get: function () {
  25500. return this._dPadUp;
  25501. },
  25502. set: function (value) {
  25503. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25504. },
  25505. enumerable: true,
  25506. configurable: true
  25507. });
  25508. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25509. get: function () {
  25510. return this._dPadDown;
  25511. },
  25512. set: function (value) {
  25513. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25514. },
  25515. enumerable: true,
  25516. configurable: true
  25517. });
  25518. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25519. get: function () {
  25520. return this._dPadLeft;
  25521. },
  25522. set: function (value) {
  25523. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25524. },
  25525. enumerable: true,
  25526. configurable: true
  25527. });
  25528. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25529. get: function () {
  25530. return this._dPadRight;
  25531. },
  25532. set: function (value) {
  25533. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25534. },
  25535. enumerable: true,
  25536. configurable: true
  25537. });
  25538. Xbox360Pad.prototype.update = function () {
  25539. _super.prototype.update.call(this);
  25540. this.buttonA = this.browserGamepad.buttons[0].value;
  25541. this.buttonB = this.browserGamepad.buttons[1].value;
  25542. this.buttonX = this.browserGamepad.buttons[2].value;
  25543. this.buttonY = this.browserGamepad.buttons[3].value;
  25544. this.buttonLB = this.browserGamepad.buttons[4].value;
  25545. this.buttonRB = this.browserGamepad.buttons[5].value;
  25546. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25547. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25548. this.buttonBack = this.browserGamepad.buttons[8].value;
  25549. this.buttonStart = this.browserGamepad.buttons[9].value;
  25550. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25551. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25552. this.dPadUp = this.browserGamepad.buttons[12].value;
  25553. this.dPadDown = this.browserGamepad.buttons[13].value;
  25554. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25555. this.dPadRight = this.browserGamepad.buttons[15].value;
  25556. };
  25557. return Xbox360Pad;
  25558. })(Gamepad);
  25559. BABYLON.Xbox360Pad = Xbox360Pad;
  25560. })(BABYLON || (BABYLON = {}));
  25561. //# sourceMappingURL=babylon.gamepads.js.map
  25562. var BABYLON;
  25563. (function (BABYLON) {
  25564. // We're mainly based on the logic defined into the FreeCamera code
  25565. var GamepadCamera = (function (_super) {
  25566. __extends(GamepadCamera, _super);
  25567. function GamepadCamera(name, position, scene) {
  25568. var _this = this;
  25569. _super.call(this, name, position, scene);
  25570. this.angularSensibility = 200;
  25571. this.moveSensibility = 75;
  25572. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25573. _this._onNewGameConnected(gamepad);
  25574. });
  25575. }
  25576. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25577. // Only the first gamepad can control the camera
  25578. if (gamepad.index === 0) {
  25579. this._gamepad = gamepad;
  25580. }
  25581. };
  25582. GamepadCamera.prototype._checkInputs = function () {
  25583. if (!this._gamepad) {
  25584. return;
  25585. }
  25586. var LSValues = this._gamepad.leftStick;
  25587. var normalizedLX = LSValues.x / this.moveSensibility;
  25588. var normalizedLY = LSValues.y / this.moveSensibility;
  25589. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25590. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25591. var RSValues = this._gamepad.rightStick;
  25592. var normalizedRX = RSValues.x / this.angularSensibility;
  25593. var normalizedRY = RSValues.y / this.angularSensibility;
  25594. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25595. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25596. ;
  25597. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25598. var speed = this._computeLocalCameraSpeed() * 50.0;
  25599. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25600. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25601. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25602. };
  25603. GamepadCamera.prototype.dispose = function () {
  25604. this._gamepads.dispose();
  25605. _super.prototype.dispose.call(this);
  25606. };
  25607. return GamepadCamera;
  25608. })(BABYLON.FreeCamera);
  25609. BABYLON.GamepadCamera = GamepadCamera;
  25610. })(BABYLON || (BABYLON = {}));
  25611. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25612. var BABYLON;
  25613. (function (BABYLON) {
  25614. var LinesMesh = (function (_super) {
  25615. __extends(LinesMesh, _super);
  25616. function LinesMesh(name, scene, updatable) {
  25617. if (updatable === void 0) { updatable = false; }
  25618. _super.call(this, name, scene);
  25619. this.color = new BABYLON.Color3(1, 1, 1);
  25620. this.alpha = 1;
  25621. this._indices = new Array();
  25622. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25623. attributes: ["position"],
  25624. uniforms: ["worldViewProjection", "color"],
  25625. needAlphaBlending: true
  25626. });
  25627. }
  25628. Object.defineProperty(LinesMesh.prototype, "material", {
  25629. get: function () {
  25630. return this._colorShader;
  25631. },
  25632. enumerable: true,
  25633. configurable: true
  25634. });
  25635. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25636. get: function () {
  25637. return false;
  25638. },
  25639. enumerable: true,
  25640. configurable: true
  25641. });
  25642. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25643. get: function () {
  25644. return false;
  25645. },
  25646. enumerable: true,
  25647. configurable: true
  25648. });
  25649. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25650. var engine = this.getScene().getEngine();
  25651. var indexToBind = this._geometry.getIndexBuffer();
  25652. // VBOs
  25653. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25654. // Color
  25655. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25656. };
  25657. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25658. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25659. return;
  25660. }
  25661. var engine = this.getScene().getEngine();
  25662. // Draw order
  25663. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25664. };
  25665. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25666. return null;
  25667. };
  25668. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25669. this._colorShader.dispose();
  25670. _super.prototype.dispose.call(this, doNotRecurse);
  25671. };
  25672. return LinesMesh;
  25673. })(BABYLON.Mesh);
  25674. BABYLON.LinesMesh = LinesMesh;
  25675. })(BABYLON || (BABYLON = {}));
  25676. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25677. (function (BABYLON) {
  25678. var OutlineRenderer = (function () {
  25679. function OutlineRenderer(scene) {
  25680. this._scene = scene;
  25681. }
  25682. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25683. var _this = this;
  25684. if (useOverlay === void 0) { useOverlay = false; }
  25685. var scene = this._scene;
  25686. var engine = this._scene.getEngine();
  25687. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25688. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25689. return;
  25690. }
  25691. var mesh = subMesh.getRenderingMesh();
  25692. var material = subMesh.getMaterial();
  25693. engine.enableEffect(this._effect);
  25694. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25695. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25696. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25697. // Bones
  25698. if (mesh.useBones) {
  25699. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25700. }
  25701. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25702. // Alpha test
  25703. if (material && material.needAlphaTesting()) {
  25704. var alphaTexture = material.getAlphaTestTexture();
  25705. this._effect.setTexture("diffuseSampler", alphaTexture);
  25706. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25707. }
  25708. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25709. _this._effect.setMatrix("world", world);
  25710. });
  25711. };
  25712. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25713. var defines = [];
  25714. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25715. var mesh = subMesh.getMesh();
  25716. var material = subMesh.getMaterial();
  25717. // Alpha test
  25718. if (material && material.needAlphaTesting()) {
  25719. defines.push("#define ALPHATEST");
  25720. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25721. attribs.push(BABYLON.VertexBuffer.UVKind);
  25722. defines.push("#define UV1");
  25723. }
  25724. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25725. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25726. defines.push("#define UV2");
  25727. }
  25728. }
  25729. // Bones
  25730. if (mesh.useBones) {
  25731. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25732. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25733. defines.push("#define BONES");
  25734. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25735. }
  25736. // Instances
  25737. if (useInstances) {
  25738. defines.push("#define INSTANCES");
  25739. attribs.push("world0");
  25740. attribs.push("world1");
  25741. attribs.push("world2");
  25742. attribs.push("world3");
  25743. }
  25744. // Get correct effect
  25745. var join = defines.join("\n");
  25746. if (this._cachedDefines !== join) {
  25747. this._cachedDefines = join;
  25748. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25749. }
  25750. return this._effect.isReady();
  25751. };
  25752. return OutlineRenderer;
  25753. })();
  25754. BABYLON.OutlineRenderer = OutlineRenderer;
  25755. })(BABYLON || (BABYLON = {}));
  25756. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25757. (function (BABYLON) {
  25758. var MeshAssetTask = (function () {
  25759. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25760. this.name = name;
  25761. this.meshesNames = meshesNames;
  25762. this.rootUrl = rootUrl;
  25763. this.sceneFilename = sceneFilename;
  25764. this.isCompleted = false;
  25765. }
  25766. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25767. var _this = this;
  25768. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25769. _this.loadedMeshes = meshes;
  25770. _this.loadedParticleSystems = particleSystems;
  25771. _this.loadedSkeletons = skeletons;
  25772. _this.isCompleted = true;
  25773. if (_this.onSuccess) {
  25774. _this.onSuccess(_this);
  25775. }
  25776. onSuccess();
  25777. }, null, function () {
  25778. if (_this.onError) {
  25779. _this.onError(_this);
  25780. }
  25781. onError();
  25782. });
  25783. };
  25784. return MeshAssetTask;
  25785. })();
  25786. BABYLON.MeshAssetTask = MeshAssetTask;
  25787. var TextFileAssetTask = (function () {
  25788. function TextFileAssetTask(name, url) {
  25789. this.name = name;
  25790. this.url = url;
  25791. this.isCompleted = false;
  25792. }
  25793. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25794. var _this = this;
  25795. BABYLON.Tools.LoadFile(this.url, function (data) {
  25796. _this.text = data;
  25797. _this.isCompleted = true;
  25798. if (_this.onSuccess) {
  25799. _this.onSuccess(_this);
  25800. }
  25801. onSuccess();
  25802. }, null, scene.database, false, function () {
  25803. if (_this.onError) {
  25804. _this.onError(_this);
  25805. }
  25806. onError();
  25807. });
  25808. };
  25809. return TextFileAssetTask;
  25810. })();
  25811. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25812. var BinaryFileAssetTask = (function () {
  25813. function BinaryFileAssetTask(name, url) {
  25814. this.name = name;
  25815. this.url = url;
  25816. this.isCompleted = false;
  25817. }
  25818. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25819. var _this = this;
  25820. BABYLON.Tools.LoadFile(this.url, function (data) {
  25821. _this.data = data;
  25822. _this.isCompleted = true;
  25823. if (_this.onSuccess) {
  25824. _this.onSuccess(_this);
  25825. }
  25826. onSuccess();
  25827. }, null, scene.database, true, function () {
  25828. if (_this.onError) {
  25829. _this.onError(_this);
  25830. }
  25831. onError();
  25832. });
  25833. };
  25834. return BinaryFileAssetTask;
  25835. })();
  25836. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25837. var ImageAssetTask = (function () {
  25838. function ImageAssetTask(name, url) {
  25839. this.name = name;
  25840. this.url = url;
  25841. this.isCompleted = false;
  25842. }
  25843. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25844. var _this = this;
  25845. var img = new Image();
  25846. img.onload = function () {
  25847. _this.image = img;
  25848. _this.isCompleted = true;
  25849. if (_this.onSuccess) {
  25850. _this.onSuccess(_this);
  25851. }
  25852. onSuccess();
  25853. };
  25854. img.onerror = function () {
  25855. if (_this.onError) {
  25856. _this.onError(_this);
  25857. }
  25858. onError();
  25859. };
  25860. img.src = this.url;
  25861. };
  25862. return ImageAssetTask;
  25863. })();
  25864. BABYLON.ImageAssetTask = ImageAssetTask;
  25865. var TextureAssetTask = (function () {
  25866. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25867. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25868. this.name = name;
  25869. this.url = url;
  25870. this.noMipmap = noMipmap;
  25871. this.invertY = invertY;
  25872. this.samplingMode = samplingMode;
  25873. this.isCompleted = false;
  25874. }
  25875. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25876. var _this = this;
  25877. var onload = function () {
  25878. _this.isCompleted = true;
  25879. if (_this.onSuccess) {
  25880. _this.onSuccess(_this);
  25881. }
  25882. onSuccess();
  25883. };
  25884. var onerror = function () {
  25885. if (_this.onError) {
  25886. _this.onError(_this);
  25887. }
  25888. onError();
  25889. };
  25890. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25891. };
  25892. return TextureAssetTask;
  25893. })();
  25894. BABYLON.TextureAssetTask = TextureAssetTask;
  25895. var AssetsManager = (function () {
  25896. function AssetsManager(scene) {
  25897. this._tasks = new Array();
  25898. this._waitingTasksCount = 0;
  25899. this.useDefaultLoadingScreen = true;
  25900. this._scene = scene;
  25901. }
  25902. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25903. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25904. this._tasks.push(task);
  25905. return task;
  25906. };
  25907. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25908. var task = new TextFileAssetTask(taskName, url);
  25909. this._tasks.push(task);
  25910. return task;
  25911. };
  25912. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25913. var task = new BinaryFileAssetTask(taskName, url);
  25914. this._tasks.push(task);
  25915. return task;
  25916. };
  25917. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25918. var task = new ImageAssetTask(taskName, url);
  25919. this._tasks.push(task);
  25920. return task;
  25921. };
  25922. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25923. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25924. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25925. this._tasks.push(task);
  25926. return task;
  25927. };
  25928. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25929. this._waitingTasksCount--;
  25930. if (this._waitingTasksCount === 0) {
  25931. if (this.onFinish) {
  25932. this.onFinish(this._tasks);
  25933. }
  25934. this._scene.getEngine().hideLoadingUI();
  25935. }
  25936. };
  25937. AssetsManager.prototype._runTask = function (task) {
  25938. var _this = this;
  25939. task.run(this._scene, function () {
  25940. if (_this.onTaskSuccess) {
  25941. _this.onTaskSuccess(task);
  25942. }
  25943. _this._decreaseWaitingTasksCount();
  25944. }, function () {
  25945. if (_this.onTaskError) {
  25946. _this.onTaskError(task);
  25947. }
  25948. _this._decreaseWaitingTasksCount();
  25949. });
  25950. };
  25951. AssetsManager.prototype.reset = function () {
  25952. this._tasks = new Array();
  25953. return this;
  25954. };
  25955. AssetsManager.prototype.load = function () {
  25956. this._waitingTasksCount = this._tasks.length;
  25957. if (this._waitingTasksCount === 0) {
  25958. if (this.onFinish) {
  25959. this.onFinish(this._tasks);
  25960. }
  25961. return this;
  25962. }
  25963. if (this.useDefaultLoadingScreen) {
  25964. this._scene.getEngine().displayLoadingUI();
  25965. }
  25966. for (var index = 0; index < this._tasks.length; index++) {
  25967. var task = this._tasks[index];
  25968. this._runTask(task);
  25969. }
  25970. return this;
  25971. };
  25972. return AssetsManager;
  25973. })();
  25974. BABYLON.AssetsManager = AssetsManager;
  25975. })(BABYLON || (BABYLON = {}));
  25976. //# sourceMappingURL=babylon.assetsManager.js.map
  25977. var BABYLON;
  25978. (function (BABYLON) {
  25979. var VRDeviceOrientationCamera = (function (_super) {
  25980. __extends(VRDeviceOrientationCamera, _super);
  25981. function VRDeviceOrientationCamera(name, position, scene) {
  25982. _super.call(this, name, position, scene);
  25983. this._alpha = 0;
  25984. this._beta = 0;
  25985. this._gamma = 0;
  25986. }
  25987. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25988. this._alpha = +evt.alpha | 0;
  25989. this._beta = +evt.beta | 0;
  25990. this._gamma = +evt.gamma | 0;
  25991. if (this._gamma < 0) {
  25992. this._gamma = 90 + this._gamma;
  25993. }
  25994. else {
  25995. // Incline it in the correct angle.
  25996. this._gamma = 270 - this._gamma;
  25997. }
  25998. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25999. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26000. this.rotation.z = this._beta / 180.0 * Math.PI;
  26001. };
  26002. return VRDeviceOrientationCamera;
  26003. })(BABYLON.OculusCamera);
  26004. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26005. })(BABYLON || (BABYLON = {}));
  26006. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26007. var BABYLON;
  26008. (function (BABYLON) {
  26009. var WebVRCamera = (function (_super) {
  26010. __extends(WebVRCamera, _super);
  26011. function WebVRCamera(name, position, scene) {
  26012. _super.call(this, name, position, scene);
  26013. this._hmdDevice = null;
  26014. this._sensorDevice = null;
  26015. this._cacheState = null;
  26016. this._cacheQuaternion = new BABYLON.Quaternion();
  26017. this._cacheRotation = BABYLON.Vector3.Zero();
  26018. this._vrEnabled = false;
  26019. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26020. }
  26021. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26022. var size = devices.length;
  26023. var i = 0;
  26024. // Reset devices.
  26025. this._sensorDevice = null;
  26026. this._hmdDevice = null;
  26027. while (i < size && this._hmdDevice === null) {
  26028. if (devices[i] instanceof HMDVRDevice) {
  26029. this._hmdDevice = devices[i];
  26030. }
  26031. i++;
  26032. }
  26033. i = 0;
  26034. while (i < size && this._sensorDevice === null) {
  26035. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26036. this._sensorDevice = devices[i];
  26037. }
  26038. i++;
  26039. }
  26040. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26041. };
  26042. WebVRCamera.prototype._update = function () {
  26043. if (this._vrEnabled) {
  26044. this._cacheState = this._sensorDevice.getState();
  26045. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26046. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26047. this.rotation.x = -this._cacheRotation.z;
  26048. this.rotation.y = -this._cacheRotation.y;
  26049. this.rotation.z = this._cacheRotation.x;
  26050. }
  26051. _super.prototype._update.call(this);
  26052. };
  26053. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26054. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26055. if (navigator.getVRDevices) {
  26056. navigator.getVRDevices().then(this._getWebVRDevices);
  26057. }
  26058. else if (navigator.mozGetVRDevices) {
  26059. navigator.mozGetVRDevices(this._getWebVRDevices);
  26060. }
  26061. };
  26062. WebVRCamera.prototype.detachControl = function (element) {
  26063. _super.prototype.detachControl.call(this, element);
  26064. this._vrEnabled = false;
  26065. };
  26066. return WebVRCamera;
  26067. })(BABYLON.OculusCamera);
  26068. BABYLON.WebVRCamera = WebVRCamera;
  26069. })(BABYLON || (BABYLON = {}));
  26070. //# sourceMappingURL=babylon.webVRCamera.js.map
  26071. var BABYLON;
  26072. (function (BABYLON) {
  26073. // Standard optimizations
  26074. var SceneOptimization = (function () {
  26075. function SceneOptimization(priority) {
  26076. if (priority === void 0) { priority = 0; }
  26077. this.priority = priority;
  26078. this.apply = function (scene) {
  26079. return true; // Return true if everything that can be done was applied
  26080. };
  26081. }
  26082. return SceneOptimization;
  26083. })();
  26084. BABYLON.SceneOptimization = SceneOptimization;
  26085. var TextureOptimization = (function (_super) {
  26086. __extends(TextureOptimization, _super);
  26087. function TextureOptimization(priority, maximumSize) {
  26088. var _this = this;
  26089. if (priority === void 0) { priority = 0; }
  26090. if (maximumSize === void 0) { maximumSize = 1024; }
  26091. _super.call(this, priority);
  26092. this.priority = priority;
  26093. this.maximumSize = maximumSize;
  26094. this.apply = function (scene) {
  26095. var allDone = true;
  26096. for (var index = 0; index < scene.textures.length; index++) {
  26097. var texture = scene.textures[index];
  26098. if (!texture.canRescale) {
  26099. continue;
  26100. }
  26101. var currentSize = texture.getSize();
  26102. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26103. if (maxDimension > _this.maximumSize) {
  26104. texture.scale(0.5);
  26105. allDone = false;
  26106. }
  26107. }
  26108. return allDone;
  26109. };
  26110. }
  26111. return TextureOptimization;
  26112. })(SceneOptimization);
  26113. BABYLON.TextureOptimization = TextureOptimization;
  26114. var HardwareScalingOptimization = (function (_super) {
  26115. __extends(HardwareScalingOptimization, _super);
  26116. function HardwareScalingOptimization(priority, maximumScale) {
  26117. var _this = this;
  26118. if (priority === void 0) { priority = 0; }
  26119. if (maximumScale === void 0) { maximumScale = 2; }
  26120. _super.call(this, priority);
  26121. this.priority = priority;
  26122. this.maximumScale = maximumScale;
  26123. this._currentScale = 1;
  26124. this.apply = function (scene) {
  26125. _this._currentScale++;
  26126. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26127. return _this._currentScale >= _this.maximumScale;
  26128. };
  26129. }
  26130. return HardwareScalingOptimization;
  26131. })(SceneOptimization);
  26132. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26133. var ShadowsOptimization = (function (_super) {
  26134. __extends(ShadowsOptimization, _super);
  26135. function ShadowsOptimization() {
  26136. _super.apply(this, arguments);
  26137. this.apply = function (scene) {
  26138. scene.shadowsEnabled = false;
  26139. return true;
  26140. };
  26141. }
  26142. return ShadowsOptimization;
  26143. })(SceneOptimization);
  26144. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26145. var PostProcessesOptimization = (function (_super) {
  26146. __extends(PostProcessesOptimization, _super);
  26147. function PostProcessesOptimization() {
  26148. _super.apply(this, arguments);
  26149. this.apply = function (scene) {
  26150. scene.postProcessesEnabled = false;
  26151. return true;
  26152. };
  26153. }
  26154. return PostProcessesOptimization;
  26155. })(SceneOptimization);
  26156. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26157. var LensFlaresOptimization = (function (_super) {
  26158. __extends(LensFlaresOptimization, _super);
  26159. function LensFlaresOptimization() {
  26160. _super.apply(this, arguments);
  26161. this.apply = function (scene) {
  26162. scene.lensFlaresEnabled = false;
  26163. return true;
  26164. };
  26165. }
  26166. return LensFlaresOptimization;
  26167. })(SceneOptimization);
  26168. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26169. var ParticlesOptimization = (function (_super) {
  26170. __extends(ParticlesOptimization, _super);
  26171. function ParticlesOptimization() {
  26172. _super.apply(this, arguments);
  26173. this.apply = function (scene) {
  26174. scene.particlesEnabled = false;
  26175. return true;
  26176. };
  26177. }
  26178. return ParticlesOptimization;
  26179. })(SceneOptimization);
  26180. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26181. var RenderTargetsOptimization = (function (_super) {
  26182. __extends(RenderTargetsOptimization, _super);
  26183. function RenderTargetsOptimization() {
  26184. _super.apply(this, arguments);
  26185. this.apply = function (scene) {
  26186. scene.renderTargetsEnabled = false;
  26187. return true;
  26188. };
  26189. }
  26190. return RenderTargetsOptimization;
  26191. })(SceneOptimization);
  26192. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26193. var MergeMeshesOptimization = (function (_super) {
  26194. __extends(MergeMeshesOptimization, _super);
  26195. function MergeMeshesOptimization() {
  26196. var _this = this;
  26197. _super.apply(this, arguments);
  26198. this._canBeMerged = function (abstractMesh) {
  26199. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26200. return false;
  26201. }
  26202. var mesh = abstractMesh;
  26203. if (!mesh.isVisible || !mesh.isEnabled()) {
  26204. return false;
  26205. }
  26206. if (mesh.instances.length > 0) {
  26207. return false;
  26208. }
  26209. if (mesh.skeleton || mesh.hasLODLevels) {
  26210. return false;
  26211. }
  26212. return true;
  26213. };
  26214. this.apply = function (scene) {
  26215. var globalPool = scene.meshes.slice(0);
  26216. var globalLength = globalPool.length;
  26217. for (var index = 0; index < globalLength; index++) {
  26218. var currentPool = new Array();
  26219. var current = globalPool[index];
  26220. // Checks
  26221. if (!_this._canBeMerged(current)) {
  26222. continue;
  26223. }
  26224. currentPool.push(current);
  26225. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26226. var otherMesh = globalPool[subIndex];
  26227. if (!_this._canBeMerged(otherMesh)) {
  26228. continue;
  26229. }
  26230. if (otherMesh.material !== current.material) {
  26231. continue;
  26232. }
  26233. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26234. continue;
  26235. }
  26236. currentPool.push(otherMesh);
  26237. globalLength--;
  26238. globalPool.splice(subIndex, 1);
  26239. subIndex--;
  26240. }
  26241. if (currentPool.length < 2) {
  26242. continue;
  26243. }
  26244. // Merge meshes
  26245. BABYLON.Mesh.MergeMeshes(currentPool);
  26246. }
  26247. return true;
  26248. };
  26249. }
  26250. return MergeMeshesOptimization;
  26251. })(SceneOptimization);
  26252. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26253. // Options
  26254. var SceneOptimizerOptions = (function () {
  26255. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26256. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26257. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26258. this.targetFrameRate = targetFrameRate;
  26259. this.trackerDuration = trackerDuration;
  26260. this.optimizations = new Array();
  26261. }
  26262. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26263. var result = new SceneOptimizerOptions(targetFrameRate);
  26264. var priority = 0;
  26265. result.optimizations.push(new MergeMeshesOptimization(priority));
  26266. result.optimizations.push(new ShadowsOptimization(priority));
  26267. result.optimizations.push(new LensFlaresOptimization(priority));
  26268. // Next priority
  26269. priority++;
  26270. result.optimizations.push(new PostProcessesOptimization(priority));
  26271. result.optimizations.push(new ParticlesOptimization(priority));
  26272. // Next priority
  26273. priority++;
  26274. result.optimizations.push(new TextureOptimization(priority, 1024));
  26275. return result;
  26276. };
  26277. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26278. var result = new SceneOptimizerOptions(targetFrameRate);
  26279. var priority = 0;
  26280. result.optimizations.push(new MergeMeshesOptimization(priority));
  26281. result.optimizations.push(new ShadowsOptimization(priority));
  26282. result.optimizations.push(new LensFlaresOptimization(priority));
  26283. // Next priority
  26284. priority++;
  26285. result.optimizations.push(new PostProcessesOptimization(priority));
  26286. result.optimizations.push(new ParticlesOptimization(priority));
  26287. // Next priority
  26288. priority++;
  26289. result.optimizations.push(new TextureOptimization(priority, 512));
  26290. // Next priority
  26291. priority++;
  26292. result.optimizations.push(new RenderTargetsOptimization(priority));
  26293. // Next priority
  26294. priority++;
  26295. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26296. return result;
  26297. };
  26298. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26299. var result = new SceneOptimizerOptions(targetFrameRate);
  26300. var priority = 0;
  26301. result.optimizations.push(new MergeMeshesOptimization(priority));
  26302. result.optimizations.push(new ShadowsOptimization(priority));
  26303. result.optimizations.push(new LensFlaresOptimization(priority));
  26304. // Next priority
  26305. priority++;
  26306. result.optimizations.push(new PostProcessesOptimization(priority));
  26307. result.optimizations.push(new ParticlesOptimization(priority));
  26308. // Next priority
  26309. priority++;
  26310. result.optimizations.push(new TextureOptimization(priority, 256));
  26311. // Next priority
  26312. priority++;
  26313. result.optimizations.push(new RenderTargetsOptimization(priority));
  26314. // Next priority
  26315. priority++;
  26316. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26317. return result;
  26318. };
  26319. return SceneOptimizerOptions;
  26320. })();
  26321. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26322. // Scene optimizer tool
  26323. var SceneOptimizer = (function () {
  26324. function SceneOptimizer() {
  26325. }
  26326. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26327. // TODO: add an epsilon
  26328. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26329. if (onSuccess) {
  26330. onSuccess();
  26331. }
  26332. return;
  26333. }
  26334. // Apply current level of optimizations
  26335. var allDone = true;
  26336. var noOptimizationApplied = true;
  26337. for (var index = 0; index < options.optimizations.length; index++) {
  26338. var optimization = options.optimizations[index];
  26339. if (optimization.priority === currentPriorityLevel) {
  26340. noOptimizationApplied = false;
  26341. allDone = allDone && optimization.apply(scene);
  26342. }
  26343. }
  26344. // If no optimization was applied, this is a failure :(
  26345. if (noOptimizationApplied) {
  26346. if (onFailure) {
  26347. onFailure();
  26348. }
  26349. return;
  26350. }
  26351. // If all optimizations were done, move to next level
  26352. if (allDone) {
  26353. currentPriorityLevel++;
  26354. }
  26355. // Let's the system running for a specific amount of time before checking FPS
  26356. scene.executeWhenReady(function () {
  26357. setTimeout(function () {
  26358. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26359. }, options.trackerDuration);
  26360. });
  26361. };
  26362. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26363. if (!options) {
  26364. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26365. }
  26366. // Let's the system running for a specific amount of time before checking FPS
  26367. scene.executeWhenReady(function () {
  26368. setTimeout(function () {
  26369. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26370. }, options.trackerDuration);
  26371. });
  26372. };
  26373. return SceneOptimizer;
  26374. })();
  26375. BABYLON.SceneOptimizer = SceneOptimizer;
  26376. })(BABYLON || (BABYLON = {}));
  26377. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26378. (function (BABYLON) {
  26379. var Internals;
  26380. (function (Internals) {
  26381. var MeshLODLevel = (function () {
  26382. function MeshLODLevel(distance, mesh) {
  26383. this.distance = distance;
  26384. this.mesh = mesh;
  26385. }
  26386. return MeshLODLevel;
  26387. })();
  26388. Internals.MeshLODLevel = MeshLODLevel;
  26389. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26390. })(BABYLON || (BABYLON = {}));
  26391. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26392. (function (BABYLON) {
  26393. var AudioEngine = (function () {
  26394. function AudioEngine() {
  26395. this.audioContext = null;
  26396. this.canUseWebAudio = false;
  26397. this.WarnedWebAudioUnsupported = false;
  26398. try {
  26399. if (typeof AudioContext !== 'undefined') {
  26400. this.audioContext = new AudioContext();
  26401. this.canUseWebAudio = true;
  26402. }
  26403. else if (typeof webkitAudioContext !== 'undefined') {
  26404. this.audioContext = new webkitAudioContext();
  26405. this.canUseWebAudio = true;
  26406. }
  26407. }
  26408. catch (e) {
  26409. this.canUseWebAudio = false;
  26410. BABYLON.Tools.Error("Web Audio: " + e.message);
  26411. }
  26412. // create a global volume gain node
  26413. if (this.canUseWebAudio) {
  26414. this.masterGain = this.audioContext.createGain();
  26415. this.masterGain.gain.value = 1;
  26416. this.masterGain.connect(this.audioContext.destination);
  26417. }
  26418. }
  26419. AudioEngine.prototype.dispose = function () {
  26420. if (this.canUseWebAudio) {
  26421. if (this._connectedAnalyser) {
  26422. this._connectedAnalyser.stopDebugCanvas();
  26423. this._connectedAnalyser.dispose();
  26424. this.masterGain.disconnect();
  26425. this.masterGain.connect(this.audioContext.destination);
  26426. this._connectedAnalyser = null;
  26427. }
  26428. this.masterGain.gain.value = 1;
  26429. }
  26430. this.WarnedWebAudioUnsupported = false;
  26431. };
  26432. AudioEngine.prototype.getGlobalVolume = function () {
  26433. if (this.canUseWebAudio) {
  26434. return this.masterGain.gain.value;
  26435. }
  26436. else {
  26437. return -1;
  26438. }
  26439. };
  26440. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26441. if (this.canUseWebAudio) {
  26442. this.masterGain.gain.value = newVolume;
  26443. }
  26444. };
  26445. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26446. if (this._connectedAnalyser) {
  26447. this._connectedAnalyser.stopDebugCanvas();
  26448. }
  26449. this._connectedAnalyser = analyser;
  26450. if (this.canUseWebAudio) {
  26451. this.masterGain.disconnect();
  26452. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26453. }
  26454. };
  26455. return AudioEngine;
  26456. })();
  26457. BABYLON.AudioEngine = AudioEngine;
  26458. })(BABYLON || (BABYLON = {}));
  26459. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26460. (function (BABYLON) {
  26461. var Sound = (function () {
  26462. /**
  26463. * Create a sound and attach it to a scene
  26464. * @param name Name of your sound
  26465. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26466. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26467. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26468. */
  26469. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26470. var _this = this;
  26471. this.autoplay = false;
  26472. this.loop = false;
  26473. this.useCustomAttenuation = false;
  26474. this.spatialSound = false;
  26475. this.refDistance = 1;
  26476. this.rolloffFactor = 1;
  26477. this.maxDistance = 100;
  26478. this.distanceModel = "linear";
  26479. this.panningModel = "HRTF";
  26480. this._playbackRate = 1;
  26481. this._startTime = 0;
  26482. this._startOffset = 0;
  26483. this._position = BABYLON.Vector3.Zero();
  26484. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26485. this._volume = 1;
  26486. this._isLoaded = false;
  26487. this._isReadyToPlay = false;
  26488. this.isPlaying = false;
  26489. this.isPaused = false;
  26490. this._isDirectional = false;
  26491. // Used if you'd like to create a directional sound.
  26492. // If not set, the sound will be omnidirectional
  26493. this._coneInnerAngle = 360;
  26494. this._coneOuterAngle = 360;
  26495. this._coneOuterGain = 0;
  26496. this.name = name;
  26497. this._scene = scene;
  26498. this._readyToPlayCallback = readyToPlayCallback;
  26499. // Default custom attenuation function is a linear attenuation
  26500. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26501. if (currentDistance < maxDistance) {
  26502. return currentVolume * (1 - currentDistance / maxDistance);
  26503. }
  26504. else {
  26505. return 0;
  26506. }
  26507. };
  26508. if (options) {
  26509. this.autoplay = options.autoplay || false;
  26510. this.loop = options.loop || false;
  26511. // if volume === 0, we need another way to check this option
  26512. if (options.volume !== undefined) {
  26513. this._volume = options.volume;
  26514. }
  26515. this.spatialSound = options.spatialSound || false;
  26516. this.maxDistance = options.maxDistance || 100;
  26517. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26518. this.rolloffFactor = options.rolloffFactor || 1;
  26519. this.refDistance = options.refDistance || 1;
  26520. this.distanceModel = options.distanceModel || "linear";
  26521. this.panningModel = options.panningModel || "HRTF";
  26522. this._playbackRate = options.playbackRate || 1;
  26523. }
  26524. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26525. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26526. this._soundGain.gain.value = this._volume;
  26527. this._inputAudioNode = this._soundGain;
  26528. this._ouputAudioNode = this._soundGain;
  26529. if (this.spatialSound) {
  26530. this._createSpatialParameters();
  26531. }
  26532. this._scene.mainSoundTrack.AddSound(this);
  26533. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26534. if (urlOrArrayBuffer) {
  26535. // If it's an URL
  26536. if (typeof (urlOrArrayBuffer) === "string") {
  26537. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26538. _this._soundLoaded(data);
  26539. }, null, null, true);
  26540. }
  26541. else {
  26542. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26543. this._soundLoaded(urlOrArrayBuffer);
  26544. }
  26545. else {
  26546. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26547. }
  26548. }
  26549. }
  26550. }
  26551. else {
  26552. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26553. this._scene.mainSoundTrack.AddSound(this);
  26554. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26555. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26556. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26557. }
  26558. }
  26559. }
  26560. Sound.prototype.dispose = function () {
  26561. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26562. if (this.isPlaying) {
  26563. this.stop();
  26564. }
  26565. this._isReadyToPlay = false;
  26566. if (this.soundTrackId === -1) {
  26567. this._scene.mainSoundTrack.RemoveSound(this);
  26568. }
  26569. else {
  26570. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26571. }
  26572. if (this._soundGain) {
  26573. this._soundGain.disconnect();
  26574. this._soundGain = null;
  26575. }
  26576. if (this._soundPanner) {
  26577. this._soundPanner.disconnect();
  26578. this._soundPanner = null;
  26579. }
  26580. if (this._soundSource) {
  26581. this._soundSource.disconnect();
  26582. this._soundSource = null;
  26583. }
  26584. this._audioBuffer = null;
  26585. if (this._connectedMesh) {
  26586. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26587. this._connectedMesh = null;
  26588. }
  26589. }
  26590. };
  26591. Sound.prototype._soundLoaded = function (audioData) {
  26592. var _this = this;
  26593. this._isLoaded = true;
  26594. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26595. _this._audioBuffer = buffer;
  26596. _this._isReadyToPlay = true;
  26597. if (_this.autoplay) {
  26598. _this.play();
  26599. }
  26600. if (_this._readyToPlayCallback) {
  26601. _this._readyToPlayCallback();
  26602. }
  26603. }, function (error) {
  26604. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26605. });
  26606. };
  26607. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26608. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26609. this._audioBuffer = audioBuffer;
  26610. this._isReadyToPlay = true;
  26611. }
  26612. };
  26613. Sound.prototype.updateOptions = function (options) {
  26614. if (options) {
  26615. this.loop = options.loop || this.loop;
  26616. this.maxDistance = options.maxDistance || this.maxDistance;
  26617. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26618. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26619. this.refDistance = options.refDistance || this.refDistance;
  26620. this.distanceModel = options.distanceModel || this.distanceModel;
  26621. this.panningModel = options.panningModel || this.panningModel;
  26622. this._playbackRate = options.playbackRate || this._playbackRate;
  26623. }
  26624. };
  26625. Sound.prototype._createSpatialParameters = function () {
  26626. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26627. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26628. if (this.useCustomAttenuation) {
  26629. // Tricks to disable in a way embedded Web Audio attenuation
  26630. this._soundPanner.distanceModel = "linear";
  26631. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26632. this._soundPanner.refDistance = 1;
  26633. this._soundPanner.rolloffFactor = 1;
  26634. this._soundPanner.panningModel = "HRTF";
  26635. }
  26636. else {
  26637. this._soundPanner.distanceModel = this.distanceModel;
  26638. this._soundPanner.maxDistance = this.maxDistance;
  26639. this._soundPanner.refDistance = this.refDistance;
  26640. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26641. this._soundPanner.panningModel = this.panningModel;
  26642. }
  26643. this._soundPanner.connect(this._ouputAudioNode);
  26644. this._inputAudioNode = this._soundPanner;
  26645. }
  26646. };
  26647. Sound.prototype.switchPanningModelToHRTF = function () {
  26648. this._switchPanningModel("HRTF");
  26649. };
  26650. Sound.prototype.switchPanningModelToEqualPower = function () {
  26651. this._switchPanningModel("equalpower");
  26652. };
  26653. Sound.prototype._switchPanningModel = function (newModel) {
  26654. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26655. this._soundPanner.panningModel = newModel;
  26656. }
  26657. };
  26658. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26659. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26660. this._ouputAudioNode.disconnect();
  26661. this._ouputAudioNode.connect(soundTrackAudioNode);
  26662. }
  26663. };
  26664. /**
  26665. * Transform this sound into a directional source
  26666. * @param coneInnerAngle Size of the inner cone in degree
  26667. * @param coneOuterAngle Size of the outer cone in degree
  26668. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26669. */
  26670. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26671. if (coneOuterAngle < coneInnerAngle) {
  26672. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26673. return;
  26674. }
  26675. this._coneInnerAngle = coneInnerAngle;
  26676. this._coneOuterAngle = coneOuterAngle;
  26677. this._coneOuterGain = coneOuterGain;
  26678. this._isDirectional = true;
  26679. if (this.isPlaying && this.loop) {
  26680. this.stop();
  26681. this.play();
  26682. }
  26683. };
  26684. Sound.prototype.setPosition = function (newPosition) {
  26685. this._position = newPosition;
  26686. if (this.isPlaying && this.spatialSound) {
  26687. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26688. }
  26689. };
  26690. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26691. this._localDirection = newLocalDirection;
  26692. if (this._connectedMesh && this.isPlaying) {
  26693. this._updateDirection();
  26694. }
  26695. };
  26696. Sound.prototype._updateDirection = function () {
  26697. var mat = this._connectedMesh.getWorldMatrix();
  26698. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26699. direction.normalize();
  26700. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26701. };
  26702. Sound.prototype.updateDistanceFromListener = function () {
  26703. if (this._connectedMesh && this.useCustomAttenuation) {
  26704. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26705. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26706. }
  26707. };
  26708. Sound.prototype.setAttenuationFunction = function (callback) {
  26709. this._customAttenuationFunction = callback;
  26710. };
  26711. /**
  26712. * Play the sound
  26713. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26714. */
  26715. Sound.prototype.play = function (time) {
  26716. var _this = this;
  26717. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26718. try {
  26719. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26720. if (!this._soundSource) {
  26721. if (this.spatialSound) {
  26722. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26723. if (this._isDirectional) {
  26724. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26725. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26726. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26727. if (this._connectedMesh) {
  26728. this._updateDirection();
  26729. }
  26730. else {
  26731. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26732. }
  26733. }
  26734. }
  26735. }
  26736. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26737. this._soundSource.buffer = this._audioBuffer;
  26738. this._soundSource.connect(this._inputAudioNode);
  26739. this._soundSource.loop = this.loop;
  26740. this._soundSource.playbackRate.value = this._playbackRate;
  26741. this._startTime = startTime;
  26742. this._soundSource.onended = function () {
  26743. _this._onended();
  26744. };
  26745. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26746. this.isPlaying = true;
  26747. this.isPaused = false;
  26748. }
  26749. catch (ex) {
  26750. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26751. }
  26752. }
  26753. };
  26754. Sound.prototype._onended = function () {
  26755. this.isPlaying = false;
  26756. if (this.onended) {
  26757. this.onended();
  26758. }
  26759. };
  26760. /**
  26761. * Stop the sound
  26762. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26763. */
  26764. Sound.prototype.stop = function (time) {
  26765. if (this.isPlaying) {
  26766. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26767. this._soundSource.stop(stopTime);
  26768. this.isPlaying = false;
  26769. }
  26770. };
  26771. Sound.prototype.pause = function () {
  26772. if (this.isPlaying) {
  26773. this.stop(0);
  26774. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26775. this.isPaused = true;
  26776. }
  26777. };
  26778. Sound.prototype.setVolume = function (newVolume, time) {
  26779. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26780. if (time) {
  26781. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26782. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26783. }
  26784. else {
  26785. this._soundGain.gain.value = newVolume;
  26786. }
  26787. }
  26788. this._volume = newVolume;
  26789. };
  26790. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26791. this._playbackRate = newPlaybackRate;
  26792. if (this.isPlaying) {
  26793. this._soundSource.playbackRate.value = this._playbackRate;
  26794. }
  26795. };
  26796. Sound.prototype.getVolume = function () {
  26797. return this._volume;
  26798. };
  26799. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26800. var _this = this;
  26801. this._connectedMesh = meshToConnectTo;
  26802. if (!this.spatialSound) {
  26803. this._createSpatialParameters();
  26804. this.spatialSound = true;
  26805. if (this.isPlaying && this.loop) {
  26806. this.stop();
  26807. this.play();
  26808. }
  26809. }
  26810. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26811. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26812. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26813. };
  26814. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26815. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26816. if (this._isDirectional && this.isPlaying) {
  26817. this._updateDirection();
  26818. }
  26819. };
  26820. return Sound;
  26821. })();
  26822. BABYLON.Sound = Sound;
  26823. })(BABYLON || (BABYLON = {}));
  26824. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26825. (function (BABYLON) {
  26826. var SoundTrack = (function () {
  26827. function SoundTrack(scene, options) {
  26828. this.id = -1;
  26829. this._isMainTrack = false;
  26830. this._scene = scene;
  26831. this._audioEngine = BABYLON.Engine.audioEngine;
  26832. this.soundCollection = new Array();
  26833. if (this._audioEngine.canUseWebAudio) {
  26834. this._trackGain = this._audioEngine.audioContext.createGain();
  26835. this._trackGain.connect(this._audioEngine.masterGain);
  26836. if (options) {
  26837. if (options.volume) {
  26838. this._trackGain.gain.value = options.volume;
  26839. }
  26840. if (options.mainTrack) {
  26841. this._isMainTrack = options.mainTrack;
  26842. }
  26843. }
  26844. }
  26845. if (!this._isMainTrack) {
  26846. this._scene.soundTracks.push(this);
  26847. this.id = this._scene.soundTracks.length - 1;
  26848. }
  26849. }
  26850. SoundTrack.prototype.dispose = function () {
  26851. if (this._audioEngine.canUseWebAudio) {
  26852. if (this._connectedAnalyser) {
  26853. this._connectedAnalyser.stopDebugCanvas();
  26854. }
  26855. while (this.soundCollection.length) {
  26856. this.soundCollection[0].dispose();
  26857. }
  26858. this._trackGain.disconnect();
  26859. this._trackGain = null;
  26860. }
  26861. };
  26862. SoundTrack.prototype.AddSound = function (sound) {
  26863. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26864. sound.connectToSoundTrackAudioNode(this._trackGain);
  26865. }
  26866. if (sound.soundTrackId) {
  26867. if (sound.soundTrackId === -1) {
  26868. this._scene.mainSoundTrack.RemoveSound(sound);
  26869. }
  26870. else {
  26871. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26872. }
  26873. }
  26874. this.soundCollection.push(sound);
  26875. sound.soundTrackId = this.id;
  26876. };
  26877. SoundTrack.prototype.RemoveSound = function (sound) {
  26878. var index = this.soundCollection.indexOf(sound);
  26879. if (index !== -1) {
  26880. this.soundCollection.splice(index, 1);
  26881. }
  26882. };
  26883. SoundTrack.prototype.setVolume = function (newVolume) {
  26884. if (this._audioEngine.canUseWebAudio) {
  26885. this._trackGain.gain.value = newVolume;
  26886. }
  26887. };
  26888. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26889. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26890. for (var i = 0; i < this.soundCollection.length; i++) {
  26891. this.soundCollection[i].switchPanningModelToHRTF();
  26892. }
  26893. }
  26894. };
  26895. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26896. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26897. for (var i = 0; i < this.soundCollection.length; i++) {
  26898. this.soundCollection[i].switchPanningModelToEqualPower();
  26899. }
  26900. }
  26901. };
  26902. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26903. if (this._connectedAnalyser) {
  26904. this._connectedAnalyser.stopDebugCanvas();
  26905. }
  26906. this._connectedAnalyser = analyser;
  26907. if (this._audioEngine.canUseWebAudio) {
  26908. this._trackGain.disconnect();
  26909. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26910. }
  26911. };
  26912. return SoundTrack;
  26913. })();
  26914. BABYLON.SoundTrack = SoundTrack;
  26915. })(BABYLON || (BABYLON = {}));
  26916. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26917. (function (BABYLON) {
  26918. var DebugLayer = (function () {
  26919. function DebugLayer(scene) {
  26920. var _this = this;
  26921. this._transformationMatrix = BABYLON.Matrix.Identity();
  26922. this._enabled = false;
  26923. this._labelsEnabled = false;
  26924. this._displayStatistics = true;
  26925. this._displayTree = false;
  26926. this._displayLogs = false;
  26927. this._identityMatrix = BABYLON.Matrix.Identity();
  26928. this.axisRatio = 0.02;
  26929. this.accentColor = "orange";
  26930. this._scene = scene;
  26931. this._syncPositions = function () {
  26932. var engine = _this._scene.getEngine();
  26933. var canvasRect = engine.getRenderingCanvasClientRect();
  26934. if (_this._showUI) {
  26935. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26936. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26937. _this._statsDiv.style.width = "400px";
  26938. _this._statsDiv.style.height = "auto";
  26939. _this._statsSubsetDiv.style.maxHeight = "240px";
  26940. _this._optionsDiv.style.left = "0px";
  26941. _this._optionsDiv.style.top = "10px";
  26942. _this._optionsDiv.style.width = "200px";
  26943. _this._optionsDiv.style.height = "auto";
  26944. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26945. _this._logDiv.style.left = "0px";
  26946. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26947. _this._logDiv.style.width = "600px";
  26948. _this._logDiv.style.height = "160px";
  26949. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26950. _this._treeDiv.style.top = "10px";
  26951. _this._treeDiv.style.width = "300px";
  26952. _this._treeDiv.style.height = "auto";
  26953. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26954. }
  26955. _this._globalDiv.style.left = canvasRect.left + "px";
  26956. _this._globalDiv.style.top = canvasRect.top + "px";
  26957. _this._drawingCanvas.style.left = "0px";
  26958. _this._drawingCanvas.style.top = "0px";
  26959. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26960. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26961. var devicePixelRatio = window.devicePixelRatio || 1;
  26962. var context = _this._drawingContext;
  26963. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26964. _this._ratio = devicePixelRatio / backingStoreRatio;
  26965. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26966. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26967. };
  26968. this._onCanvasClick = function (evt) {
  26969. _this._clickPosition = {
  26970. x: evt.clientX * _this._ratio,
  26971. y: evt.clientY * _this._ratio
  26972. };
  26973. };
  26974. this._syncUI = function () {
  26975. if (_this._showUI) {
  26976. if (_this._displayStatistics) {
  26977. _this._displayStats();
  26978. _this._statsDiv.style.display = "";
  26979. }
  26980. else {
  26981. _this._statsDiv.style.display = "none";
  26982. }
  26983. if (_this._displayLogs) {
  26984. _this._logDiv.style.display = "";
  26985. }
  26986. else {
  26987. _this._logDiv.style.display = "none";
  26988. }
  26989. if (_this._displayTree) {
  26990. _this._treeDiv.style.display = "";
  26991. if (_this._needToRefreshMeshesTree) {
  26992. _this._needToRefreshMeshesTree = false;
  26993. _this._refreshMeshesTreeContent();
  26994. }
  26995. }
  26996. else {
  26997. _this._treeDiv.style.display = "none";
  26998. }
  26999. }
  27000. };
  27001. this._syncData = function () {
  27002. if (_this._labelsEnabled || !_this._showUI) {
  27003. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27004. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27005. var engine = _this._scene.getEngine();
  27006. var viewport = _this._camera.viewport;
  27007. var globalViewport = viewport.toGlobal(engine);
  27008. // Meshes
  27009. var meshes = _this._camera.getActiveMeshes();
  27010. for (var index = 0; index < meshes.length; index++) {
  27011. var mesh = meshes.data[index];
  27012. var position = mesh.getBoundingInfo().boundingSphere.center;
  27013. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27014. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27015. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27016. }
  27017. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27018. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27019. mesh.renderOverlay = !mesh.renderOverlay;
  27020. }, function () {
  27021. return mesh.renderOverlay ? 'red' : 'black';
  27022. });
  27023. }
  27024. }
  27025. // Cameras
  27026. var cameras = _this._scene.cameras;
  27027. for (index = 0; index < cameras.length; index++) {
  27028. var camera = cameras[index];
  27029. if (camera === _this._camera) {
  27030. continue;
  27031. }
  27032. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27033. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27034. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27035. _this._camera.detachControl(engine.getRenderingCanvas());
  27036. _this._camera = camera;
  27037. _this._camera.attachControl(engine.getRenderingCanvas());
  27038. }, function () {
  27039. return "purple";
  27040. });
  27041. }
  27042. }
  27043. // Lights
  27044. var lights = _this._scene.lights;
  27045. for (index = 0; index < lights.length; index++) {
  27046. var light = lights[index];
  27047. if (light.position) {
  27048. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27049. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27050. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27051. light.setEnabled(!light.isEnabled());
  27052. }, function () {
  27053. return light.isEnabled() ? "orange" : "gray";
  27054. });
  27055. }
  27056. }
  27057. }
  27058. }
  27059. _this._clickPosition = undefined;
  27060. };
  27061. }
  27062. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27063. while (this._treeSubsetDiv.hasChildNodes()) {
  27064. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27065. }
  27066. // Add meshes
  27067. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27068. sortedArray.sort(function (a, b) {
  27069. if (a.name === b.name) {
  27070. return 0;
  27071. }
  27072. return (a.name > b.name) ? 1 : -1;
  27073. });
  27074. for (var index = 0; index < sortedArray.length; index++) {
  27075. var mesh = sortedArray[index];
  27076. if (!mesh.isEnabled()) {
  27077. continue;
  27078. }
  27079. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27080. m.isVisible = element.checked;
  27081. }, mesh);
  27082. }
  27083. };
  27084. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27085. this._drawingContext.beginPath();
  27086. this._drawingContext.moveTo(zero.x, zero.y);
  27087. this._drawingContext.lineTo(unit.x, unit.y);
  27088. this._drawingContext.strokeStyle = color;
  27089. this._drawingContext.lineWidth = 4;
  27090. this._drawingContext.stroke();
  27091. this._drawingContext.font = "normal 14px Segoe UI";
  27092. this._drawingContext.fillStyle = color;
  27093. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27094. };
  27095. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27096. var position = mesh.getBoundingInfo().boundingSphere.center;
  27097. var worldMatrix = mesh.getWorldMatrix();
  27098. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27099. var unit = (unprojectedVector.subtract(position)).length();
  27100. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27101. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27102. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27103. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27104. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27105. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27106. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27107. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27108. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27109. };
  27110. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27111. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27112. this._drawingContext.font = "normal 12px Segoe UI";
  27113. var textMetrics = this._drawingContext.measureText(text);
  27114. var centerX = projectedPosition.x - textMetrics.width / 2;
  27115. var centerY = projectedPosition.y;
  27116. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27117. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27118. onClick();
  27119. }
  27120. this._drawingContext.beginPath();
  27121. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27122. this._drawingContext.fillStyle = getFillStyle();
  27123. this._drawingContext.globalAlpha = 0.5;
  27124. this._drawingContext.fill();
  27125. this._drawingContext.globalAlpha = 1.0;
  27126. this._drawingContext.strokeStyle = '#FFFFFF';
  27127. this._drawingContext.lineWidth = 1;
  27128. this._drawingContext.stroke();
  27129. this._drawingContext.fillStyle = "#FFFFFF";
  27130. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27131. this._drawingContext.beginPath();
  27132. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27133. this._drawingContext.fill();
  27134. }
  27135. };
  27136. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27137. if (!this._clickPosition) {
  27138. return false;
  27139. }
  27140. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27141. return false;
  27142. }
  27143. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27144. return false;
  27145. }
  27146. return true;
  27147. };
  27148. DebugLayer.prototype.isVisible = function () {
  27149. return this._enabled;
  27150. };
  27151. DebugLayer.prototype.hide = function () {
  27152. if (!this._enabled) {
  27153. return;
  27154. }
  27155. this._enabled = false;
  27156. var engine = this._scene.getEngine();
  27157. this._scene.unregisterBeforeRender(this._syncData);
  27158. this._scene.unregisterAfterRender(this._syncUI);
  27159. document.body.removeChild(this._globalDiv);
  27160. window.removeEventListener("resize", this._syncPositions);
  27161. this._scene.forceShowBoundingBoxes = false;
  27162. this._scene.forceWireframe = false;
  27163. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27164. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27165. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27166. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27167. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27168. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27169. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27170. this._scene.shadowsEnabled = true;
  27171. this._scene.particlesEnabled = true;
  27172. this._scene.postProcessesEnabled = true;
  27173. this._scene.collisionsEnabled = true;
  27174. this._scene.lightsEnabled = true;
  27175. this._scene.texturesEnabled = true;
  27176. this._scene.lensFlaresEnabled = true;
  27177. this._scene.proceduralTexturesEnabled = true;
  27178. this._scene.renderTargetsEnabled = true;
  27179. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27180. };
  27181. DebugLayer.prototype.show = function (showUI, camera) {
  27182. if (showUI === void 0) { showUI = true; }
  27183. if (camera === void 0) { camera = null; }
  27184. if (this._enabled) {
  27185. return;
  27186. }
  27187. if (camera) {
  27188. this._camera = camera;
  27189. }
  27190. else {
  27191. this._camera = this._scene.activeCamera;
  27192. }
  27193. this._enabled = true;
  27194. this._showUI = showUI;
  27195. var engine = this._scene.getEngine();
  27196. this._globalDiv = document.createElement("div");
  27197. document.body.appendChild(this._globalDiv);
  27198. this._generateDOMelements();
  27199. window.addEventListener("resize", this._syncPositions);
  27200. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27201. this._syncPositions();
  27202. this._scene.registerBeforeRender(this._syncData);
  27203. this._scene.registerAfterRender(this._syncUI);
  27204. };
  27205. DebugLayer.prototype._clearLabels = function () {
  27206. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27207. for (var index = 0; index < this._scene.meshes.length; index++) {
  27208. var mesh = this._scene.meshes[index];
  27209. mesh.renderOverlay = false;
  27210. }
  27211. };
  27212. DebugLayer.prototype._generateheader = function (root, text) {
  27213. var header = document.createElement("div");
  27214. header.innerHTML = text + "&nbsp;";
  27215. header.style.textAlign = "right";
  27216. header.style.width = "100%";
  27217. header.style.color = "white";
  27218. header.style.backgroundColor = "Black";
  27219. header.style.padding = "5px 5px 4px 0px";
  27220. header.style.marginLeft = "-5px";
  27221. header.style.fontWeight = "bold";
  27222. root.appendChild(header);
  27223. };
  27224. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27225. var label = document.createElement("label");
  27226. label.innerHTML = title;
  27227. label.style.color = color;
  27228. root.appendChild(label);
  27229. root.appendChild(document.createElement("br"));
  27230. };
  27231. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27232. if (tag === void 0) { tag = null; }
  27233. var label = document.createElement("label");
  27234. var boundingBoxesCheckbox = document.createElement("input");
  27235. boundingBoxesCheckbox.type = "checkbox";
  27236. boundingBoxesCheckbox.checked = initialState;
  27237. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27238. task(evt.target, tag);
  27239. });
  27240. label.appendChild(boundingBoxesCheckbox);
  27241. var container = document.createElement("span");
  27242. var leftPart = document.createElement("span");
  27243. var rightPart = document.createElement("span");
  27244. rightPart.style.cssFloat = "right";
  27245. leftPart.innerHTML = leftTitle;
  27246. rightPart.innerHTML = rightTitle;
  27247. rightPart.style.fontSize = "12px";
  27248. rightPart.style.maxWidth = "200px";
  27249. container.appendChild(leftPart);
  27250. container.appendChild(rightPart);
  27251. label.appendChild(container);
  27252. root.appendChild(label);
  27253. root.appendChild(document.createElement("br"));
  27254. };
  27255. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27256. if (tag === void 0) { tag = null; }
  27257. var label = document.createElement("label");
  27258. var checkBox = document.createElement("input");
  27259. checkBox.type = "checkbox";
  27260. checkBox.checked = initialState;
  27261. checkBox.addEventListener("change", function (evt) {
  27262. task(evt.target, tag);
  27263. });
  27264. label.appendChild(checkBox);
  27265. label.appendChild(document.createTextNode(title));
  27266. root.appendChild(label);
  27267. root.appendChild(document.createElement("br"));
  27268. };
  27269. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27270. if (tag === void 0) { tag = null; }
  27271. var button = document.createElement("button");
  27272. button.innerHTML = title;
  27273. button.style.height = "24px";
  27274. button.style.color = "#444444";
  27275. button.style.border = "1px solid white";
  27276. button.className = "debugLayerButton";
  27277. button.addEventListener("click", function (evt) {
  27278. task(evt.target, tag);
  27279. });
  27280. root.appendChild(button);
  27281. root.appendChild(document.createElement("br"));
  27282. };
  27283. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27284. if (tag === void 0) { tag = null; }
  27285. var label = document.createElement("label");
  27286. var boundingBoxesRadio = document.createElement("input");
  27287. boundingBoxesRadio.type = "radio";
  27288. boundingBoxesRadio.name = name;
  27289. boundingBoxesRadio.checked = initialState;
  27290. boundingBoxesRadio.addEventListener("change", function (evt) {
  27291. task(evt.target, tag);
  27292. });
  27293. label.appendChild(boundingBoxesRadio);
  27294. label.appendChild(document.createTextNode(title));
  27295. root.appendChild(label);
  27296. root.appendChild(document.createElement("br"));
  27297. };
  27298. DebugLayer.prototype._generateDOMelements = function () {
  27299. var _this = this;
  27300. this._globalDiv.id = "DebugLayer";
  27301. this._globalDiv.style.position = "absolute";
  27302. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27303. this._globalDiv.style.fontSize = "14px";
  27304. this._globalDiv.style.color = "white";
  27305. // Drawing canvas
  27306. this._drawingCanvas = document.createElement("canvas");
  27307. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27308. this._drawingCanvas.style.position = "absolute";
  27309. this._drawingCanvas.style.pointerEvents = "none";
  27310. this._drawingContext = this._drawingCanvas.getContext("2d");
  27311. this._globalDiv.appendChild(this._drawingCanvas);
  27312. if (this._showUI) {
  27313. var background = "rgba(128, 128, 128, 0.4)";
  27314. var border = "rgb(180, 180, 180) solid 1px";
  27315. // Stats
  27316. this._statsDiv = document.createElement("div");
  27317. this._statsDiv.id = "DebugLayerStats";
  27318. this._statsDiv.style.border = border;
  27319. this._statsDiv.style.position = "absolute";
  27320. this._statsDiv.style.background = background;
  27321. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27322. this._generateheader(this._statsDiv, "STATISTICS");
  27323. this._statsSubsetDiv = document.createElement("div");
  27324. this._statsSubsetDiv.style.paddingTop = "5px";
  27325. this._statsSubsetDiv.style.paddingBottom = "5px";
  27326. this._statsSubsetDiv.style.overflowY = "auto";
  27327. this._statsDiv.appendChild(this._statsSubsetDiv);
  27328. // Tree
  27329. this._treeDiv = document.createElement("div");
  27330. this._treeDiv.id = "DebugLayerTree";
  27331. this._treeDiv.style.border = border;
  27332. this._treeDiv.style.position = "absolute";
  27333. this._treeDiv.style.background = background;
  27334. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27335. this._treeDiv.style.display = "none";
  27336. this._generateheader(this._treeDiv, "MESHES TREE");
  27337. this._treeSubsetDiv = document.createElement("div");
  27338. this._treeSubsetDiv.style.paddingTop = "5px";
  27339. this._treeSubsetDiv.style.paddingRight = "5px";
  27340. this._treeSubsetDiv.style.overflowY = "auto";
  27341. this._treeSubsetDiv.style.maxHeight = "300px";
  27342. this._treeDiv.appendChild(this._treeSubsetDiv);
  27343. this._needToRefreshMeshesTree = true;
  27344. // Logs
  27345. this._logDiv = document.createElement("div");
  27346. this._logDiv.style.border = border;
  27347. this._logDiv.id = "DebugLayerLogs";
  27348. this._logDiv.style.position = "absolute";
  27349. this._logDiv.style.background = background;
  27350. this._logDiv.style.padding = "0px 0px 0px 5px";
  27351. this._logDiv.style.display = "none";
  27352. this._generateheader(this._logDiv, "LOGS");
  27353. this._logSubsetDiv = document.createElement("div");
  27354. this._logSubsetDiv.style.height = "127px";
  27355. this._logSubsetDiv.style.paddingTop = "5px";
  27356. this._logSubsetDiv.style.overflowY = "auto";
  27357. this._logSubsetDiv.style.fontSize = "12px";
  27358. this._logSubsetDiv.style.fontFamily = "consolas";
  27359. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27360. this._logDiv.appendChild(this._logSubsetDiv);
  27361. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27362. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27363. };
  27364. // Options
  27365. this._optionsDiv = document.createElement("div");
  27366. this._optionsDiv.id = "DebugLayerOptions";
  27367. this._optionsDiv.style.border = border;
  27368. this._optionsDiv.style.position = "absolute";
  27369. this._optionsDiv.style.background = background;
  27370. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27371. this._optionsDiv.style.overflowY = "auto";
  27372. this._generateheader(this._optionsDiv, "OPTIONS");
  27373. this._optionsSubsetDiv = document.createElement("div");
  27374. this._optionsSubsetDiv.style.paddingTop = "5px";
  27375. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27376. this._optionsSubsetDiv.style.overflowY = "auto";
  27377. this._optionsSubsetDiv.style.maxHeight = "200px";
  27378. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27379. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27380. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27381. _this._displayStatistics = element.checked;
  27382. });
  27383. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27384. _this._displayLogs = element.checked;
  27385. });
  27386. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27387. _this._displayTree = element.checked;
  27388. _this._needToRefreshMeshesTree = true;
  27389. });
  27390. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27391. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27392. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27393. _this._scene.forceShowBoundingBoxes = element.checked;
  27394. });
  27395. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27396. _this._labelsEnabled = element.checked;
  27397. if (!_this._labelsEnabled) {
  27398. _this._clearLabels();
  27399. }
  27400. });
  27401. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27402. if (element.checked) {
  27403. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27404. }
  27405. else {
  27406. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27407. }
  27408. });
  27409. ;
  27410. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27411. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27412. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27413. if (element.checked) {
  27414. _this._scene.forceWireframe = false;
  27415. _this._scene.forcePointsCloud = false;
  27416. }
  27417. });
  27418. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27419. if (element.checked) {
  27420. _this._scene.forceWireframe = true;
  27421. _this._scene.forcePointsCloud = false;
  27422. }
  27423. });
  27424. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27425. if (element.checked) {
  27426. _this._scene.forceWireframe = false;
  27427. _this._scene.forcePointsCloud = true;
  27428. }
  27429. });
  27430. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27431. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27432. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27433. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27434. });
  27435. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27436. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27437. });
  27438. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27439. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27440. });
  27441. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27442. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27443. });
  27444. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27445. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27446. });
  27447. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27448. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27449. });
  27450. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27451. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27452. });
  27453. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27454. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27455. });
  27456. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27457. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27458. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27459. _this._scene.animationsEnabled = element.checked;
  27460. });
  27461. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27462. _this._scene.collisionsEnabled = element.checked;
  27463. });
  27464. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27465. _this._scene.fogEnabled = element.checked;
  27466. });
  27467. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27468. _this._scene.lensFlaresEnabled = element.checked;
  27469. });
  27470. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27471. _this._scene.lightsEnabled = element.checked;
  27472. });
  27473. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27474. _this._scene.particlesEnabled = element.checked;
  27475. });
  27476. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27477. _this._scene.postProcessesEnabled = element.checked;
  27478. });
  27479. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27480. _this._scene.proceduralTexturesEnabled = element.checked;
  27481. });
  27482. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27483. _this._scene.renderTargetsEnabled = element.checked;
  27484. });
  27485. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27486. _this._scene.shadowsEnabled = element.checked;
  27487. });
  27488. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27489. _this._scene.skeletonsEnabled = element.checked;
  27490. });
  27491. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27492. _this._scene.spritesEnabled = element.checked;
  27493. });
  27494. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27495. _this._scene.texturesEnabled = element.checked;
  27496. });
  27497. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27498. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27499. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27500. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", true, function (element) {
  27501. if (element.checked) {
  27502. _this._scene.switchAudioModeForHeadphones();
  27503. }
  27504. });
  27505. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", false, function (element) {
  27506. if (element.checked) {
  27507. _this._scene.switchAudioModeForNormalSpeakers();
  27508. }
  27509. });
  27510. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27511. _this._scene.audioEnabled = !element.checked;
  27512. });
  27513. }
  27514. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27515. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27516. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27517. _this._scene.dumpNextRenderTargets = true;
  27518. });
  27519. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27520. this._globalDiv.appendChild(this._statsDiv);
  27521. this._globalDiv.appendChild(this._logDiv);
  27522. this._globalDiv.appendChild(this._optionsDiv);
  27523. this._globalDiv.appendChild(this._treeDiv);
  27524. }
  27525. };
  27526. DebugLayer.prototype._displayStats = function () {
  27527. var scene = this._scene;
  27528. var engine = scene.getEngine();
  27529. var glInfo = engine.getGlInfo();
  27530. 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>";
  27531. if (this.customStatsFunction) {
  27532. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27533. }
  27534. };
  27535. return DebugLayer;
  27536. })();
  27537. BABYLON.DebugLayer = DebugLayer;
  27538. })(BABYLON || (BABYLON = {}));
  27539. //# sourceMappingURL=babylon.debugLayer.js.map
  27540. var BABYLON;
  27541. (function (BABYLON) {
  27542. var RawTexture = (function (_super) {
  27543. __extends(RawTexture, _super);
  27544. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27545. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27546. if (invertY === void 0) { invertY = false; }
  27547. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27548. _super.call(this, null, scene, !generateMipMaps, invertY);
  27549. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27550. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27551. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27552. }
  27553. // Statics
  27554. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27555. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27556. if (invertY === void 0) { invertY = false; }
  27557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27558. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27559. };
  27560. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27561. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27562. if (invertY === void 0) { invertY = false; }
  27563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27564. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27565. };
  27566. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27567. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27568. if (invertY === void 0) { invertY = false; }
  27569. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27570. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27571. };
  27572. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27573. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27574. if (invertY === void 0) { invertY = false; }
  27575. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27576. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27577. };
  27578. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27579. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27580. if (invertY === void 0) { invertY = false; }
  27581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27582. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27583. };
  27584. return RawTexture;
  27585. })(BABYLON.Texture);
  27586. BABYLON.RawTexture = RawTexture;
  27587. })(BABYLON || (BABYLON = {}));
  27588. //# sourceMappingURL=babylon.rawTexture.js.map
  27589. var BABYLON;
  27590. (function (BABYLON) {
  27591. var IndexedVector2 = (function (_super) {
  27592. __extends(IndexedVector2, _super);
  27593. function IndexedVector2(original, index) {
  27594. _super.call(this, original.x, original.y);
  27595. this.index = index;
  27596. }
  27597. return IndexedVector2;
  27598. })(BABYLON.Vector2);
  27599. var PolygonPoints = (function () {
  27600. function PolygonPoints() {
  27601. this.elements = new Array();
  27602. }
  27603. PolygonPoints.prototype.add = function (originalPoints) {
  27604. var _this = this;
  27605. var result = new Array();
  27606. originalPoints.forEach(function (point) {
  27607. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27608. var newPoint = new IndexedVector2(point, _this.elements.length);
  27609. result.push(newPoint);
  27610. _this.elements.push(newPoint);
  27611. }
  27612. });
  27613. return result;
  27614. };
  27615. PolygonPoints.prototype.computeBounds = function () {
  27616. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27617. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27618. this.elements.forEach(function (point) {
  27619. // x
  27620. if (point.x < lmin.x) {
  27621. lmin.x = point.x;
  27622. }
  27623. else if (point.x > lmax.x) {
  27624. lmax.x = point.x;
  27625. }
  27626. // y
  27627. if (point.y < lmin.y) {
  27628. lmin.y = point.y;
  27629. }
  27630. else if (point.y > lmax.y) {
  27631. lmax.y = point.y;
  27632. }
  27633. });
  27634. return {
  27635. min: lmin,
  27636. max: lmax,
  27637. width: lmax.x - lmin.x,
  27638. height: lmax.y - lmin.y
  27639. };
  27640. };
  27641. return PolygonPoints;
  27642. })();
  27643. var Polygon = (function () {
  27644. function Polygon() {
  27645. }
  27646. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27647. return [
  27648. new BABYLON.Vector2(xmin, ymin),
  27649. new BABYLON.Vector2(xmax, ymin),
  27650. new BABYLON.Vector2(xmax, ymax),
  27651. new BABYLON.Vector2(xmin, ymax)
  27652. ];
  27653. };
  27654. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27655. if (cx === void 0) { cx = 0; }
  27656. if (cy === void 0) { cy = 0; }
  27657. if (numberOfSides === void 0) { numberOfSides = 32; }
  27658. var result = new Array();
  27659. var angle = 0;
  27660. var increment = (Math.PI * 2) / numberOfSides;
  27661. for (var i = 0; i < numberOfSides; i++) {
  27662. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27663. angle -= increment;
  27664. }
  27665. return result;
  27666. };
  27667. Polygon.Parse = function (input) {
  27668. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27669. var i, result = [];
  27670. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27671. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27672. }
  27673. return result;
  27674. };
  27675. Polygon.StartingAt = function (x, y) {
  27676. return BABYLON.Path2.StartingAt(x, y);
  27677. };
  27678. return Polygon;
  27679. })();
  27680. BABYLON.Polygon = Polygon;
  27681. var PolygonMeshBuilder = (function () {
  27682. function PolygonMeshBuilder(name, contours, scene) {
  27683. this._points = new PolygonPoints();
  27684. if (!("poly2tri" in window)) {
  27685. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27686. }
  27687. this._name = name;
  27688. this._scene = scene;
  27689. var points;
  27690. if (contours instanceof BABYLON.Path2) {
  27691. points = contours.getPoints();
  27692. }
  27693. else {
  27694. points = contours;
  27695. }
  27696. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27697. }
  27698. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27699. this._swctx.addHole(this._points.add(hole));
  27700. return this;
  27701. };
  27702. PolygonMeshBuilder.prototype.build = function (updatable) {
  27703. if (updatable === void 0) { updatable = false; }
  27704. var result = new BABYLON.Mesh(this._name, this._scene);
  27705. var normals = [];
  27706. var positions = [];
  27707. var uvs = [];
  27708. var bounds = this._points.computeBounds();
  27709. this._points.elements.forEach(function (p) {
  27710. normals.push(0, 1.0, 0);
  27711. positions.push(p.x, 0, p.y);
  27712. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27713. });
  27714. var indices = [];
  27715. this._swctx.triangulate();
  27716. this._swctx.getTriangles().forEach(function (triangle) {
  27717. triangle.getPoints().forEach(function (point) {
  27718. indices.push(point.index);
  27719. });
  27720. });
  27721. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27722. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27723. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27724. result.setIndices(indices);
  27725. return result;
  27726. };
  27727. return PolygonMeshBuilder;
  27728. })();
  27729. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27730. })(BABYLON || (BABYLON = {}));
  27731. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27732. (function (BABYLON) {
  27733. var SimplificationSettings = (function () {
  27734. function SimplificationSettings(quality, distance) {
  27735. this.quality = quality;
  27736. this.distance = distance;
  27737. }
  27738. return SimplificationSettings;
  27739. })();
  27740. BABYLON.SimplificationSettings = SimplificationSettings;
  27741. var SimplificationQueue = (function () {
  27742. function SimplificationQueue() {
  27743. this.running = false;
  27744. this._simplificationArray = [];
  27745. }
  27746. SimplificationQueue.prototype.addTask = function (task) {
  27747. this._simplificationArray.push(task);
  27748. };
  27749. SimplificationQueue.prototype.executeNext = function () {
  27750. var task = this._simplificationArray.pop();
  27751. if (task) {
  27752. this.running = true;
  27753. this.runSimplification(task);
  27754. }
  27755. else {
  27756. this.running = false;
  27757. }
  27758. };
  27759. SimplificationQueue.prototype.runSimplification = function (task) {
  27760. var _this = this;
  27761. function setLODLevel(distance, mesh) {
  27762. }
  27763. if (task.parallelProcessing) {
  27764. //parallel simplifier
  27765. task.settings.forEach(function (setting) {
  27766. var simplifier = _this.getSimplifier(task);
  27767. simplifier.simplify(setting, function (newMesh) {
  27768. task.mesh.addLODLevel(setting.distance, newMesh);
  27769. //check if it is the last
  27770. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27771. //all done, run the success callback.
  27772. task.successCallback();
  27773. }
  27774. _this.executeNext();
  27775. });
  27776. });
  27777. }
  27778. else {
  27779. //single simplifier.
  27780. var simplifier = this.getSimplifier(task);
  27781. var runDecimation = function (setting, callback) {
  27782. simplifier.simplify(setting, function (newMesh) {
  27783. task.mesh.addLODLevel(setting.distance, newMesh);
  27784. //run the next quality level
  27785. callback();
  27786. });
  27787. };
  27788. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27789. runDecimation(task.settings[loop.index], function () {
  27790. loop.executeNext();
  27791. });
  27792. }, function () {
  27793. //execution ended, run the success callback.
  27794. if (task.successCallback) {
  27795. task.successCallback();
  27796. }
  27797. _this.executeNext();
  27798. });
  27799. }
  27800. };
  27801. SimplificationQueue.prototype.getSimplifier = function (task) {
  27802. switch (task.simplificationType) {
  27803. case 0 /* QUADRATIC */:
  27804. default:
  27805. return new QuadraticErrorSimplification(task.mesh);
  27806. }
  27807. };
  27808. return SimplificationQueue;
  27809. })();
  27810. BABYLON.SimplificationQueue = SimplificationQueue;
  27811. /**
  27812. * The implemented types of simplification.
  27813. * At the moment only Quadratic Error Decimation is implemented.
  27814. */
  27815. (function (SimplificationType) {
  27816. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27817. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27818. var SimplificationType = BABYLON.SimplificationType;
  27819. var DecimationTriangle = (function () {
  27820. function DecimationTriangle(vertices) {
  27821. this.vertices = vertices;
  27822. this.error = new Array(4);
  27823. this.deleted = false;
  27824. this.isDirty = false;
  27825. this.borderFactor = 0;
  27826. }
  27827. return DecimationTriangle;
  27828. })();
  27829. BABYLON.DecimationTriangle = DecimationTriangle;
  27830. var DecimationVertex = (function () {
  27831. function DecimationVertex(position, normal, uv, id) {
  27832. this.position = position;
  27833. this.normal = normal;
  27834. this.uv = uv;
  27835. this.id = id;
  27836. this.isBorder = true;
  27837. this.q = new QuadraticMatrix();
  27838. this.triangleCount = 0;
  27839. this.triangleStart = 0;
  27840. }
  27841. return DecimationVertex;
  27842. })();
  27843. BABYLON.DecimationVertex = DecimationVertex;
  27844. var QuadraticMatrix = (function () {
  27845. function QuadraticMatrix(data) {
  27846. this.data = new Array(10);
  27847. for (var i = 0; i < 10; ++i) {
  27848. if (data && data[i]) {
  27849. this.data[i] = data[i];
  27850. }
  27851. else {
  27852. this.data[i] = 0;
  27853. }
  27854. }
  27855. }
  27856. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27857. 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];
  27858. return det;
  27859. };
  27860. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27861. for (var i = 0; i < 10; ++i) {
  27862. this.data[i] += matrix.data[i];
  27863. }
  27864. };
  27865. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27866. for (var i = 0; i < 10; ++i) {
  27867. this.data[i] += data[i];
  27868. }
  27869. };
  27870. QuadraticMatrix.prototype.add = function (matrix) {
  27871. var m = new QuadraticMatrix();
  27872. for (var i = 0; i < 10; ++i) {
  27873. m.data[i] = this.data[i] + matrix.data[i];
  27874. }
  27875. return m;
  27876. };
  27877. QuadraticMatrix.FromData = function (a, b, c, d) {
  27878. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27879. };
  27880. //returning an array to avoid garbage collection
  27881. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27882. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27883. };
  27884. return QuadraticMatrix;
  27885. })();
  27886. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27887. var Reference = (function () {
  27888. function Reference(vertexId, triangleId) {
  27889. this.vertexId = vertexId;
  27890. this.triangleId = triangleId;
  27891. }
  27892. return Reference;
  27893. })();
  27894. BABYLON.Reference = Reference;
  27895. /**
  27896. * An implementation of the Quadratic Error simplification algorithm.
  27897. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27898. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27899. * @author RaananW
  27900. */
  27901. var QuadraticErrorSimplification = (function () {
  27902. function QuadraticErrorSimplification(_mesh) {
  27903. this._mesh = _mesh;
  27904. this.initialised = false;
  27905. this.syncIterations = 5000;
  27906. this.aggressiveness = 7;
  27907. this.decimationIterations = 100;
  27908. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  27909. }
  27910. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27911. var _this = this;
  27912. this.initDecimatedMesh();
  27913. //iterating through the submeshes array, one after the other.
  27914. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  27915. _this.initWithMesh(_this._mesh, loop.index, function () {
  27916. _this.runDecimation(settings, loop.index, function () {
  27917. loop.executeNext();
  27918. });
  27919. });
  27920. }, function () {
  27921. setTimeout(function () {
  27922. _this._reconstructedMesh.isVisible = true;
  27923. successCallback(_this._reconstructedMesh);
  27924. }, 0);
  27925. });
  27926. };
  27927. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  27928. var _this = this;
  27929. var gCount = 0;
  27930. triangle.vertices.forEach(function (vId) {
  27931. var count = 0;
  27932. var vPos = _this.vertices[vId].position;
  27933. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  27934. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  27935. ++count;
  27936. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  27937. ++count;
  27938. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  27939. ++count;
  27940. if (count > 1) {
  27941. ++gCount;
  27942. }
  27943. ;
  27944. });
  27945. if (gCount > 1) {
  27946. console.log(triangle, gCount);
  27947. }
  27948. return gCount > 1;
  27949. };
  27950. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  27951. var _this = this;
  27952. var targetCount = ~~(this.triangles.length * settings.quality);
  27953. var deletedTriangles = 0;
  27954. var triangleCount = this.triangles.length;
  27955. var iterationFunction = function (iteration, callback) {
  27956. setTimeout(function () {
  27957. if (iteration % 5 === 0) {
  27958. _this.updateMesh(iteration === 0);
  27959. }
  27960. for (var i = 0; i < _this.triangles.length; ++i) {
  27961. _this.triangles[i].isDirty = false;
  27962. }
  27963. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27964. var trianglesIterator = function (i) {
  27965. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27966. var t = _this.triangles[tIdx];
  27967. if (!t)
  27968. return;
  27969. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27970. return;
  27971. }
  27972. for (var j = 0; j < 3; ++j) {
  27973. if (t.error[j] < threshold) {
  27974. var deleted0 = [];
  27975. var deleted1 = [];
  27976. var i0 = t.vertices[j];
  27977. var i1 = t.vertices[(j + 1) % 3];
  27978. var v0 = _this.vertices[i0];
  27979. var v1 = _this.vertices[i1];
  27980. if (v0.isBorder !== v1.isBorder)
  27981. continue;
  27982. var p = BABYLON.Vector3.Zero();
  27983. var n = BABYLON.Vector3.Zero();
  27984. var uv = BABYLON.Vector2.Zero();
  27985. var color = new BABYLON.Color4(0, 0, 0, 1);
  27986. _this.calculateError(v0, v1, p, n, uv, color);
  27987. var delTr = [];
  27988. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27989. continue;
  27990. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27991. continue;
  27992. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27993. continue;
  27994. }
  27995. v0.normal = n;
  27996. if (v0.uv)
  27997. v0.uv = uv;
  27998. else if (v0.color)
  27999. v0.color = color;
  28000. v0.q = v1.q.add(v0.q);
  28001. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28002. continue;
  28003. if (p.equals(v0.position))
  28004. continue;
  28005. v0.position = p;
  28006. var tStart = _this.references.length;
  28007. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28008. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28009. var tCount = _this.references.length - tStart;
  28010. if (tCount <= v0.triangleCount) {
  28011. if (tCount) {
  28012. for (var c = 0; c < tCount; c++) {
  28013. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28014. }
  28015. }
  28016. }
  28017. else {
  28018. v0.triangleStart = tStart;
  28019. }
  28020. v0.triangleCount = tCount;
  28021. break;
  28022. }
  28023. }
  28024. };
  28025. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28026. return (triangleCount - deletedTriangles <= targetCount);
  28027. });
  28028. }, 0);
  28029. };
  28030. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28031. if (triangleCount - deletedTriangles <= targetCount)
  28032. loop.breakLoop();
  28033. else {
  28034. iterationFunction(loop.index, function () {
  28035. loop.executeNext();
  28036. });
  28037. }
  28038. }, function () {
  28039. setTimeout(function () {
  28040. //reconstruct this part of the mesh
  28041. _this.reconstructMesh(submeshIndex);
  28042. successCallback();
  28043. }, 0);
  28044. });
  28045. };
  28046. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28047. var _this = this;
  28048. if (!mesh)
  28049. return;
  28050. this.vertices = [];
  28051. this.triangles = [];
  28052. this._mesh = mesh;
  28053. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28054. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28055. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28056. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28057. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28058. var indices = mesh.getIndices();
  28059. var submesh = mesh.subMeshes[submeshIndex];
  28060. var vertexInit = function (i) {
  28061. var offset = i + submesh.verticesStart;
  28062. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28063. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28064. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28065. }
  28066. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28067. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28068. }
  28069. _this.vertices.push(vertex);
  28070. };
  28071. //var totalVertices = mesh.getTotalVertices();
  28072. var totalVertices = submesh.verticesCount;
  28073. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28074. var indicesInit = function (i) {
  28075. var offset = (submesh.indexStart / 3) + i;
  28076. var pos = (offset * 3);
  28077. var i0 = indices[pos + 0] - submesh.verticesStart;
  28078. var i1 = indices[pos + 1] - submesh.verticesStart;
  28079. var i2 = indices[pos + 2] - submesh.verticesStart;
  28080. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28081. _this.triangles.push(triangle);
  28082. };
  28083. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28084. _this.init(callback);
  28085. });
  28086. });
  28087. };
  28088. QuadraticErrorSimplification.prototype.init = function (callback) {
  28089. var _this = this;
  28090. var triangleInit1 = function (i) {
  28091. var t = _this.triangles[i];
  28092. 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();
  28093. for (var j = 0; j < 3; j++) {
  28094. _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))));
  28095. }
  28096. };
  28097. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28098. var triangleInit2 = function (i) {
  28099. var t = _this.triangles[i];
  28100. for (var j = 0; j < 3; ++j) {
  28101. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28102. }
  28103. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28104. };
  28105. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28106. _this.initialised = true;
  28107. callback();
  28108. });
  28109. });
  28110. };
  28111. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28112. var newTriangles = [];
  28113. var i;
  28114. for (i = 0; i < this.vertices.length; ++i) {
  28115. this.vertices[i].triangleCount = 0;
  28116. }
  28117. var t;
  28118. var j;
  28119. for (i = 0; i < this.triangles.length; ++i) {
  28120. if (!this.triangles[i].deleted) {
  28121. t = this.triangles[i];
  28122. for (j = 0; j < 3; ++j) {
  28123. this.vertices[t.vertices[j]].triangleCount = 1;
  28124. }
  28125. newTriangles.push(t);
  28126. }
  28127. }
  28128. var newVerticesOrder = [];
  28129. //compact vertices, get the IDs of the vertices used.
  28130. var dst = 0;
  28131. for (i = 0; i < this.vertices.length; ++i) {
  28132. if (this.vertices[i].triangleCount) {
  28133. this.vertices[i].triangleStart = dst;
  28134. this.vertices[dst].position = this.vertices[i].position;
  28135. this.vertices[dst].normal = this.vertices[i].normal;
  28136. this.vertices[dst].uv = this.vertices[i].uv;
  28137. this.vertices[dst].color = this.vertices[i].color;
  28138. newVerticesOrder.push(i);
  28139. dst++;
  28140. }
  28141. }
  28142. for (i = 0; i < newTriangles.length; ++i) {
  28143. t = newTriangles[i];
  28144. for (j = 0; j < 3; ++j) {
  28145. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28146. }
  28147. }
  28148. this.vertices = this.vertices.slice(0, dst);
  28149. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28150. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28151. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28152. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28153. for (i = 0; i < newVerticesOrder.length; ++i) {
  28154. newPositionData.push(this.vertices[i].position.x);
  28155. newPositionData.push(this.vertices[i].position.y);
  28156. newPositionData.push(this.vertices[i].position.z);
  28157. newNormalData.push(this.vertices[i].normal.x);
  28158. newNormalData.push(this.vertices[i].normal.y);
  28159. newNormalData.push(this.vertices[i].normal.z);
  28160. if (this.vertices[i].uv) {
  28161. newUVsData.push(this.vertices[i].uv.x);
  28162. newUVsData.push(this.vertices[i].uv.y);
  28163. }
  28164. else if (this.vertices[i].color) {
  28165. newColorsData.push(this.vertices[i].color.r);
  28166. newColorsData.push(this.vertices[i].color.g);
  28167. newColorsData.push(this.vertices[i].color.b);
  28168. newColorsData.push(this.vertices[i].color.a);
  28169. }
  28170. }
  28171. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28172. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28173. var submeshesArray = this._reconstructedMesh.subMeshes;
  28174. this._reconstructedMesh.subMeshes = [];
  28175. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28176. for (i = 0; i < newTriangles.length; ++i) {
  28177. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28178. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28179. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28180. }
  28181. //overwriting the old vertex buffers and indices.
  28182. this._reconstructedMesh.setIndices(newIndicesArray);
  28183. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28184. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28185. if (newUVsData.length > 0)
  28186. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28187. if (newColorsData.length > 0)
  28188. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28189. //create submesh
  28190. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28191. if (submeshIndex > 0) {
  28192. this._reconstructedMesh.subMeshes = [];
  28193. submeshesArray.forEach(function (submesh) {
  28194. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28195. });
  28196. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28197. }
  28198. };
  28199. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28200. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28201. this._reconstructedMesh.material = this._mesh.material;
  28202. this._reconstructedMesh.parent = this._mesh.parent;
  28203. this._reconstructedMesh.isVisible = false;
  28204. };
  28205. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28206. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28207. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28208. if (t.deleted)
  28209. continue;
  28210. var s = this.references[vertex1.triangleStart + i].vertexId;
  28211. var id1 = t.vertices[(s + 1) % 3];
  28212. var id2 = t.vertices[(s + 2) % 3];
  28213. if ((id1 === index2 || id2 === index2)) {
  28214. deletedArray[i] = true;
  28215. delTr.push(t);
  28216. continue;
  28217. }
  28218. var d1 = this.vertices[id1].position.subtract(point);
  28219. d1 = d1.normalize();
  28220. var d2 = this.vertices[id2].position.subtract(point);
  28221. d2 = d2.normalize();
  28222. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28223. return true;
  28224. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28225. deletedArray[i] = false;
  28226. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28227. return true;
  28228. }
  28229. return false;
  28230. };
  28231. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28232. var newDeleted = deletedTriangles;
  28233. for (var i = 0; i < vertex.triangleCount; ++i) {
  28234. var ref = this.references[vertex.triangleStart + i];
  28235. var t = this.triangles[ref.triangleId];
  28236. if (t.deleted)
  28237. continue;
  28238. if (deletedArray[i]) {
  28239. t.deleted = true;
  28240. newDeleted++;
  28241. continue;
  28242. }
  28243. t.vertices[ref.vertexId] = vertexId;
  28244. t.isDirty = true;
  28245. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28246. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28247. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28248. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28249. this.references.push(ref);
  28250. }
  28251. return newDeleted;
  28252. };
  28253. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28254. for (var i = 0; i < this.vertices.length; ++i) {
  28255. var vCount = [];
  28256. var vId = [];
  28257. var v = this.vertices[i];
  28258. var j;
  28259. for (j = 0; j < v.triangleCount; ++j) {
  28260. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28261. for (var ii = 0; ii < 3; ii++) {
  28262. var ofs = 0;
  28263. var id = triangle.vertices[ii];
  28264. while (ofs < vCount.length) {
  28265. if (vId[ofs] === id)
  28266. break;
  28267. ++ofs;
  28268. }
  28269. if (ofs === vCount.length) {
  28270. vCount.push(1);
  28271. vId.push(id);
  28272. }
  28273. else {
  28274. vCount[ofs]++;
  28275. }
  28276. }
  28277. }
  28278. for (j = 0; j < vCount.length; ++j) {
  28279. if (vCount[j] === 1) {
  28280. this.vertices[vId[j]].isBorder = true;
  28281. }
  28282. else {
  28283. this.vertices[vId[j]].isBorder = false;
  28284. }
  28285. }
  28286. }
  28287. };
  28288. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28289. if (identifyBorders === void 0) { identifyBorders = false; }
  28290. var i;
  28291. if (!identifyBorders) {
  28292. var newTrianglesVector = [];
  28293. for (i = 0; i < this.triangles.length; ++i) {
  28294. if (!this.triangles[i].deleted) {
  28295. newTrianglesVector.push(this.triangles[i]);
  28296. }
  28297. }
  28298. this.triangles = newTrianglesVector;
  28299. }
  28300. for (i = 0; i < this.vertices.length; ++i) {
  28301. this.vertices[i].triangleCount = 0;
  28302. this.vertices[i].triangleStart = 0;
  28303. }
  28304. var t;
  28305. var j;
  28306. var v;
  28307. for (i = 0; i < this.triangles.length; ++i) {
  28308. t = this.triangles[i];
  28309. for (j = 0; j < 3; ++j) {
  28310. v = this.vertices[t.vertices[j]];
  28311. v.triangleCount++;
  28312. }
  28313. }
  28314. var tStart = 0;
  28315. for (i = 0; i < this.vertices.length; ++i) {
  28316. this.vertices[i].triangleStart = tStart;
  28317. tStart += this.vertices[i].triangleCount;
  28318. this.vertices[i].triangleCount = 0;
  28319. }
  28320. var newReferences = new Array(this.triangles.length * 3);
  28321. for (i = 0; i < this.triangles.length; ++i) {
  28322. t = this.triangles[i];
  28323. for (j = 0; j < 3; ++j) {
  28324. v = this.vertices[t.vertices[j]];
  28325. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28326. v.triangleCount++;
  28327. }
  28328. }
  28329. this.references = newReferences;
  28330. if (identifyBorders) {
  28331. this.identifyBorder();
  28332. }
  28333. };
  28334. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28335. var x = point.x;
  28336. var y = point.y;
  28337. var z = point.z;
  28338. 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];
  28339. };
  28340. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28341. var q = vertex1.q.add(vertex2.q);
  28342. var border = vertex1.isBorder && vertex2.isBorder;
  28343. var error = 0;
  28344. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28345. if (qDet !== 0 && !border) {
  28346. if (!pointResult) {
  28347. pointResult = BABYLON.Vector3.Zero();
  28348. }
  28349. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28350. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28351. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28352. error = this.vertexError(q, pointResult);
  28353. //TODO this should be correctly calculated
  28354. if (normalResult) {
  28355. normalResult.copyFrom(vertex1.normal);
  28356. if (vertex1.uv)
  28357. uvResult.copyFrom(vertex1.uv);
  28358. else if (vertex1.color)
  28359. colorResult.copyFrom(vertex1.color);
  28360. }
  28361. }
  28362. else {
  28363. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28364. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28365. var error1 = this.vertexError(q, vertex1.position);
  28366. var error2 = this.vertexError(q, vertex2.position);
  28367. var error3 = this.vertexError(q, p3);
  28368. error = Math.min(error1, error2, error3);
  28369. if (error === error1) {
  28370. if (pointResult) {
  28371. pointResult.copyFrom(vertex1.position);
  28372. normalResult.copyFrom(vertex1.normal);
  28373. if (vertex1.uv)
  28374. uvResult.copyFrom(vertex1.uv);
  28375. else if (vertex1.color)
  28376. colorResult.copyFrom(vertex1.color);
  28377. }
  28378. }
  28379. else if (error === error2) {
  28380. if (pointResult) {
  28381. pointResult.copyFrom(vertex2.position);
  28382. normalResult.copyFrom(vertex2.normal);
  28383. if (vertex2.uv)
  28384. uvResult.copyFrom(vertex2.uv);
  28385. else if (vertex2.color)
  28386. colorResult.copyFrom(vertex2.color);
  28387. }
  28388. }
  28389. else {
  28390. if (pointResult) {
  28391. pointResult.copyFrom(p3);
  28392. normalResult.copyFrom(vertex1.normal);
  28393. if (vertex1.uv)
  28394. uvResult.copyFrom(vertex1.uv);
  28395. else if (vertex1.color)
  28396. colorResult.copyFrom(vertex1.color);
  28397. }
  28398. }
  28399. }
  28400. return error;
  28401. };
  28402. return QuadraticErrorSimplification;
  28403. })();
  28404. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28405. })(BABYLON || (BABYLON = {}));
  28406. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28407. (function (BABYLON) {
  28408. var Analyser = (function () {
  28409. function Analyser(scene) {
  28410. this.SMOOTHING = 0.75;
  28411. this.FFT_SIZE = 512;
  28412. this.BARGRAPHAMPLITUDE = 256;
  28413. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28414. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28415. this._scene = scene;
  28416. this._audioEngine = BABYLON.Engine.audioEngine;
  28417. if (this._audioEngine.canUseWebAudio) {
  28418. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28419. this._webAudioAnalyser.minDecibels = -140;
  28420. this._webAudioAnalyser.maxDecibels = 0;
  28421. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28422. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28423. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28424. }
  28425. }
  28426. Analyser.prototype.getFrequencyBinCount = function () {
  28427. if (this._audioEngine.canUseWebAudio) {
  28428. return this._webAudioAnalyser.frequencyBinCount;
  28429. }
  28430. else {
  28431. return 0;
  28432. }
  28433. };
  28434. Analyser.prototype.getByteFrequencyData = function () {
  28435. if (this._audioEngine.canUseWebAudio) {
  28436. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28437. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28438. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28439. }
  28440. return this._byteFreqs;
  28441. };
  28442. Analyser.prototype.getByteTimeDomainData = function () {
  28443. if (this._audioEngine.canUseWebAudio) {
  28444. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28445. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28446. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28447. }
  28448. return this._byteTime;
  28449. };
  28450. Analyser.prototype.getFloatFrequencyData = function () {
  28451. if (this._audioEngine.canUseWebAudio) {
  28452. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28453. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28454. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28455. }
  28456. return this._floatFreqs;
  28457. };
  28458. Analyser.prototype.drawDebugCanvas = function () {
  28459. var _this = this;
  28460. if (this._audioEngine.canUseWebAudio) {
  28461. if (!this._debugCanvas) {
  28462. this._debugCanvas = document.createElement("canvas");
  28463. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28464. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28465. this._debugCanvas.style.position = "absolute";
  28466. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28467. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28468. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28469. document.body.appendChild(this._debugCanvas);
  28470. this._registerFunc = function () {
  28471. _this.drawDebugCanvas();
  28472. };
  28473. this._scene.registerBeforeRender(this._registerFunc);
  28474. }
  28475. if (this._registerFunc) {
  28476. var workingArray = this.getByteFrequencyData();
  28477. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28478. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28479. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28480. var value = workingArray[i];
  28481. var percent = value / this.BARGRAPHAMPLITUDE;
  28482. var height = this.DEBUGCANVASSIZE.height * percent;
  28483. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28484. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28485. var hue = i / this.getFrequencyBinCount() * 360;
  28486. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28487. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28488. }
  28489. }
  28490. }
  28491. };
  28492. Analyser.prototype.stopDebugCanvas = function () {
  28493. if (this._debugCanvas) {
  28494. this._scene.unregisterBeforeRender(this._registerFunc);
  28495. this._registerFunc = null;
  28496. document.body.removeChild(this._debugCanvas);
  28497. this._debugCanvas = null;
  28498. this._debugCanvasContext = null;
  28499. }
  28500. };
  28501. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28502. if (this._audioEngine.canUseWebAudio) {
  28503. inputAudioNode.connect(this._webAudioAnalyser);
  28504. this._webAudioAnalyser.connect(outputAudioNode);
  28505. }
  28506. };
  28507. Analyser.prototype.dispose = function () {
  28508. if (this._audioEngine.canUseWebAudio) {
  28509. this._webAudioAnalyser.disconnect();
  28510. }
  28511. };
  28512. return Analyser;
  28513. })();
  28514. BABYLON.Analyser = Analyser;
  28515. })(BABYLON || (BABYLON = {}));
  28516. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28517. (function (BABYLON) {
  28518. var DepthRenderer = (function () {
  28519. function DepthRenderer(scene, type) {
  28520. var _this = this;
  28521. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28522. this._viewMatrix = BABYLON.Matrix.Zero();
  28523. this._projectionMatrix = BABYLON.Matrix.Zero();
  28524. this._transformMatrix = BABYLON.Matrix.Zero();
  28525. this._worldViewProjection = BABYLON.Matrix.Zero();
  28526. this._scene = scene;
  28527. var engine = scene.getEngine();
  28528. // Render target
  28529. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28530. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28531. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28532. this._depthMap.refreshRate = 1;
  28533. this._depthMap.renderParticles = false;
  28534. this._depthMap.renderList = null;
  28535. // Custom render function
  28536. var renderSubMesh = function (subMesh) {
  28537. var mesh = subMesh.getRenderingMesh();
  28538. var scene = _this._scene;
  28539. var engine = scene.getEngine();
  28540. // Culling
  28541. engine.setState(subMesh.getMaterial().backFaceCulling);
  28542. // Managing instances
  28543. var batch = mesh._getInstancesRenderList(subMesh._id);
  28544. if (batch.mustReturn) {
  28545. return;
  28546. }
  28547. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28548. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28549. engine.enableEffect(_this._effect);
  28550. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28551. var material = subMesh.getMaterial();
  28552. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28553. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28554. // Alpha test
  28555. if (material && material.needAlphaTesting()) {
  28556. var alphaTexture = material.getAlphaTestTexture();
  28557. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28558. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28559. }
  28560. // Bones
  28561. if (mesh.useBones) {
  28562. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28563. }
  28564. // Draw
  28565. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28566. }
  28567. };
  28568. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28569. var index;
  28570. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28571. renderSubMesh(opaqueSubMeshes.data[index]);
  28572. }
  28573. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28574. renderSubMesh(alphaTestSubMeshes.data[index]);
  28575. }
  28576. };
  28577. }
  28578. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28579. var defines = [];
  28580. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28581. var mesh = subMesh.getMesh();
  28582. var scene = mesh.getScene();
  28583. var material = subMesh.getMaterial();
  28584. // Alpha test
  28585. if (material && material.needAlphaTesting()) {
  28586. defines.push("#define ALPHATEST");
  28587. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28588. attribs.push(BABYLON.VertexBuffer.UVKind);
  28589. defines.push("#define UV1");
  28590. }
  28591. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28592. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28593. defines.push("#define UV2");
  28594. }
  28595. }
  28596. // Bones
  28597. if (mesh.useBones) {
  28598. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28599. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28600. defines.push("#define BONES");
  28601. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28602. }
  28603. // Instances
  28604. if (useInstances) {
  28605. defines.push("#define INSTANCES");
  28606. attribs.push("world0");
  28607. attribs.push("world1");
  28608. attribs.push("world2");
  28609. attribs.push("world3");
  28610. }
  28611. // Get correct effect
  28612. var join = defines.join("\n");
  28613. if (this._cachedDefines !== join) {
  28614. this._cachedDefines = join;
  28615. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28616. }
  28617. return this._effect.isReady();
  28618. };
  28619. DepthRenderer.prototype.getDepthMap = function () {
  28620. return this._depthMap;
  28621. };
  28622. // Methods
  28623. DepthRenderer.prototype.dispose = function () {
  28624. this._depthMap.dispose();
  28625. };
  28626. return DepthRenderer;
  28627. })();
  28628. BABYLON.DepthRenderer = DepthRenderer;
  28629. })(BABYLON || (BABYLON = {}));
  28630. //# sourceMappingURL=babylon.depthRenderer.js.map
  28631. var BABYLON;
  28632. (function (BABYLON) {
  28633. var SSAORenderingPipeline = (function (_super) {
  28634. __extends(SSAORenderingPipeline, _super);
  28635. /**
  28636. * @constructor
  28637. * @param {string} name - The rendering pipeline name
  28638. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28639. * @param {any} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28640. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28641. */
  28642. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28643. var _this = this;
  28644. _super.call(this, scene.getEngine(), name);
  28645. // Members
  28646. /**
  28647. * The PassPostProcess id in the pipeline that contains the original scene color
  28648. * @type {string}
  28649. */
  28650. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28651. /**
  28652. * The SSAO PostProcess id in the pipeline
  28653. * @type {string}
  28654. */
  28655. this.SSAORenderEffect = "SSAORenderEffect";
  28656. /**
  28657. * The horizontal blur PostProcess id in the pipeline
  28658. * @type {string}
  28659. */
  28660. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28661. /**
  28662. * The vertical blur PostProcess id in the pipeline
  28663. * @type {string}
  28664. */
  28665. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28666. /**
  28667. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28668. * @type {string}
  28669. */
  28670. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28671. this._firstUpdate = true;
  28672. this._scene = scene;
  28673. // Set up assets
  28674. this._createRandomTexture();
  28675. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28676. var ssaoRatio = ratio.ssaoRatio || ratio;
  28677. var combineRatio = ratio.combineRatio || ratio;
  28678. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28679. this._createSSAOPostProcess(ssaoRatio);
  28680. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28681. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28682. this._createSSAOCombinePostProcess(combineRatio);
  28683. // Set up pipeline
  28684. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28685. return _this._originalColorPostProcess;
  28686. }, true));
  28687. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28688. return _this._ssaoPostProcess;
  28689. }, true));
  28690. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28691. return _this._blurHPostProcess;
  28692. }, true));
  28693. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28694. return _this._blurVPostProcess;
  28695. }, true));
  28696. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28697. return _this._ssaoCombinePostProcess;
  28698. }, true));
  28699. // Finish
  28700. scene.postProcessRenderPipelineManager.addPipeline(this);
  28701. if (cameras)
  28702. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28703. }
  28704. // Public Methods
  28705. /**
  28706. * Returns the horizontal blur PostProcess
  28707. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28708. */
  28709. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28710. return this._blurHPostProcess;
  28711. };
  28712. /**
  28713. * Returns the vertical blur PostProcess
  28714. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28715. */
  28716. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28717. return this._blurVPostProcess;
  28718. };
  28719. /**
  28720. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28721. */
  28722. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28723. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28724. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28725. this._originalColorPostProcess = undefined;
  28726. this._ssaoPostProcess = undefined;
  28727. this._blurHPostProcess = undefined;
  28728. this._blurVPostProcess = undefined;
  28729. this._ssaoCombinePostProcess = undefined;
  28730. this._randomTexture.dispose();
  28731. if (disableDepthRender)
  28732. this._scene.disableDepthRenderer();
  28733. };
  28734. // Private Methods
  28735. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28736. var _this = this;
  28737. var sampleSphere = [
  28738. 0.5381,
  28739. 0.1856,
  28740. -0.4319,
  28741. 0.1379,
  28742. 0.2486,
  28743. 0.4430,
  28744. 0.3371,
  28745. 0.5679,
  28746. -0.0057,
  28747. -0.6999,
  28748. -0.0451,
  28749. -0.0019,
  28750. 0.0689,
  28751. -0.1598,
  28752. -0.8547,
  28753. 0.0560,
  28754. 0.0069,
  28755. -0.1843,
  28756. -0.0146,
  28757. 0.1402,
  28758. 0.0762,
  28759. 0.0100,
  28760. -0.1924,
  28761. -0.0344,
  28762. -0.3577,
  28763. -0.5301,
  28764. -0.4358,
  28765. -0.3169,
  28766. 0.1063,
  28767. 0.0158,
  28768. 0.0103,
  28769. -0.5869,
  28770. 0.0046,
  28771. -0.0897,
  28772. -0.4940,
  28773. 0.3287,
  28774. 0.7119,
  28775. -0.0154,
  28776. -0.0918,
  28777. -0.0533,
  28778. 0.0596,
  28779. -0.5411,
  28780. 0.0352,
  28781. -0.0631,
  28782. 0.5460,
  28783. -0.4776,
  28784. 0.2847,
  28785. -0.0271
  28786. ];
  28787. var samplesFactor = 1.0 / 16.0;
  28788. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28789. this._ssaoPostProcess.onApply = function (effect) {
  28790. if (_this._firstUpdate) {
  28791. effect.setArray3("sampleSphere", sampleSphere);
  28792. effect.setFloat("samplesFactor", samplesFactor);
  28793. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28794. _this._firstUpdate = false;
  28795. }
  28796. effect.setTexture("textureSampler", _this._depthTexture);
  28797. effect.setTexture("randomSampler", _this._randomTexture);
  28798. };
  28799. };
  28800. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28801. var _this = this;
  28802. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28803. this._ssaoCombinePostProcess.onApply = function (effect) {
  28804. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28805. };
  28806. };
  28807. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28808. var size = 512;
  28809. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28810. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28811. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28812. var context = this._randomTexture.getContext();
  28813. var rand = function (min, max) {
  28814. return Math.random() * (max - min) + min;
  28815. };
  28816. for (var x = 0; x < size; x++) {
  28817. for (var y = 0; y < size; y++) {
  28818. var randVector = BABYLON.Vector3.Zero();
  28819. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28820. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28821. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28822. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28823. context.fillRect(x, y, 1, 1);
  28824. }
  28825. }
  28826. this._randomTexture.update(false);
  28827. };
  28828. return SSAORenderingPipeline;
  28829. })(BABYLON.PostProcessRenderPipeline);
  28830. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28831. })(BABYLON || (BABYLON = {}));
  28832. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28833. var BABYLON;
  28834. (function (BABYLON) {
  28835. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28836. var VolumetricLightScatteringPostProcess = (function (_super) {
  28837. __extends(VolumetricLightScatteringPostProcess, _super);
  28838. /**
  28839. * @constructor
  28840. * @param {string} name - The post-process name
  28841. * @param {any} ratio - The size of the post-process and/or internal pass (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  28842. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28843. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28844. * @param {number} samples - The post-process quality, default 100
  28845. * @param {number} samplingMode - The post-process filtering mode
  28846. * @param {BABYLON.Engine} engine - The babylon engine
  28847. * @param {boolean} reusable - If the post-process is reusable
  28848. */
  28849. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28850. var _this = this;
  28851. if (samples === void 0) { samples = 100; }
  28852. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28853. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28854. this._screenCoordinates = BABYLON.Vector2.Zero();
  28855. /**
  28856. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28857. * @type {boolean}
  28858. */
  28859. this.useCustomMeshPosition = false;
  28860. /**
  28861. * If the post-process should inverse the light scattering direction
  28862. * @type {boolean}
  28863. */
  28864. this.invert = true;
  28865. /**
  28866. * Array containing the excluded meshes not rendered in the internal pass
  28867. */
  28868. this.excludedMeshes = new Array();
  28869. this.exposure = 0.3;
  28870. this.decay = 0.96815;
  28871. this.weight = 0.58767;
  28872. this.density = 0.926;
  28873. var scene = camera.getScene();
  28874. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28875. // Configure mesh
  28876. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28877. // Configure
  28878. this._createPass(scene, ratio.passRatio || ratio);
  28879. this.onApply = function (effect) {
  28880. _this._updateMeshScreenCoordinates(scene);
  28881. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28882. effect.setFloat("exposure", _this.exposure);
  28883. effect.setFloat("decay", _this.decay);
  28884. effect.setFloat("weight", _this.weight);
  28885. effect.setFloat("density", _this.density);
  28886. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28887. };
  28888. }
  28889. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28890. var mesh = subMesh.getMesh();
  28891. var defines = [];
  28892. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28893. var material = subMesh.getMaterial();
  28894. // Render this.mesh as default
  28895. if (mesh === this.mesh) {
  28896. defines.push("#define BASIC_RENDER");
  28897. }
  28898. // Alpha test
  28899. if (material) {
  28900. if (material.needAlphaTesting() || mesh === this.mesh)
  28901. defines.push("#define ALPHATEST");
  28902. if (material.opacityTexture !== undefined)
  28903. defines.push("#define OPACITY");
  28904. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28905. attribs.push(BABYLON.VertexBuffer.UVKind);
  28906. defines.push("#define UV1");
  28907. }
  28908. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28909. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28910. defines.push("#define UV2");
  28911. }
  28912. }
  28913. // Bones
  28914. if (mesh.useBones) {
  28915. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28916. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28917. defines.push("#define BONES");
  28918. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28919. }
  28920. // Instances
  28921. if (useInstances) {
  28922. defines.push("#define INSTANCES");
  28923. attribs.push("world0");
  28924. attribs.push("world1");
  28925. attribs.push("world2");
  28926. attribs.push("world3");
  28927. }
  28928. // Get correct effect
  28929. var join = defines.join("\n");
  28930. if (this._cachedDefines !== join) {
  28931. this._cachedDefines = join;
  28932. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28933. }
  28934. return this._volumetricLightScatteringPass.isReady();
  28935. };
  28936. /**
  28937. * Sets the new light position for light scattering effect
  28938. * @param {BABYLON.Vector3} The new custom light position
  28939. */
  28940. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28941. this._customMeshPosition = position;
  28942. };
  28943. /**
  28944. * Returns the light position for light scattering effect
  28945. * @return {BABYLON.Vector3} The custom light position
  28946. */
  28947. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28948. return this._customMeshPosition;
  28949. };
  28950. /**
  28951. * Disposes the internal assets and detaches the post-process from the camera
  28952. */
  28953. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28954. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28955. if (rttIndex !== -1) {
  28956. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28957. }
  28958. this._volumetricLightScatteringRTT.dispose();
  28959. _super.prototype.dispose.call(this, camera);
  28960. };
  28961. /**
  28962. * Returns the render target texture used by the post-process
  28963. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28964. */
  28965. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28966. return this._volumetricLightScatteringRTT;
  28967. };
  28968. // Private methods
  28969. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28970. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28971. return true;
  28972. }
  28973. return false;
  28974. };
  28975. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28976. var _this = this;
  28977. var engine = scene.getEngine();
  28978. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28979. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28980. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28981. this._volumetricLightScatteringRTT.renderList = null;
  28982. this._volumetricLightScatteringRTT.renderParticles = false;
  28983. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28984. // Custom render function for submeshes
  28985. var renderSubMesh = function (subMesh) {
  28986. var mesh = subMesh.getRenderingMesh();
  28987. if (_this._meshExcluded(mesh)) {
  28988. return;
  28989. }
  28990. var scene = mesh.getScene();
  28991. var engine = scene.getEngine();
  28992. // Culling
  28993. engine.setState(subMesh.getMaterial().backFaceCulling);
  28994. // Managing instances
  28995. var batch = mesh._getInstancesRenderList(subMesh._id);
  28996. if (batch.mustReturn) {
  28997. return;
  28998. }
  28999. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29000. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29001. engine.enableEffect(_this._volumetricLightScatteringPass);
  29002. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29003. var material = subMesh.getMaterial();
  29004. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29005. // Alpha test
  29006. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29007. var alphaTexture = material.getAlphaTestTexture();
  29008. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29009. if (_this.mesh.material && alphaTexture)
  29010. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29011. if (material.opacityTexture !== undefined)
  29012. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29013. }
  29014. // Bones
  29015. if (mesh.useBones) {
  29016. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29017. }
  29018. // Draw
  29019. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29020. }
  29021. };
  29022. // Render target texture callbacks
  29023. var savedSceneClearColor;
  29024. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29025. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29026. savedSceneClearColor = scene.clearColor;
  29027. scene.clearColor = sceneClearColor;
  29028. };
  29029. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29030. scene.clearColor = savedSceneClearColor;
  29031. };
  29032. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29033. var index;
  29034. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29035. renderSubMesh(opaqueSubMeshes.data[index]);
  29036. }
  29037. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29038. renderSubMesh(alphaTestSubMeshes.data[index]);
  29039. }
  29040. for (index = 0; index < transparentSubMeshes.length; index++) {
  29041. renderSubMesh(transparentSubMeshes.data[index]);
  29042. }
  29043. };
  29044. };
  29045. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29046. var transform = scene.getTransformMatrix();
  29047. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29048. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29049. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29050. if (this.invert)
  29051. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29052. };
  29053. // Static methods
  29054. /**
  29055. * Creates a default mesh for the Volumeric Light Scattering post-process
  29056. * @param {string} The mesh name
  29057. * @param {BABYLON.Scene} The scene where to create the mesh
  29058. * @return {BABYLON.Mesh} the default mesh
  29059. */
  29060. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29061. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29062. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29063. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29064. return mesh;
  29065. };
  29066. return VolumetricLightScatteringPostProcess;
  29067. })(BABYLON.PostProcess);
  29068. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29069. })(BABYLON || (BABYLON = {}));
  29070. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29071. var BABYLON;
  29072. (function (BABYLON) {
  29073. var LensRenderingPipeline = (function (_super) {
  29074. __extends(LensRenderingPipeline, _super);
  29075. /**
  29076. * @constructor
  29077. * @param {string} name - The rendering pipeline name
  29078. * @param {object} parameters - An object containing all parameters (see below)
  29079. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29080. * @param {number} ratio - The size of the postprocesses (0.5 means that your postprocess will have a width = canvas.width 0.5 and a height = canvas.height 0.5)
  29081. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29082. Effect parameters are as follow:
  29083. {
  29084. chromatic_aberration: number; // from 0 to x (1 for realism)
  29085. edge_blur: number; // from 0 to x (1 for realism)
  29086. distortion: number; // from 0 to x (1 for realism)
  29087. grain_amount: number; // from 0 to 1
  29088. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29089. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29090. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29091. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29092. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29093. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29094. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29095. }
  29096. Note: if an effect parameter is unset, effect is disabled
  29097. */
  29098. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29099. var _this = this;
  29100. if (ratio === void 0) { ratio = 1.0; }
  29101. _super.call(this, scene.getEngine(), name);
  29102. // Lens effects can be of the following:
  29103. // - chromatic aberration (slight shift of RGB colors)
  29104. // - blur on the edge of the lens
  29105. // - lens distortion
  29106. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29107. // - grain/dust-on-lens effect
  29108. // Two additional texture samplers are needed:
  29109. // - depth map (for depth-of-field)
  29110. // - grain texture
  29111. /**
  29112. * The chromatic aberration PostProcess id in the pipeline
  29113. * @type {string}
  29114. */
  29115. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29116. /**
  29117. * The depth-of-field PostProcess id in the pipeline
  29118. * @type {string}
  29119. */
  29120. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29121. this._scene = scene;
  29122. // Fetch texture samplers
  29123. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29124. if (parameters.grain_texture) {
  29125. this._grainTexture = parameters.grain_texture;
  29126. }
  29127. else {
  29128. this._createGrainTexture();
  29129. }
  29130. // save parameters
  29131. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29132. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29133. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29134. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29135. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29136. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29137. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29138. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29139. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29140. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29141. // Create effects
  29142. this._createChromaticAberrationPostProcess(ratio);
  29143. this._createDepthOfFieldPostProcess(ratio);
  29144. // Set up pipeline
  29145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29146. return _this._chromaticAberrationPostProcess;
  29147. }, true));
  29148. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29149. return _this._depthOfFieldPostProcess;
  29150. }, true));
  29151. // Finish
  29152. scene.postProcessRenderPipelineManager.addPipeline(this);
  29153. if (cameras) {
  29154. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29155. }
  29156. }
  29157. // public methods
  29158. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29159. this._edgeBlur = amount;
  29160. };
  29161. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29162. this._edgeBlur = 0;
  29163. };
  29164. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29165. this._grainAmount = amount;
  29166. };
  29167. LensRenderingPipeline.prototype.disableGrain = function () {
  29168. this._grainAmount = 0;
  29169. };
  29170. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29171. this._chromaticAberration = amount;
  29172. };
  29173. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29174. this._chromaticAberration = 0;
  29175. };
  29176. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29177. this._distortion = amount;
  29178. };
  29179. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29180. this._distortion = 0;
  29181. };
  29182. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29183. this._highlightsGain = amount;
  29184. };
  29185. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29186. this._highlightsThreshold = amount;
  29187. };
  29188. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29189. this._dofDepth = amount;
  29190. };
  29191. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29192. this._dofDepth = -1;
  29193. };
  29194. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29195. this._dofAperture = amount;
  29196. };
  29197. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29198. this._dofPentagon = true;
  29199. };
  29200. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29201. this._dofPentagon = false;
  29202. };
  29203. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29204. this._blurNoise = true;
  29205. };
  29206. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29207. this._blurNoise = false;
  29208. };
  29209. /**
  29210. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29211. */
  29212. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29213. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29214. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29215. this._chromaticAberrationPostProcess = undefined;
  29216. this._depthOfFieldPostProcess = undefined;
  29217. this._grainTexture.dispose();
  29218. if (disableDepthRender)
  29219. this._scene.disableDepthRenderer();
  29220. };
  29221. // colors shifting and distortion
  29222. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29223. var _this = this;
  29224. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29225. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29226. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29227. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29228. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29229. };
  29230. };
  29231. // colors shifting and distortion
  29232. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29233. var _this = this;
  29234. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29235. "gain",
  29236. "threshold",
  29237. "focus_depth",
  29238. "aperture",
  29239. "pentagon",
  29240. "maxZ",
  29241. "edge_blur",
  29242. "chromatic_aberration",
  29243. "distortion",
  29244. "blur_noise",
  29245. "grain_amount",
  29246. "screen_width",
  29247. "screen_height"
  29248. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29249. this._depthOfFieldPostProcess.onApply = function (effect) {
  29250. effect.setBool('pentagon', _this._dofPentagon);
  29251. effect.setBool('blur_noise', _this._blurNoise);
  29252. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29253. effect.setFloat('grain_amount', _this._grainAmount);
  29254. effect.setTexture("depthSampler", _this._depthTexture);
  29255. effect.setTexture("grainSampler", _this._grainTexture);
  29256. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29257. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29258. effect.setFloat('distortion', _this._distortion);
  29259. effect.setFloat('focus_depth', _this._dofDepth);
  29260. effect.setFloat('aperture', _this._dofAperture);
  29261. effect.setFloat('gain', _this._highlightsGain);
  29262. effect.setFloat('threshold', _this._highlightsThreshold);
  29263. effect.setFloat('edge_blur', _this._edgeBlur);
  29264. };
  29265. };
  29266. // creates a black and white random noise texture, 512x512
  29267. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29268. var size = 512;
  29269. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29270. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29271. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29272. var context = this._grainTexture.getContext();
  29273. var rand = function (min, max) {
  29274. return Math.random() * (max - min) + min;
  29275. };
  29276. var value;
  29277. for (var x = 0; x < size; x++) {
  29278. for (var y = 0; y < size; y++) {
  29279. value = Math.floor(rand(0.42, 0.58) * 255);
  29280. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29281. context.fillRect(x, y, 1, 1);
  29282. }
  29283. }
  29284. this._grainTexture.update(false);
  29285. };
  29286. return LensRenderingPipeline;
  29287. })(BABYLON.PostProcessRenderPipeline);
  29288. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29289. })(BABYLON || (BABYLON = {}));
  29290. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29291. // This post-process allows the modification of rendered colors by using
  29292. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29293. //
  29294. // The object needs to be provided an url to a texture containing the color
  29295. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29296. // Use an image editing software to tweak the LUT to match your needs.
  29297. //
  29298. // For an example of a color LUT, see here:
  29299. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29300. // For explanations on color grading, see here:
  29301. // http://udn.epicgames.com/Three/ColorGrading.html
  29302. //
  29303. var BABYLON;
  29304. (function (BABYLON) {
  29305. var ColorCorrectionPostProcess = (function (_super) {
  29306. __extends(ColorCorrectionPostProcess, _super);
  29307. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29308. var _this = this;
  29309. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29310. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29311. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29312. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29313. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29314. this.onApply = function (effect) {
  29315. effect.setTexture("colorTable", _this._colorTableTexture);
  29316. };
  29317. }
  29318. return ColorCorrectionPostProcess;
  29319. })(BABYLON.PostProcess);
  29320. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29321. })(BABYLON || (BABYLON = {}));
  29322. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map