babylon.2.1-alpha.debug.js 1.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858
  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.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  639. var v = SIMD.float32x4(vector.x, vector.y, vector.z, 0);
  640. var m0 = SIMD.float32x4.load(transformation.m, 0);
  641. var m1 = SIMD.float32x4.load(transformation.m, 4);
  642. var m2 = SIMD.float32x4.load(transformation.m, 8);
  643. var m3 = SIMD.float32x4.load(transformation.m, 12);
  644. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 0, 0, 0, 0), m0), SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 1, 1, 1, 1), m1)), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(v, 2, 2, 2, 2), m2), m3));
  645. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  646. SIMD.float32x4.storeXYZ(result, 0, r);
  647. };
  648. Vector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  649. var v0 = SIMD.float32x4.splat(x);
  650. var v1 = SIMD.float32x4.splat(y);
  651. var v2 = SIMD.float32x4.splat(z);
  652. var m0 = SIMD.float32x4.load(transformation.m, 0);
  653. var m1 = SIMD.float32x4.load(transformation.m, 4);
  654. var m2 = SIMD.float32x4.load(transformation.m, 8);
  655. var m3 = SIMD.float32x4.load(transformation.m, 12);
  656. var r = SIMD.float32x4.add(SIMD.float32x4.add(SIMD.float32x4.mul(v0, m0), SIMD.float32x4.mul(v1, m1)), SIMD.float32x4.add(SIMD.float32x4.mul(v2, m2), m3));
  657. r = SIMD.float32x4.div(r, SIMD.float32x4.swizzle(r, 3, 3, 3, 3));
  658. SIMD.float32x4.storeXYZ(result, 0, r);
  659. };
  660. Vector3.TransformNormal = function (vector, transformation) {
  661. var result = Vector3.Zero();
  662. Vector3.TransformNormalToRef(vector, transformation, result);
  663. return result;
  664. };
  665. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  666. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  667. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  668. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  669. };
  670. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  671. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  672. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  673. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  674. };
  675. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  676. var squared = amount * amount;
  677. var cubed = amount * squared;
  678. 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));
  679. 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));
  680. 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));
  681. return new Vector3(x, y, z);
  682. };
  683. Vector3.Clamp = function (value, min, max) {
  684. var x = value.x;
  685. x = (x > max.x) ? max.x : x;
  686. x = (x < min.x) ? min.x : x;
  687. var y = value.y;
  688. y = (y > max.y) ? max.y : y;
  689. y = (y < min.y) ? min.y : y;
  690. var z = value.z;
  691. z = (z > max.z) ? max.z : z;
  692. z = (z < min.z) ? min.z : z;
  693. return new Vector3(x, y, z);
  694. };
  695. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  696. var squared = amount * amount;
  697. var cubed = amount * squared;
  698. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  699. var part2 = (-2.0 * cubed) + (3.0 * squared);
  700. var part3 = (cubed - (2.0 * squared)) + amount;
  701. var part4 = cubed - squared;
  702. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  703. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  704. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  705. return new Vector3(x, y, z);
  706. };
  707. Vector3.Lerp = function (start, end, amount) {
  708. var x = start.x + ((end.x - start.x) * amount);
  709. var y = start.y + ((end.y - start.y) * amount);
  710. var z = start.z + ((end.z - start.z) * amount);
  711. return new Vector3(x, y, z);
  712. };
  713. Vector3.Dot = function (left, right) {
  714. return (left.x * right.x + left.y * right.y + left.z * right.z);
  715. };
  716. Vector3.Cross = function (left, right) {
  717. var result = Vector3.Zero();
  718. Vector3.CrossToRef(left, right, result);
  719. return result;
  720. };
  721. Vector3.CrossToRef = function (left, right, result) {
  722. result.x = left.y * right.z - left.z * right.y;
  723. result.y = left.z * right.x - left.x * right.z;
  724. result.z = left.x * right.y - left.y * right.x;
  725. };
  726. Vector3.Normalize = function (vector) {
  727. var result = Vector3.Zero();
  728. Vector3.NormalizeToRef(vector, result);
  729. return result;
  730. };
  731. Vector3.NormalizeToRef = function (vector, result) {
  732. result.copyFrom(vector);
  733. result.normalize();
  734. };
  735. Vector3.Project = function (vector, world, transform, viewport) {
  736. var cw = viewport.width;
  737. var ch = viewport.height;
  738. var cx = viewport.x;
  739. var cy = viewport.y;
  740. 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);
  741. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  742. return Vector3.TransformCoordinates(vector, finalMatrix);
  743. };
  744. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  745. var matrix = world.multiply(transform);
  746. matrix.invert();
  747. source.x = source.x / viewportWidth * 2 - 1;
  748. source.y = -(source.y / viewportHeight * 2 - 1);
  749. var vector = Vector3.TransformCoordinates(source, matrix);
  750. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  751. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  752. vector = vector.scale(1.0 / num);
  753. }
  754. return vector;
  755. };
  756. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  757. var matrix = world.multiply(view).multiply(projection);
  758. matrix.invert();
  759. source.x = source.x / viewportWidth * 2 - 1;
  760. source.y = -(source.y / viewportHeight * 2 - 1);
  761. var vector = Vector3.TransformCoordinates(source, matrix);
  762. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  763. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  764. vector = vector.scale(1.0 / num);
  765. }
  766. return vector;
  767. };
  768. Vector3.Minimize = function (left, right) {
  769. var min = left.clone();
  770. min.MinimizeInPlace(right);
  771. return min;
  772. };
  773. Vector3.Maximize = function (left, right) {
  774. var max = left.clone();
  775. max.MaximizeInPlace(right);
  776. return max;
  777. };
  778. Vector3.Distance = function (value1, value2) {
  779. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  780. };
  781. Vector3.DistanceSquared = function (value1, value2) {
  782. var x = value1.x - value2.x;
  783. var y = value1.y - value2.y;
  784. var z = value1.z - value2.z;
  785. return (x * x) + (y * y) + (z * z);
  786. };
  787. Vector3.Center = function (value1, value2) {
  788. var center = value1.add(value2);
  789. center.scaleInPlace(0.5);
  790. return center;
  791. };
  792. return Vector3;
  793. })();
  794. BABYLON.Vector3 = Vector3;
  795. //Vector4 class created for EulerAngle class conversion to Quaternion
  796. var Vector4 = (function () {
  797. function Vector4(x, y, z, w) {
  798. this.x = x;
  799. this.y = y;
  800. this.z = z;
  801. this.w = w;
  802. }
  803. Vector4.prototype.toString = function () {
  804. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  805. };
  806. // Operators
  807. Vector4.prototype.asArray = function () {
  808. var result = [];
  809. this.toArray(result, 0);
  810. return result;
  811. };
  812. Vector4.prototype.toArray = function (array, index) {
  813. if (index === undefined) {
  814. index = 0;
  815. }
  816. array[index] = this.x;
  817. array[index + 1] = this.y;
  818. array[index + 2] = this.z;
  819. array[index + 3] = this.w;
  820. return this;
  821. };
  822. Vector4.prototype.addInPlace = function (otherVector) {
  823. this.x += otherVector.x;
  824. this.y += otherVector.y;
  825. this.z += otherVector.z;
  826. this.w += otherVector.w;
  827. return this;
  828. };
  829. Vector4.prototype.add = function (otherVector) {
  830. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  831. };
  832. Vector4.prototype.addToRef = function (otherVector, result) {
  833. result.x = this.x + otherVector.x;
  834. result.y = this.y + otherVector.y;
  835. result.z = this.z + otherVector.z;
  836. result.w = this.w + otherVector.w;
  837. return this;
  838. };
  839. Vector4.prototype.subtractInPlace = function (otherVector) {
  840. this.x -= otherVector.x;
  841. this.y -= otherVector.y;
  842. this.z -= otherVector.z;
  843. this.w -= otherVector.w;
  844. return this;
  845. };
  846. Vector4.prototype.subtract = function (otherVector) {
  847. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  848. };
  849. Vector4.prototype.subtractToRef = function (otherVector, result) {
  850. result.x = this.x - otherVector.x;
  851. result.y = this.y - otherVector.y;
  852. result.z = this.z - otherVector.z;
  853. result.w = this.w - otherVector.w;
  854. return this;
  855. };
  856. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  857. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  858. };
  859. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  860. result.x = this.x - x;
  861. result.y = this.y - y;
  862. result.z = this.z - z;
  863. result.w = this.w - w;
  864. return this;
  865. };
  866. Vector4.prototype.negate = function () {
  867. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  868. };
  869. Vector4.prototype.scaleInPlace = function (scale) {
  870. this.x *= scale;
  871. this.y *= scale;
  872. this.z *= scale;
  873. this.w *= scale;
  874. return this;
  875. };
  876. Vector4.prototype.scale = function (scale) {
  877. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  878. };
  879. Vector4.prototype.scaleToRef = function (scale, result) {
  880. result.x = this.x * scale;
  881. result.y = this.y * scale;
  882. result.z = this.z * scale;
  883. result.w = this.w * scale;
  884. };
  885. Vector4.prototype.equals = function (otherVector) {
  886. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  887. };
  888. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  889. 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;
  890. };
  891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  892. return this.x === x && this.y === y && this.z === z && this.w === w;
  893. };
  894. Vector4.prototype.multiplyInPlace = function (otherVector) {
  895. this.x *= otherVector.x;
  896. this.y *= otherVector.y;
  897. this.z *= otherVector.z;
  898. this.w *= otherVector.w;
  899. return this;
  900. };
  901. Vector4.prototype.multiply = function (otherVector) {
  902. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  903. };
  904. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  905. result.x = this.x * otherVector.x;
  906. result.y = this.y * otherVector.y;
  907. result.z = this.z * otherVector.z;
  908. result.w = this.w * otherVector.w;
  909. return this;
  910. };
  911. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  912. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  913. };
  914. Vector4.prototype.divide = function (otherVector) {
  915. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  916. };
  917. Vector4.prototype.divideToRef = function (otherVector, result) {
  918. result.x = this.x / otherVector.x;
  919. result.y = this.y / otherVector.y;
  920. result.z = this.z / otherVector.z;
  921. result.w = this.w / otherVector.w;
  922. return this;
  923. };
  924. Vector4.prototype.MinimizeInPlace = function (other) {
  925. if (other.x < this.x)
  926. this.x = other.x;
  927. if (other.y < this.y)
  928. this.y = other.y;
  929. if (other.z < this.z)
  930. this.z = other.z;
  931. if (other.w < this.w)
  932. this.w = other.w;
  933. return this;
  934. };
  935. Vector4.prototype.MaximizeInPlace = function (other) {
  936. if (other.x > this.x)
  937. this.x = other.x;
  938. if (other.y > this.y)
  939. this.y = other.y;
  940. if (other.z > this.z)
  941. this.z = other.z;
  942. if (other.w > this.w)
  943. this.w = other.w;
  944. return this;
  945. };
  946. // Properties
  947. Vector4.prototype.length = function () {
  948. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  949. };
  950. Vector4.prototype.lengthSquared = function () {
  951. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  952. };
  953. // Methods
  954. Vector4.prototype.normalize = function () {
  955. var len = this.length();
  956. if (len === 0)
  957. return this;
  958. var num = 1.0 / len;
  959. this.x *= num;
  960. this.y *= num;
  961. this.z *= num;
  962. this.w *= num;
  963. return this;
  964. };
  965. Vector4.prototype.clone = function () {
  966. return new Vector4(this.x, this.y, this.z, this.w);
  967. };
  968. Vector4.prototype.copyFrom = function (source) {
  969. this.x = source.x;
  970. this.y = source.y;
  971. this.z = source.z;
  972. this.w = source.w;
  973. return this;
  974. };
  975. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  976. this.x = x;
  977. this.y = y;
  978. this.z = z;
  979. this.w = w;
  980. return this;
  981. };
  982. // Statics
  983. Vector4.FromArray = function (array, offset) {
  984. if (!offset) {
  985. offset = 0;
  986. }
  987. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  988. };
  989. Vector4.FromArrayToRef = function (array, offset, result) {
  990. result.x = array[offset];
  991. result.y = array[offset + 1];
  992. result.z = array[offset + 2];
  993. result.w = array[offset + 3];
  994. };
  995. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  996. result.x = array[offset];
  997. result.y = array[offset + 1];
  998. result.z = array[offset + 2];
  999. result.w = array[offset + 3];
  1000. };
  1001. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1002. result.x = x;
  1003. result.y = y;
  1004. result.z = z;
  1005. result.w = w;
  1006. };
  1007. Vector4.Zero = function () {
  1008. return new Vector4(0, 0, 0, 0);
  1009. };
  1010. Vector4.Normalize = function (vector) {
  1011. var result = Vector4.Zero();
  1012. Vector4.NormalizeToRef(vector, result);
  1013. return result;
  1014. };
  1015. Vector4.NormalizeToRef = function (vector, result) {
  1016. result.copyFrom(vector);
  1017. result.normalize();
  1018. };
  1019. Vector4.Minimize = function (left, right) {
  1020. var min = left.clone();
  1021. min.MinimizeInPlace(right);
  1022. return min;
  1023. };
  1024. Vector4.Maximize = function (left, right) {
  1025. var max = left.clone();
  1026. max.MaximizeInPlace(right);
  1027. return max;
  1028. };
  1029. Vector4.Distance = function (value1, value2) {
  1030. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1031. };
  1032. Vector4.DistanceSquared = function (value1, value2) {
  1033. var x = value1.x - value2.x;
  1034. var y = value1.y - value2.y;
  1035. var z = value1.z - value2.z;
  1036. var w = value1.w - value2.w;
  1037. return (x * x) + (y * y) + (z * z) + (w * w);
  1038. };
  1039. Vector4.Center = function (value1, value2) {
  1040. var center = value1.add(value2);
  1041. center.scaleInPlace(0.5);
  1042. return center;
  1043. };
  1044. return Vector4;
  1045. })();
  1046. BABYLON.Vector4 = Vector4;
  1047. var Quaternion = (function () {
  1048. function Quaternion(x, y, z, w) {
  1049. if (x === void 0) { x = 0; }
  1050. if (y === void 0) { y = 0; }
  1051. if (z === void 0) { z = 0; }
  1052. if (w === void 0) { w = 1; }
  1053. this.x = x;
  1054. this.y = y;
  1055. this.z = z;
  1056. this.w = w;
  1057. }
  1058. Quaternion.prototype.toString = function () {
  1059. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1060. };
  1061. Quaternion.prototype.asArray = function () {
  1062. return [this.x, this.y, this.z, this.w];
  1063. };
  1064. Quaternion.prototype.equals = function (otherQuaternion) {
  1065. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1066. };
  1067. Quaternion.prototype.clone = function () {
  1068. return new Quaternion(this.x, this.y, this.z, this.w);
  1069. };
  1070. Quaternion.prototype.copyFrom = function (other) {
  1071. this.x = other.x;
  1072. this.y = other.y;
  1073. this.z = other.z;
  1074. this.w = other.w;
  1075. return this;
  1076. };
  1077. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1078. this.x = x;
  1079. this.y = y;
  1080. this.z = z;
  1081. this.w = w;
  1082. return this;
  1083. };
  1084. Quaternion.prototype.add = function (other) {
  1085. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1086. };
  1087. Quaternion.prototype.subtract = function (other) {
  1088. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1089. };
  1090. Quaternion.prototype.scale = function (value) {
  1091. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1092. };
  1093. Quaternion.prototype.multiply = function (q1) {
  1094. var result = new Quaternion(0, 0, 0, 1.0);
  1095. this.multiplyToRef(q1, result);
  1096. return result;
  1097. };
  1098. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1099. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1100. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1101. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1102. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1103. return this;
  1104. };
  1105. Quaternion.prototype.length = function () {
  1106. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1107. };
  1108. Quaternion.prototype.normalize = function () {
  1109. var length = 1.0 / this.length();
  1110. this.x *= length;
  1111. this.y *= length;
  1112. this.z *= length;
  1113. this.w *= length;
  1114. return this;
  1115. };
  1116. Quaternion.prototype.toEulerAngles = function () {
  1117. var result = Vector3.Zero();
  1118. this.toEulerAnglesToRef(result);
  1119. return result;
  1120. };
  1121. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1122. //result is an EulerAngles in the in the z-x-z convention
  1123. var qx = this.x;
  1124. var qy = this.y;
  1125. var qz = this.z;
  1126. var qw = this.w;
  1127. var qxy = qx * qy;
  1128. var qxz = qx * qz;
  1129. var qwy = qw * qy;
  1130. var qwz = qw * qz;
  1131. var qwx = qw * qx;
  1132. var qyz = qy * qz;
  1133. var sqx = qx * qx;
  1134. var sqy = qy * qy;
  1135. var determinant = sqx + sqy;
  1136. if (determinant !== 0.000 && determinant !== 1.000) {
  1137. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1138. result.y = Math.acos(1 - 2 * determinant);
  1139. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1140. }
  1141. else {
  1142. if (determinant === 0.0) {
  1143. result.x = 0.0;
  1144. result.y = 0.0;
  1145. 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)
  1146. }
  1147. else {
  1148. 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)
  1149. result.y = Math.PI;
  1150. result.z = 0.0;
  1151. }
  1152. }
  1153. return this;
  1154. };
  1155. Quaternion.prototype.toRotationMatrix = function (result) {
  1156. var xx = this.x * this.x;
  1157. var yy = this.y * this.y;
  1158. var zz = this.z * this.z;
  1159. var xy = this.x * this.y;
  1160. var zw = this.z * this.w;
  1161. var zx = this.z * this.x;
  1162. var yw = this.y * this.w;
  1163. var yz = this.y * this.z;
  1164. var xw = this.x * this.w;
  1165. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1166. result.m[1] = 2.0 * (xy + zw);
  1167. result.m[2] = 2.0 * (zx - yw);
  1168. result.m[3] = 0;
  1169. result.m[4] = 2.0 * (xy - zw);
  1170. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1171. result.m[6] = 2.0 * (yz + xw);
  1172. result.m[7] = 0;
  1173. result.m[8] = 2.0 * (zx + yw);
  1174. result.m[9] = 2.0 * (yz - xw);
  1175. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1176. result.m[11] = 0;
  1177. result.m[12] = 0;
  1178. result.m[13] = 0;
  1179. result.m[14] = 0;
  1180. result.m[15] = 1.0;
  1181. return this;
  1182. };
  1183. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1184. Quaternion.FromRotationMatrixToRef(matrix, this);
  1185. return this;
  1186. };
  1187. // Statics
  1188. Quaternion.FromRotationMatrix = function (matrix) {
  1189. var result = new Quaternion();
  1190. Quaternion.FromRotationMatrixToRef(matrix, result);
  1191. return result;
  1192. };
  1193. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1194. var data = matrix.m;
  1195. var m11 = data[0], m12 = data[4], m13 = data[8];
  1196. var m21 = data[1], m22 = data[5], m23 = data[9];
  1197. var m31 = data[2], m32 = data[6], m33 = data[10];
  1198. var trace = m11 + m22 + m33;
  1199. var s;
  1200. if (trace > 0) {
  1201. s = 0.5 / Math.sqrt(trace + 1.0);
  1202. result.w = 0.25 / s;
  1203. result.x = (m32 - m23) * s;
  1204. result.y = (m13 - m31) * s;
  1205. result.z = (m21 - m12) * s;
  1206. }
  1207. else if (m11 > m22 && m11 > m33) {
  1208. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1209. result.w = (m32 - m23) / s;
  1210. result.x = 0.25 * s;
  1211. result.y = (m12 + m21) / s;
  1212. result.z = (m13 + m31) / s;
  1213. }
  1214. else if (m22 > m33) {
  1215. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1216. result.w = (m13 - m31) / s;
  1217. result.x = (m12 + m21) / s;
  1218. result.y = 0.25 * s;
  1219. result.z = (m23 + m32) / s;
  1220. }
  1221. else {
  1222. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1223. result.w = (m21 - m12) / s;
  1224. result.x = (m13 + m31) / s;
  1225. result.y = (m23 + m32) / s;
  1226. result.z = 0.25 * s;
  1227. }
  1228. };
  1229. Quaternion.Inverse = function (q) {
  1230. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1231. };
  1232. Quaternion.Identity = function () {
  1233. return new Quaternion(0, 0, 0, 1);
  1234. };
  1235. Quaternion.RotationAxis = function (axis, angle) {
  1236. var result = new Quaternion();
  1237. var sin = Math.sin(angle / 2);
  1238. result.w = Math.cos(angle / 2);
  1239. result.x = axis.x * sin;
  1240. result.y = axis.y * sin;
  1241. result.z = axis.z * sin;
  1242. return result;
  1243. };
  1244. Quaternion.FromArray = function (array, offset) {
  1245. if (!offset) {
  1246. offset = 0;
  1247. }
  1248. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1249. };
  1250. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1251. var result = new Quaternion();
  1252. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1253. return result;
  1254. };
  1255. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1256. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1257. var halfRoll = roll * 0.5;
  1258. var halfPitch = pitch * 0.5;
  1259. var halfYaw = yaw * 0.5;
  1260. var sinRoll = Math.sin(halfRoll);
  1261. var cosRoll = Math.cos(halfRoll);
  1262. var sinPitch = Math.sin(halfPitch);
  1263. var cosPitch = Math.cos(halfPitch);
  1264. var sinYaw = Math.sin(halfYaw);
  1265. var cosYaw = Math.cos(halfYaw);
  1266. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1267. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1268. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1269. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1270. };
  1271. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1272. var result = new Quaternion();
  1273. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1274. return result;
  1275. };
  1276. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1277. // Produces a quaternion from Euler angles in the z-x-z orientation
  1278. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1279. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1280. var halfBeta = beta * 0.5;
  1281. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1282. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1283. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1284. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1285. };
  1286. Quaternion.Slerp = function (left, right, amount) {
  1287. var num2;
  1288. var num3;
  1289. var num = amount;
  1290. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1291. var flag = false;
  1292. if (num4 < 0) {
  1293. flag = true;
  1294. num4 = -num4;
  1295. }
  1296. if (num4 > 0.999999) {
  1297. num3 = 1 - num;
  1298. num2 = flag ? -num : num;
  1299. }
  1300. else {
  1301. var num5 = Math.acos(num4);
  1302. var num6 = (1.0 / Math.sin(num5));
  1303. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1304. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1305. }
  1306. 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));
  1307. };
  1308. return Quaternion;
  1309. })();
  1310. BABYLON.Quaternion = Quaternion;
  1311. var Matrix = (function () {
  1312. function Matrix() {
  1313. this.m = new Float32Array(16);
  1314. }
  1315. // Properties
  1316. Matrix.prototype.isIdentity = function () {
  1317. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1318. return false;
  1319. 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)
  1320. return false;
  1321. return true;
  1322. };
  1323. Matrix.prototype.determinant = function () {
  1324. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1325. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1326. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1327. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1328. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1329. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1330. 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))));
  1331. };
  1332. // Methods
  1333. Matrix.prototype.toArray = function () {
  1334. return this.m;
  1335. };
  1336. Matrix.prototype.asArray = function () {
  1337. return this.toArray();
  1338. };
  1339. Matrix.prototype.invert = function () {
  1340. this.invertToRef(this);
  1341. return this;
  1342. };
  1343. Matrix.prototype.invertToRef = function (other) {
  1344. var l1 = this.m[0];
  1345. var l2 = this.m[1];
  1346. var l3 = this.m[2];
  1347. var l4 = this.m[3];
  1348. var l5 = this.m[4];
  1349. var l6 = this.m[5];
  1350. var l7 = this.m[6];
  1351. var l8 = this.m[7];
  1352. var l9 = this.m[8];
  1353. var l10 = this.m[9];
  1354. var l11 = this.m[10];
  1355. var l12 = this.m[11];
  1356. var l13 = this.m[12];
  1357. var l14 = this.m[13];
  1358. var l15 = this.m[14];
  1359. var l16 = this.m[15];
  1360. var l17 = (l11 * l16) - (l12 * l15);
  1361. var l18 = (l10 * l16) - (l12 * l14);
  1362. var l19 = (l10 * l15) - (l11 * l14);
  1363. var l20 = (l9 * l16) - (l12 * l13);
  1364. var l21 = (l9 * l15) - (l11 * l13);
  1365. var l22 = (l9 * l14) - (l10 * l13);
  1366. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1367. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1368. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1369. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1370. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1371. var l28 = (l7 * l16) - (l8 * l15);
  1372. var l29 = (l6 * l16) - (l8 * l14);
  1373. var l30 = (l6 * l15) - (l7 * l14);
  1374. var l31 = (l5 * l16) - (l8 * l13);
  1375. var l32 = (l5 * l15) - (l7 * l13);
  1376. var l33 = (l5 * l14) - (l6 * l13);
  1377. var l34 = (l7 * l12) - (l8 * l11);
  1378. var l35 = (l6 * l12) - (l8 * l10);
  1379. var l36 = (l6 * l11) - (l7 * l10);
  1380. var l37 = (l5 * l12) - (l8 * l9);
  1381. var l38 = (l5 * l11) - (l7 * l9);
  1382. var l39 = (l5 * l10) - (l6 * l9);
  1383. other.m[0] = l23 * l27;
  1384. other.m[4] = l24 * l27;
  1385. other.m[8] = l25 * l27;
  1386. other.m[12] = l26 * l27;
  1387. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1388. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1389. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1390. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1391. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1392. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1393. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1394. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1395. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1396. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1397. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1398. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1399. return this;
  1400. };
  1401. Matrix.prototype.invertToRefSIMD = function (other) {
  1402. var src = this.m;
  1403. var dest = other.m;
  1404. var row0, row1, row2, row3;
  1405. var tmp1;
  1406. var minor0, minor1, minor2, minor3;
  1407. var det;
  1408. // Load the 4 rows
  1409. var src0 = SIMD.float32x4.load(src, 0);
  1410. var src1 = SIMD.float32x4.load(src, 4);
  1411. var src2 = SIMD.float32x4.load(src, 8);
  1412. var src3 = SIMD.float32x4.load(src, 12);
  1413. // Transpose the source matrix. Sort of. Not a true transpose operation
  1414. tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1415. row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1416. row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  1417. row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  1418. tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1419. row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1420. row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  1421. row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  1422. // This is a true transposition, but it will lead to an incorrect result
  1423. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  1424. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  1425. //row0 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1426. //row1 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1427. //tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  1428. //tmp2 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  1429. //row2 = SIMD.float32x4.shuffle(tmp1, tmp2, 0, 2, 4, 6);
  1430. //row3 = SIMD.float32x4.shuffle(tmp1, tmp2, 1, 3, 5, 7);
  1431. // ----
  1432. tmp1 = SIMD.float32x4.mul(row2, row3);
  1433. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1434. minor0 = SIMD.float32x4.mul(row1, tmp1);
  1435. minor1 = SIMD.float32x4.mul(row0, tmp1);
  1436. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1437. minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
  1438. minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
  1439. minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  1440. // ----
  1441. tmp1 = SIMD.float32x4.mul(row1, row2);
  1442. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1443. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
  1444. minor3 = SIMD.float32x4.mul(row0, tmp1);
  1445. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1446. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
  1447. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
  1448. minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  1449. // ----
  1450. tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  1451. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1452. row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  1453. minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
  1454. minor2 = SIMD.float32x4.mul(row0, tmp1);
  1455. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1456. minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
  1457. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
  1458. minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  1459. // ----
  1460. tmp1 = SIMD.float32x4.mul(row0, row1);
  1461. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1462. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
  1463. minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
  1464. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1465. minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
  1466. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
  1467. // ----
  1468. tmp1 = SIMD.float32x4.mul(row0, row3);
  1469. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1470. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
  1471. minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
  1472. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1473. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
  1474. minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
  1475. // ----
  1476. tmp1 = SIMD.float32x4.mul(row0, row2);
  1477. tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  1478. minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
  1479. minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
  1480. tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  1481. minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
  1482. minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
  1483. // Compute determinant
  1484. det = SIMD.float32x4.mul(row0, minor0);
  1485. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  1486. det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  1487. tmp1 = SIMD.float32x4.reciprocal(det);
  1488. det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
  1489. det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
  1490. // These shuffles aren't necessary if the faulty transposition is done
  1491. // up at the top of this function.
  1492. //minor0 = SIMD.float32x4.swizzle(minor0, 2, 1, 0, 3);
  1493. //minor1 = SIMD.float32x4.swizzle(minor1, 2, 1, 0, 3);
  1494. //minor2 = SIMD.float32x4.swizzle(minor2, 2, 1, 0, 3);
  1495. //minor3 = SIMD.float32x4.swizzle(minor3, 2, 1, 0, 3);
  1496. // Compute final values by multiplying with 1/det
  1497. minor0 = SIMD.float32x4.mul(det, minor0);
  1498. minor1 = SIMD.float32x4.mul(det, minor1);
  1499. minor2 = SIMD.float32x4.mul(det, minor2);
  1500. minor3 = SIMD.float32x4.mul(det, minor3);
  1501. SIMD.float32x4.store(dest, 0, minor0);
  1502. SIMD.float32x4.store(dest, 4, minor1);
  1503. SIMD.float32x4.store(dest, 8, minor2);
  1504. SIMD.float32x4.store(dest, 12, minor3);
  1505. return this;
  1506. };
  1507. Matrix.prototype.setTranslation = function (vector3) {
  1508. this.m[12] = vector3.x;
  1509. this.m[13] = vector3.y;
  1510. this.m[14] = vector3.z;
  1511. return this;
  1512. };
  1513. Matrix.prototype.multiply = function (other) {
  1514. var result = new Matrix();
  1515. this.multiplyToRef(other, result);
  1516. return result;
  1517. };
  1518. Matrix.prototype.copyFrom = function (other) {
  1519. for (var index = 0; index < 16; index++) {
  1520. this.m[index] = other.m[index];
  1521. }
  1522. return this;
  1523. };
  1524. Matrix.prototype.copyToArray = function (array, offset) {
  1525. if (offset === void 0) { offset = 0; }
  1526. for (var index = 0; index < 16; index++) {
  1527. array[offset + index] = this.m[index];
  1528. }
  1529. return this;
  1530. };
  1531. Matrix.prototype.multiplyToRef = function (other, result) {
  1532. this.multiplyToArray(other, result.m, 0);
  1533. return this;
  1534. };
  1535. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1536. var tm0 = this.m[0];
  1537. var tm1 = this.m[1];
  1538. var tm2 = this.m[2];
  1539. var tm3 = this.m[3];
  1540. var tm4 = this.m[4];
  1541. var tm5 = this.m[5];
  1542. var tm6 = this.m[6];
  1543. var tm7 = this.m[7];
  1544. var tm8 = this.m[8];
  1545. var tm9 = this.m[9];
  1546. var tm10 = this.m[10];
  1547. var tm11 = this.m[11];
  1548. var tm12 = this.m[12];
  1549. var tm13 = this.m[13];
  1550. var tm14 = this.m[14];
  1551. var tm15 = this.m[15];
  1552. var om0 = other.m[0];
  1553. var om1 = other.m[1];
  1554. var om2 = other.m[2];
  1555. var om3 = other.m[3];
  1556. var om4 = other.m[4];
  1557. var om5 = other.m[5];
  1558. var om6 = other.m[6];
  1559. var om7 = other.m[7];
  1560. var om8 = other.m[8];
  1561. var om9 = other.m[9];
  1562. var om10 = other.m[10];
  1563. var om11 = other.m[11];
  1564. var om12 = other.m[12];
  1565. var om13 = other.m[13];
  1566. var om14 = other.m[14];
  1567. var om15 = other.m[15];
  1568. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1569. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1570. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1571. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1572. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1573. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1574. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1575. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1576. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1577. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1578. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1579. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1580. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1581. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1582. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1583. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1584. return this;
  1585. };
  1586. Matrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  1587. if (offset === void 0) { offset = 0; }
  1588. var tm = this.m;
  1589. var om = other.m;
  1590. var om0 = SIMD.float32x4.load(om, 0);
  1591. var om1 = SIMD.float32x4.load(om, 4);
  1592. var om2 = SIMD.float32x4.load(om, 8);
  1593. var om3 = SIMD.float32x4.load(om, 12);
  1594. var tm0 = SIMD.float32x4.load(tm, 0);
  1595. SIMD.float32x4.store(result, offset + 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm0, 3, 3, 3, 3), om3)))));
  1596. var tm1 = SIMD.float32x4.load(tm, 4);
  1597. SIMD.float32x4.store(result, offset + 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm1, 3, 3, 3, 3), om3)))));
  1598. var tm2 = SIMD.float32x4.load(tm, 8);
  1599. SIMD.float32x4.store(result, offset + 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm2, 3, 3, 3, 3), om3)))));
  1600. var tm3 = SIMD.float32x4.load(tm, 12);
  1601. SIMD.float32x4.store(result, offset + 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 0, 0, 0, 0), om0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 1, 1, 1, 1), om1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 2, 2, 2, 2), om2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(tm3, 3, 3, 3, 3), om3)))));
  1602. };
  1603. Matrix.prototype.equals = function (value) {
  1604. 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]);
  1605. };
  1606. Matrix.prototype.clone = function () {
  1607. 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]);
  1608. };
  1609. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1610. translation.x = this.m[12];
  1611. translation.y = this.m[13];
  1612. translation.z = this.m[14];
  1613. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1614. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1615. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1616. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1617. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1618. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1619. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1620. rotation.x = 0;
  1621. rotation.y = 0;
  1622. rotation.z = 0;
  1623. rotation.w = 1;
  1624. return false;
  1625. }
  1626. 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);
  1627. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1628. return true;
  1629. };
  1630. // Statics
  1631. Matrix.FromArray = function (array, offset) {
  1632. var result = new Matrix();
  1633. if (!offset) {
  1634. offset = 0;
  1635. }
  1636. Matrix.FromArrayToRef(array, offset, result);
  1637. return result;
  1638. };
  1639. Matrix.FromArrayToRef = function (array, offset, result) {
  1640. for (var index = 0; index < 16; index++) {
  1641. result.m[index] = array[index + offset];
  1642. }
  1643. };
  1644. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1645. result.m[0] = initialM11;
  1646. result.m[1] = initialM12;
  1647. result.m[2] = initialM13;
  1648. result.m[3] = initialM14;
  1649. result.m[4] = initialM21;
  1650. result.m[5] = initialM22;
  1651. result.m[6] = initialM23;
  1652. result.m[7] = initialM24;
  1653. result.m[8] = initialM31;
  1654. result.m[9] = initialM32;
  1655. result.m[10] = initialM33;
  1656. result.m[11] = initialM34;
  1657. result.m[12] = initialM41;
  1658. result.m[13] = initialM42;
  1659. result.m[14] = initialM43;
  1660. result.m[15] = initialM44;
  1661. };
  1662. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1663. var result = new Matrix();
  1664. result.m[0] = initialM11;
  1665. result.m[1] = initialM12;
  1666. result.m[2] = initialM13;
  1667. result.m[3] = initialM14;
  1668. result.m[4] = initialM21;
  1669. result.m[5] = initialM22;
  1670. result.m[6] = initialM23;
  1671. result.m[7] = initialM24;
  1672. result.m[8] = initialM31;
  1673. result.m[9] = initialM32;
  1674. result.m[10] = initialM33;
  1675. result.m[11] = initialM34;
  1676. result.m[12] = initialM41;
  1677. result.m[13] = initialM42;
  1678. result.m[14] = initialM43;
  1679. result.m[15] = initialM44;
  1680. return result;
  1681. };
  1682. Matrix.Compose = function (scale, rotation, translation) {
  1683. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1684. var rotationMatrix = Matrix.Identity();
  1685. rotation.toRotationMatrix(rotationMatrix);
  1686. result = result.multiply(rotationMatrix);
  1687. result.setTranslation(translation);
  1688. return result;
  1689. };
  1690. Matrix.Identity = function () {
  1691. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1692. };
  1693. Matrix.IdentityToRef = function (result) {
  1694. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1695. };
  1696. Matrix.Zero = function () {
  1697. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1698. };
  1699. Matrix.RotationX = function (angle) {
  1700. var result = new Matrix();
  1701. Matrix.RotationXToRef(angle, result);
  1702. return result;
  1703. };
  1704. Matrix.Invert = function (source) {
  1705. var result = new Matrix();
  1706. source.invertToRef(result);
  1707. return result;
  1708. };
  1709. Matrix.RotationXToRef = function (angle, result) {
  1710. var s = Math.sin(angle);
  1711. var c = Math.cos(angle);
  1712. result.m[0] = 1.0;
  1713. result.m[15] = 1.0;
  1714. result.m[5] = c;
  1715. result.m[10] = c;
  1716. result.m[9] = -s;
  1717. result.m[6] = s;
  1718. result.m[1] = 0;
  1719. result.m[2] = 0;
  1720. result.m[3] = 0;
  1721. result.m[4] = 0;
  1722. result.m[7] = 0;
  1723. result.m[8] = 0;
  1724. result.m[11] = 0;
  1725. result.m[12] = 0;
  1726. result.m[13] = 0;
  1727. result.m[14] = 0;
  1728. };
  1729. Matrix.RotationY = function (angle) {
  1730. var result = new Matrix();
  1731. Matrix.RotationYToRef(angle, result);
  1732. return result;
  1733. };
  1734. Matrix.RotationYToRef = function (angle, result) {
  1735. var s = Math.sin(angle);
  1736. var c = Math.cos(angle);
  1737. result.m[5] = 1.0;
  1738. result.m[15] = 1.0;
  1739. result.m[0] = c;
  1740. result.m[2] = -s;
  1741. result.m[8] = s;
  1742. result.m[10] = c;
  1743. result.m[1] = 0;
  1744. result.m[3] = 0;
  1745. result.m[4] = 0;
  1746. result.m[6] = 0;
  1747. result.m[7] = 0;
  1748. result.m[9] = 0;
  1749. result.m[11] = 0;
  1750. result.m[12] = 0;
  1751. result.m[13] = 0;
  1752. result.m[14] = 0;
  1753. };
  1754. Matrix.RotationZ = function (angle) {
  1755. var result = new Matrix();
  1756. Matrix.RotationZToRef(angle, result);
  1757. return result;
  1758. };
  1759. Matrix.RotationZToRef = function (angle, result) {
  1760. var s = Math.sin(angle);
  1761. var c = Math.cos(angle);
  1762. result.m[10] = 1.0;
  1763. result.m[15] = 1.0;
  1764. result.m[0] = c;
  1765. result.m[1] = s;
  1766. result.m[4] = -s;
  1767. result.m[5] = c;
  1768. result.m[2] = 0;
  1769. result.m[3] = 0;
  1770. result.m[6] = 0;
  1771. result.m[7] = 0;
  1772. result.m[8] = 0;
  1773. result.m[9] = 0;
  1774. result.m[11] = 0;
  1775. result.m[12] = 0;
  1776. result.m[13] = 0;
  1777. result.m[14] = 0;
  1778. };
  1779. Matrix.RotationAxis = function (axis, angle) {
  1780. var s = Math.sin(-angle);
  1781. var c = Math.cos(-angle);
  1782. var c1 = 1 - c;
  1783. axis.normalize();
  1784. var result = Matrix.Zero();
  1785. result.m[0] = (axis.x * axis.x) * c1 + c;
  1786. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1787. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1788. result.m[3] = 0.0;
  1789. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1790. result.m[5] = (axis.y * axis.y) * c1 + c;
  1791. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1792. result.m[7] = 0.0;
  1793. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1794. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1795. result.m[10] = (axis.z * axis.z) * c1 + c;
  1796. result.m[11] = 0.0;
  1797. result.m[15] = 1.0;
  1798. return result;
  1799. };
  1800. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1801. var result = new Matrix();
  1802. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1803. return result;
  1804. };
  1805. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1806. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1807. this._tempQuaternion.toRotationMatrix(result);
  1808. };
  1809. Matrix.Scaling = function (x, y, z) {
  1810. var result = Matrix.Zero();
  1811. Matrix.ScalingToRef(x, y, z, result);
  1812. return result;
  1813. };
  1814. Matrix.ScalingToRef = function (x, y, z, result) {
  1815. result.m[0] = x;
  1816. result.m[1] = 0;
  1817. result.m[2] = 0;
  1818. result.m[3] = 0;
  1819. result.m[4] = 0;
  1820. result.m[5] = y;
  1821. result.m[6] = 0;
  1822. result.m[7] = 0;
  1823. result.m[8] = 0;
  1824. result.m[9] = 0;
  1825. result.m[10] = z;
  1826. result.m[11] = 0;
  1827. result.m[12] = 0;
  1828. result.m[13] = 0;
  1829. result.m[14] = 0;
  1830. result.m[15] = 1.0;
  1831. };
  1832. Matrix.Translation = function (x, y, z) {
  1833. var result = Matrix.Identity();
  1834. Matrix.TranslationToRef(x, y, z, result);
  1835. return result;
  1836. };
  1837. Matrix.TranslationToRef = function (x, y, z, result) {
  1838. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1839. };
  1840. Matrix.LookAtLH = function (eye, target, up) {
  1841. var result = Matrix.Zero();
  1842. Matrix.LookAtLHToRef(eye, target, up, result);
  1843. return result;
  1844. };
  1845. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1846. // Z axis
  1847. target.subtractToRef(eye, this._zAxis);
  1848. this._zAxis.normalize();
  1849. // X axis
  1850. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1851. this._xAxis.normalize();
  1852. // Y axis
  1853. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1854. this._yAxis.normalize();
  1855. // Eye angles
  1856. var ex = -Vector3.Dot(this._xAxis, eye);
  1857. var ey = -Vector3.Dot(this._yAxis, eye);
  1858. var ez = -Vector3.Dot(this._zAxis, eye);
  1859. 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);
  1860. };
  1861. Matrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  1862. var out = result.m;
  1863. var center = SIMD.float32x4(targetRef.x, targetRef.y, targetRef.z, 0);
  1864. var eye = SIMD.float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0);
  1865. var up = SIMD.float32x4(upRef.x, upRef.y, upRef.z, 0);
  1866. // cc.kmVec3Subtract(f, pCenter, pEye);
  1867. var f = SIMD.float32x4.sub(center, eye);
  1868. // cc.kmVec3Normalize(f, f);
  1869. var tmp = SIMD.float32x4.mul(f, f);
  1870. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1871. f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrt(tmp));
  1872. // cc.kmVec3Assign(up, pUp);
  1873. // cc.kmVec3Normalize(up, up);
  1874. tmp = SIMD.float32x4.mul(up, up);
  1875. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1876. up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrt(tmp));
  1877. // cc.kmVec3Cross(s, f, up);
  1878. var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
  1879. // cc.kmVec3Normalize(s, s);
  1880. tmp = SIMD.float32x4.mul(s, s);
  1881. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1882. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1883. // cc.kmVec3Cross(u, s, f);
  1884. var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)), SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
  1885. // cc.kmVec3Normalize(s, s);
  1886. tmp = SIMD.float32x4.mul(s, s);
  1887. tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
  1888. s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrt(tmp));
  1889. //cc.kmMat4Identity(pOut);
  1890. //pOut.mat[0] = s.x;
  1891. //pOut.mat[4] = s.y;
  1892. //pOut.mat[8] = s.z;
  1893. //pOut.mat[1] = u.x;
  1894. //pOut.mat[5] = u.y;
  1895. //pOut.mat[9] = u.z;
  1896. //pOut.mat[2] = -f.x;
  1897. //pOut.mat[6] = -f.y;
  1898. //pOut.mat[10] = -f.z;
  1899. var zero = SIMD.float32x4.splat(0.0);
  1900. s = SIMD.float32x4.neg(s);
  1901. var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
  1902. var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
  1903. var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1904. var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  1905. tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
  1906. tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
  1907. var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  1908. var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
  1909. // cc.kmMat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
  1910. var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
  1911. var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
  1912. var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
  1913. var b3 = SIMD.float32x4.neg(eye);
  1914. b3 = SIMD.float32x4.withW(b3, 1.0);
  1915. // cc.kmMat4Multiply(pOut, pOut, translate);
  1916. SIMD.float32x4.store(out, 0, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
  1917. SIMD.float32x4.store(out, 4, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
  1918. SIMD.float32x4.store(out, 8, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
  1919. SIMD.float32x4.store(out, 12, SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1), SIMD.float32x4.add(SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2), SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
  1920. };
  1921. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1922. var matrix = Matrix.Zero();
  1923. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1924. return matrix;
  1925. };
  1926. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1927. var hw = 2.0 / width;
  1928. var hh = 2.0 / height;
  1929. var id = 1.0 / (zfar - znear);
  1930. var nid = znear / (znear - zfar);
  1931. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1932. };
  1933. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1934. var matrix = Matrix.Zero();
  1935. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1936. return matrix;
  1937. };
  1938. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1939. result.m[0] = 2.0 / (right - left);
  1940. result.m[1] = result.m[2] = result.m[3] = 0;
  1941. result.m[5] = 2.0 / (top - bottom);
  1942. result.m[4] = result.m[6] = result.m[7] = 0;
  1943. result.m[10] = -1.0 / (znear - zfar);
  1944. result.m[8] = result.m[9] = result.m[11] = 0;
  1945. result.m[12] = (left + right) / (left - right);
  1946. result.m[13] = (top + bottom) / (bottom - top);
  1947. result.m[14] = znear / (znear - zfar);
  1948. result.m[15] = 1.0;
  1949. };
  1950. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1951. var matrix = Matrix.Zero();
  1952. matrix.m[0] = (2.0 * znear) / width;
  1953. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1954. matrix.m[5] = (2.0 * znear) / height;
  1955. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1956. matrix.m[10] = -zfar / (znear - zfar);
  1957. matrix.m[8] = matrix.m[9] = 0.0;
  1958. matrix.m[11] = 1.0;
  1959. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1960. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1961. return matrix;
  1962. };
  1963. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1964. var matrix = Matrix.Zero();
  1965. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1966. return matrix;
  1967. };
  1968. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1969. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1970. var tan = 1.0 / (Math.tan(fov * 0.5));
  1971. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1972. if (v_fixed) {
  1973. result.m[0] = tan / aspect;
  1974. }
  1975. else {
  1976. result.m[0] = tan;
  1977. }
  1978. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1979. if (v_fixed) {
  1980. result.m[5] = tan;
  1981. }
  1982. else {
  1983. result.m[5] = tan * aspect;
  1984. }
  1985. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1986. result.m[8] = result.m[9] = 0.0;
  1987. result.m[10] = -zfar / (znear - zfar);
  1988. result.m[11] = 1.0;
  1989. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1990. result.m[14] = (znear * zfar) / (znear - zfar);
  1991. };
  1992. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1993. var cw = viewport.width;
  1994. var ch = viewport.height;
  1995. var cx = viewport.x;
  1996. var cy = viewport.y;
  1997. 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);
  1998. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1999. };
  2000. Matrix.Transpose = function (matrix) {
  2001. var result = new Matrix();
  2002. result.m[0] = matrix.m[0];
  2003. result.m[1] = matrix.m[4];
  2004. result.m[2] = matrix.m[8];
  2005. result.m[3] = matrix.m[12];
  2006. result.m[4] = matrix.m[1];
  2007. result.m[5] = matrix.m[5];
  2008. result.m[6] = matrix.m[9];
  2009. result.m[7] = matrix.m[13];
  2010. result.m[8] = matrix.m[2];
  2011. result.m[9] = matrix.m[6];
  2012. result.m[10] = matrix.m[10];
  2013. result.m[11] = matrix.m[14];
  2014. result.m[12] = matrix.m[3];
  2015. result.m[13] = matrix.m[7];
  2016. result.m[14] = matrix.m[11];
  2017. result.m[15] = matrix.m[15];
  2018. return result;
  2019. };
  2020. Matrix.Reflection = function (plane) {
  2021. var matrix = new Matrix();
  2022. Matrix.ReflectionToRef(plane, matrix);
  2023. return matrix;
  2024. };
  2025. Matrix.ReflectionToRef = function (plane, result) {
  2026. plane.normalize();
  2027. var x = plane.normal.x;
  2028. var y = plane.normal.y;
  2029. var z = plane.normal.z;
  2030. var temp = -2 * x;
  2031. var temp2 = -2 * y;
  2032. var temp3 = -2 * z;
  2033. result.m[0] = (temp * x) + 1;
  2034. result.m[1] = temp2 * x;
  2035. result.m[2] = temp3 * x;
  2036. result.m[3] = 0.0;
  2037. result.m[4] = temp * y;
  2038. result.m[5] = (temp2 * y) + 1;
  2039. result.m[6] = temp3 * y;
  2040. result.m[7] = 0.0;
  2041. result.m[8] = temp * z;
  2042. result.m[9] = temp2 * z;
  2043. result.m[10] = (temp3 * z) + 1;
  2044. result.m[11] = 0.0;
  2045. result.m[12] = temp * plane.d;
  2046. result.m[13] = temp2 * plane.d;
  2047. result.m[14] = temp3 * plane.d;
  2048. result.m[15] = 1.0;
  2049. };
  2050. Matrix._tempQuaternion = new Quaternion();
  2051. Matrix._xAxis = Vector3.Zero();
  2052. Matrix._yAxis = Vector3.Zero();
  2053. Matrix._zAxis = Vector3.Zero();
  2054. return Matrix;
  2055. })();
  2056. BABYLON.Matrix = Matrix;
  2057. var Plane = (function () {
  2058. function Plane(a, b, c, d) {
  2059. this.normal = new Vector3(a, b, c);
  2060. this.d = d;
  2061. }
  2062. Plane.prototype.asArray = function () {
  2063. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2064. };
  2065. // Methods
  2066. Plane.prototype.clone = function () {
  2067. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2068. };
  2069. Plane.prototype.normalize = function () {
  2070. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2071. var magnitude = 0;
  2072. if (norm !== 0) {
  2073. magnitude = 1.0 / norm;
  2074. }
  2075. this.normal.x *= magnitude;
  2076. this.normal.y *= magnitude;
  2077. this.normal.z *= magnitude;
  2078. this.d *= magnitude;
  2079. return this;
  2080. };
  2081. Plane.prototype.transform = function (transformation) {
  2082. var transposedMatrix = Matrix.Transpose(transformation);
  2083. var x = this.normal.x;
  2084. var y = this.normal.y;
  2085. var z = this.normal.z;
  2086. var d = this.d;
  2087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2091. return new Plane(normalX, normalY, normalZ, finalD);
  2092. };
  2093. Plane.prototype.dotCoordinate = function (point) {
  2094. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2095. };
  2096. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2097. var x1 = point2.x - point1.x;
  2098. var y1 = point2.y - point1.y;
  2099. var z1 = point2.z - point1.z;
  2100. var x2 = point3.x - point1.x;
  2101. var y2 = point3.y - point1.y;
  2102. var z2 = point3.z - point1.z;
  2103. var yz = (y1 * z2) - (z1 * y2);
  2104. var xz = (z1 * x2) - (x1 * z2);
  2105. var xy = (x1 * y2) - (y1 * x2);
  2106. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2107. var invPyth;
  2108. if (pyth !== 0) {
  2109. invPyth = 1.0 / pyth;
  2110. }
  2111. else {
  2112. invPyth = 0;
  2113. }
  2114. this.normal.x = yz * invPyth;
  2115. this.normal.y = xz * invPyth;
  2116. this.normal.z = xy * invPyth;
  2117. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2118. return this;
  2119. };
  2120. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2121. var dot = Vector3.Dot(this.normal, direction);
  2122. return (dot <= epsilon);
  2123. };
  2124. Plane.prototype.signedDistanceTo = function (point) {
  2125. return Vector3.Dot(point, this.normal) + this.d;
  2126. };
  2127. // Statics
  2128. Plane.FromArray = function (array) {
  2129. return new Plane(array[0], array[1], array[2], array[3]);
  2130. };
  2131. Plane.FromPoints = function (point1, point2, point3) {
  2132. var result = new Plane(0, 0, 0, 0);
  2133. result.copyFromPoints(point1, point2, point3);
  2134. return result;
  2135. };
  2136. Plane.FromPositionAndNormal = function (origin, normal) {
  2137. var result = new Plane(0, 0, 0, 0);
  2138. normal.normalize();
  2139. result.normal = normal;
  2140. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2141. return result;
  2142. };
  2143. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2144. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2145. return Vector3.Dot(point, normal) + d;
  2146. };
  2147. return Plane;
  2148. })();
  2149. BABYLON.Plane = Plane;
  2150. var Viewport = (function () {
  2151. function Viewport(x, y, width, height) {
  2152. this.x = x;
  2153. this.y = y;
  2154. this.width = width;
  2155. this.height = height;
  2156. }
  2157. Viewport.prototype.toGlobal = function (engine) {
  2158. var width = engine.getRenderWidth();
  2159. var height = engine.getRenderHeight();
  2160. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  2161. };
  2162. return Viewport;
  2163. })();
  2164. BABYLON.Viewport = Viewport;
  2165. var Frustum = (function () {
  2166. function Frustum() {
  2167. }
  2168. Frustum.GetPlanes = function (transform) {
  2169. var frustumPlanes = [];
  2170. for (var index = 0; index < 6; index++) {
  2171. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2172. }
  2173. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2174. return frustumPlanes;
  2175. };
  2176. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2177. // Near
  2178. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2179. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2180. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  2181. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2182. frustumPlanes[0].normalize();
  2183. // Far
  2184. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2185. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2186. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2187. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2188. frustumPlanes[1].normalize();
  2189. // Left
  2190. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2191. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2192. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2193. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2194. frustumPlanes[2].normalize();
  2195. // Right
  2196. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2197. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2198. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2199. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2200. frustumPlanes[3].normalize();
  2201. // Top
  2202. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2203. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2204. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2205. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2206. frustumPlanes[4].normalize();
  2207. // Bottom
  2208. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2209. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2210. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2211. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2212. frustumPlanes[5].normalize();
  2213. };
  2214. return Frustum;
  2215. })();
  2216. BABYLON.Frustum = Frustum;
  2217. var Ray = (function () {
  2218. function Ray(origin, direction, length) {
  2219. if (length === void 0) { length = Number.MAX_VALUE; }
  2220. this.origin = origin;
  2221. this.direction = direction;
  2222. this.length = length;
  2223. }
  2224. // Methods
  2225. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2226. var d = 0.0;
  2227. var maxValue = Number.MAX_VALUE;
  2228. if (Math.abs(this.direction.x) < 0.0000001) {
  2229. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2230. return false;
  2231. }
  2232. }
  2233. else {
  2234. var inv = 1.0 / this.direction.x;
  2235. var min = (minimum.x - this.origin.x) * inv;
  2236. var max = (maximum.x - this.origin.x) * inv;
  2237. if (max === -Infinity) {
  2238. max = Infinity;
  2239. }
  2240. if (min > max) {
  2241. var temp = min;
  2242. min = max;
  2243. max = temp;
  2244. }
  2245. d = Math.max(min, d);
  2246. maxValue = Math.min(max, maxValue);
  2247. if (d > maxValue) {
  2248. return false;
  2249. }
  2250. }
  2251. if (Math.abs(this.direction.y) < 0.0000001) {
  2252. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2253. return false;
  2254. }
  2255. }
  2256. else {
  2257. inv = 1.0 / this.direction.y;
  2258. min = (minimum.y - this.origin.y) * inv;
  2259. max = (maximum.y - this.origin.y) * inv;
  2260. if (max === -Infinity) {
  2261. max = Infinity;
  2262. }
  2263. if (min > max) {
  2264. temp = min;
  2265. min = max;
  2266. max = temp;
  2267. }
  2268. d = Math.max(min, d);
  2269. maxValue = Math.min(max, maxValue);
  2270. if (d > maxValue) {
  2271. return false;
  2272. }
  2273. }
  2274. if (Math.abs(this.direction.z) < 0.0000001) {
  2275. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2276. return false;
  2277. }
  2278. }
  2279. else {
  2280. inv = 1.0 / this.direction.z;
  2281. min = (minimum.z - this.origin.z) * inv;
  2282. max = (maximum.z - this.origin.z) * inv;
  2283. if (max === -Infinity) {
  2284. max = Infinity;
  2285. }
  2286. if (min > max) {
  2287. temp = min;
  2288. min = max;
  2289. max = temp;
  2290. }
  2291. d = Math.max(min, d);
  2292. maxValue = Math.min(max, maxValue);
  2293. if (d > maxValue) {
  2294. return false;
  2295. }
  2296. }
  2297. return true;
  2298. };
  2299. Ray.prototype.intersectsBox = function (box) {
  2300. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2301. };
  2302. Ray.prototype.intersectsSphere = function (sphere) {
  2303. var x = sphere.center.x - this.origin.x;
  2304. var y = sphere.center.y - this.origin.y;
  2305. var z = sphere.center.z - this.origin.z;
  2306. var pyth = (x * x) + (y * y) + (z * z);
  2307. var rr = sphere.radius * sphere.radius;
  2308. if (pyth <= rr) {
  2309. return true;
  2310. }
  2311. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2312. if (dot < 0.0) {
  2313. return false;
  2314. }
  2315. var temp = pyth - (dot * dot);
  2316. return temp <= rr;
  2317. };
  2318. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2319. if (!this._edge1) {
  2320. this._edge1 = Vector3.Zero();
  2321. this._edge2 = Vector3.Zero();
  2322. this._pvec = Vector3.Zero();
  2323. this._tvec = Vector3.Zero();
  2324. this._qvec = Vector3.Zero();
  2325. }
  2326. vertex1.subtractToRef(vertex0, this._edge1);
  2327. vertex2.subtractToRef(vertex0, this._edge2);
  2328. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2329. var det = Vector3.Dot(this._edge1, this._pvec);
  2330. if (det === 0) {
  2331. return null;
  2332. }
  2333. var invdet = 1 / det;
  2334. this.origin.subtractToRef(vertex0, this._tvec);
  2335. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2336. if (bu < 0 || bu > 1.0) {
  2337. return null;
  2338. }
  2339. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2340. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2341. if (bv < 0 || bu + bv > 1.0) {
  2342. return null;
  2343. }
  2344. //check if the distance is longer than the predefined length.
  2345. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2346. if (distance > this.length) {
  2347. return null;
  2348. }
  2349. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2350. };
  2351. // Statics
  2352. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2353. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2354. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2355. var direction = end.subtract(start);
  2356. direction.normalize();
  2357. return new Ray(start, direction);
  2358. };
  2359. /**
  2360. * 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
  2361. * transformed to the given world matrix.
  2362. * @param origin The origin point
  2363. * @param end The end point
  2364. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2365. */
  2366. Ray.CreateNewFromTo = function (origin, end, world) {
  2367. if (world === void 0) { world = Matrix.Identity(); }
  2368. var direction = end.subtract(origin);
  2369. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2370. direction.normalize();
  2371. return Ray.Transform(new Ray(origin, direction, length), world);
  2372. };
  2373. Ray.Transform = function (ray, matrix) {
  2374. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2375. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2376. return new Ray(newOrigin, newDirection, ray.length);
  2377. };
  2378. return Ray;
  2379. })();
  2380. BABYLON.Ray = Ray;
  2381. (function (Space) {
  2382. Space[Space["LOCAL"] = 0] = "LOCAL";
  2383. Space[Space["WORLD"] = 1] = "WORLD";
  2384. })(BABYLON.Space || (BABYLON.Space = {}));
  2385. var Space = BABYLON.Space;
  2386. var Axis = (function () {
  2387. function Axis() {
  2388. }
  2389. Axis.X = new Vector3(1, 0, 0);
  2390. Axis.Y = new Vector3(0, 1, 0);
  2391. Axis.Z = new Vector3(0, 0, 1);
  2392. return Axis;
  2393. })();
  2394. BABYLON.Axis = Axis;
  2395. ;
  2396. var BezierCurve = (function () {
  2397. function BezierCurve() {
  2398. }
  2399. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2400. // Extract X (which is equal to time here)
  2401. var f0 = 1 - 3 * x2 + 3 * x1;
  2402. var f1 = 3 * x2 - 6 * x1;
  2403. var f2 = 3 * x1;
  2404. var refinedT = t;
  2405. for (var i = 0; i < 5; i++) {
  2406. var refinedT2 = refinedT * refinedT;
  2407. var refinedT3 = refinedT2 * refinedT;
  2408. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2409. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2410. refinedT -= (x - t) * slope;
  2411. refinedT = Math.min(1, Math.max(0, refinedT));
  2412. }
  2413. // Resolve cubic bezier for the given x
  2414. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2415. };
  2416. return BezierCurve;
  2417. })();
  2418. BABYLON.BezierCurve = BezierCurve;
  2419. (function (Orientation) {
  2420. Orientation[Orientation["CW"] = 0] = "CW";
  2421. Orientation[Orientation["CCW"] = 1] = "CCW";
  2422. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2423. var Orientation = BABYLON.Orientation;
  2424. var Angle = (function () {
  2425. function Angle(radians) {
  2426. var _this = this;
  2427. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2428. this.radians = function () { return _this._radians; };
  2429. this._radians = radians;
  2430. if (this._radians < 0)
  2431. this._radians += (2 * Math.PI);
  2432. }
  2433. Angle.BetweenTwoPoints = function (a, b) {
  2434. var delta = b.subtract(a);
  2435. var theta = Math.atan2(delta.y, delta.x);
  2436. return new Angle(theta);
  2437. };
  2438. Angle.FromRadians = function (radians) {
  2439. return new Angle(radians);
  2440. };
  2441. Angle.FromDegrees = function (degrees) {
  2442. return new Angle(degrees * Math.PI / 180);
  2443. };
  2444. return Angle;
  2445. })();
  2446. BABYLON.Angle = Angle;
  2447. var Arc2 = (function () {
  2448. function Arc2(startPoint, midPoint, endPoint) {
  2449. this.startPoint = startPoint;
  2450. this.midPoint = midPoint;
  2451. this.endPoint = endPoint;
  2452. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2453. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2454. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2455. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2456. 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);
  2457. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2458. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2459. var a1 = this.startAngle.degrees();
  2460. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2461. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2462. // angles correction
  2463. if (a2 - a1 > +180.0)
  2464. a2 -= 360.0;
  2465. if (a2 - a1 < -180.0)
  2466. a2 += 360.0;
  2467. if (a3 - a2 > +180.0)
  2468. a3 -= 360.0;
  2469. if (a3 - a2 < -180.0)
  2470. a3 += 360.0;
  2471. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2472. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2473. }
  2474. return Arc2;
  2475. })();
  2476. BABYLON.Arc2 = Arc2;
  2477. var PathCursor = (function () {
  2478. function PathCursor(path) {
  2479. this.path = path;
  2480. this._onchange = new Array();
  2481. this.value = 0;
  2482. this.animations = new Array();
  2483. }
  2484. PathCursor.prototype.getPoint = function () {
  2485. var point = this.path.getPointAtLengthPosition(this.value);
  2486. return new Vector3(point.x, 0, point.y);
  2487. };
  2488. PathCursor.prototype.moveAhead = function (step) {
  2489. if (step === void 0) { step = 0.002; }
  2490. this.move(step);
  2491. return this;
  2492. };
  2493. PathCursor.prototype.moveBack = function (step) {
  2494. if (step === void 0) { step = 0.002; }
  2495. this.move(-step);
  2496. return this;
  2497. };
  2498. PathCursor.prototype.move = function (step) {
  2499. if (Math.abs(step) > 1) {
  2500. throw "step size should be less than 1.";
  2501. }
  2502. this.value += step;
  2503. this.ensureLimits();
  2504. this.raiseOnChange();
  2505. return this;
  2506. };
  2507. PathCursor.prototype.ensureLimits = function () {
  2508. while (this.value > 1) {
  2509. this.value -= 1;
  2510. }
  2511. while (this.value < 0) {
  2512. this.value += 1;
  2513. }
  2514. return this;
  2515. };
  2516. // used by animation engine
  2517. PathCursor.prototype.markAsDirty = function (propertyName) {
  2518. this.ensureLimits();
  2519. this.raiseOnChange();
  2520. return this;
  2521. };
  2522. PathCursor.prototype.raiseOnChange = function () {
  2523. var _this = this;
  2524. this._onchange.forEach(function (f) { return f(_this); });
  2525. return this;
  2526. };
  2527. PathCursor.prototype.onchange = function (f) {
  2528. this._onchange.push(f);
  2529. return this;
  2530. };
  2531. return PathCursor;
  2532. })();
  2533. BABYLON.PathCursor = PathCursor;
  2534. var Path2 = (function () {
  2535. function Path2(x, y) {
  2536. this._points = new Array();
  2537. this._length = 0;
  2538. this.closed = false;
  2539. this._points.push(new Vector2(x, y));
  2540. }
  2541. Path2.prototype.addLineTo = function (x, y) {
  2542. if (closed) {
  2543. BABYLON.Tools.Error("cannot add lines to closed paths");
  2544. return this;
  2545. }
  2546. var newPoint = new Vector2(x, y);
  2547. var previousPoint = this._points[this._points.length - 1];
  2548. this._points.push(newPoint);
  2549. this._length += newPoint.subtract(previousPoint).length();
  2550. return this;
  2551. };
  2552. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2553. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2554. if (closed) {
  2555. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2556. return this;
  2557. }
  2558. var startPoint = this._points[this._points.length - 1];
  2559. var midPoint = new Vector2(midX, midY);
  2560. var endPoint = new Vector2(endX, endY);
  2561. var arc = new Arc2(startPoint, midPoint, endPoint);
  2562. var increment = arc.angle.radians() / numberOfSegments;
  2563. if (arc.orientation === 0 /* CW */)
  2564. increment *= -1;
  2565. var currentAngle = arc.startAngle.radians() + increment;
  2566. for (var i = 0; i < numberOfSegments; i++) {
  2567. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2568. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2569. this.addLineTo(x, y);
  2570. currentAngle += increment;
  2571. }
  2572. return this;
  2573. };
  2574. Path2.prototype.close = function () {
  2575. this.closed = true;
  2576. return this;
  2577. };
  2578. Path2.prototype.length = function () {
  2579. var result = this._length;
  2580. if (!this.closed) {
  2581. var lastPoint = this._points[this._points.length - 1];
  2582. var firstPoint = this._points[0];
  2583. result += (firstPoint.subtract(lastPoint).length());
  2584. }
  2585. return result;
  2586. };
  2587. Path2.prototype.getPoints = function () {
  2588. return this._points;
  2589. };
  2590. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2591. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2592. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2593. return Vector2.Zero();
  2594. }
  2595. var lengthPosition = normalizedLengthPosition * this.length();
  2596. var previousOffset = 0;
  2597. for (var i = 0; i < this._points.length; i++) {
  2598. var j = (i + 1) % this._points.length;
  2599. var a = this._points[i];
  2600. var b = this._points[j];
  2601. var bToA = b.subtract(a);
  2602. var nextOffset = (bToA.length() + previousOffset);
  2603. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2604. var dir = bToA.normalize();
  2605. var localOffset = lengthPosition - previousOffset;
  2606. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2607. }
  2608. previousOffset = nextOffset;
  2609. }
  2610. BABYLON.Tools.Error("internal error");
  2611. return Vector2.Zero();
  2612. };
  2613. Path2.StartingAt = function (x, y) {
  2614. return new Path2(x, y);
  2615. };
  2616. return Path2;
  2617. })();
  2618. BABYLON.Path2 = Path2;
  2619. var Path3D = (function () {
  2620. function Path3D(path) {
  2621. this.path = path;
  2622. this._curve = new Array();
  2623. this._distances = new Array();
  2624. this._tangents = new Array();
  2625. this._normals = new Array();
  2626. this._binormals = new Array();
  2627. this._curve = path.slice(); // copy array
  2628. var l = this._curve.length;
  2629. // first and last tangents
  2630. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2631. this._tangents[0].normalize();
  2632. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2633. this._tangents[l - 1].normalize();
  2634. // normals and binormals at first point : arbitrary vector with _normalVector()
  2635. var tg0 = this._tangents[0];
  2636. var pp0 = this._normalVector(this._curve[0], tg0);
  2637. this._normals[0] = pp0;
  2638. this._normals[0].normalize();
  2639. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2640. this._normals[0].normalize();
  2641. this._distances[0] = 0;
  2642. // normals and binormals : next points
  2643. var prev; // previous vector (segment)
  2644. var cur; // current vector (segment)
  2645. var curTang; // current tangent
  2646. var prevNorm; // previous normal
  2647. var prevBinor; // previous binormal
  2648. for (var i = 1; i < l; i++) {
  2649. // tangents
  2650. prev = this._curve[i].subtract(this._curve[i - 1]);
  2651. if (i < l - 1) {
  2652. cur = this._curve[i + 1].subtract(this._curve[i]);
  2653. this._tangents[i] = prev.add(cur);
  2654. this._tangents[i].normalize();
  2655. }
  2656. this._distances[i] = this._distances[i - 1] + prev.length();
  2657. // normals and binormals
  2658. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2659. curTang = this._tangents[i];
  2660. prevNorm = this._normals[i - 1];
  2661. prevBinor = this._binormals[i - 1];
  2662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2663. this._normals[i].normalize();
  2664. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2665. this._binormals[i].normalize();
  2666. }
  2667. }
  2668. Path3D.prototype.getCurve = function () {
  2669. return this._curve;
  2670. };
  2671. Path3D.prototype.getTangents = function () {
  2672. return this._tangents;
  2673. };
  2674. Path3D.prototype.getNormals = function () {
  2675. return this._normals;
  2676. };
  2677. Path3D.prototype.getBinormals = function () {
  2678. return this._binormals;
  2679. };
  2680. Path3D.prototype.getDistances = function () {
  2681. return this._distances;
  2682. };
  2683. // private function normalVector(v0, vt) :
  2684. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2685. Path3D.prototype._normalVector = function (v0, vt) {
  2686. var point;
  2687. if (vt.x !== 1) {
  2688. point = new Vector3(1, 0, 0);
  2689. }
  2690. else if (vt.y !== 1) {
  2691. point = new Vector3(0, 1, 0);
  2692. }
  2693. else if (vt.z !== 1) {
  2694. point = new Vector3(0, 0, 1);
  2695. }
  2696. var normal0 = Vector3.Cross(vt, point);
  2697. normal0.normalize();
  2698. return normal0;
  2699. };
  2700. return Path3D;
  2701. })();
  2702. BABYLON.Path3D = Path3D;
  2703. var Curve3 = (function () {
  2704. function Curve3(points) {
  2705. this._points = points;
  2706. }
  2707. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2708. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  2709. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2710. var bez = new Array();
  2711. var step = 1 / nbPoints;
  2712. var equation = function (t, val0, val1, val2) {
  2713. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2714. return res;
  2715. };
  2716. for (var i = 0; i <= 1; i += step) {
  2717. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x), equation(i, v0.y, v1.y, v2.y), equation(i, v0.z, v1.z, v2.z)));
  2718. }
  2719. return new Curve3(bez);
  2720. };
  2721. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2722. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2723. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2724. var bez = new Array();
  2725. var step = 1 / nbPoints;
  2726. var equation = function (t, val0, val1, val2, val3) {
  2727. var res = (1 - t) * (1 - t) * (1 - t) * val0 + 3 * t * (1 - t) * (1 - t) * val1 + 3 * t * t * (1 - t) * val2 + t * t * t * val3;
  2728. return res;
  2729. };
  2730. for (var i = 0; i <= 1; i += step) {
  2731. bez.push(new Vector3(equation(i, v0.x, v1.x, v2.x, v3.x), equation(i, v0.y, v1.y, v2.y, v3.y), equation(i, v0.z, v1.z, v2.z, v3.z)));
  2732. }
  2733. return new Curve3(bez);
  2734. };
  2735. Curve3.prototype.getPoints = function () {
  2736. return this._points;
  2737. };
  2738. return Curve3;
  2739. })();
  2740. BABYLON.Curve3 = Curve3;
  2741. // SIMD
  2742. if (window.SIMD !== undefined) {
  2743. // Replace functions
  2744. Matrix.prototype.multiplyToArray = Matrix.prototype.multiplyToArraySIMD;
  2745. Matrix.prototype.invertToRef = Matrix.prototype.invertToRefSIMD;
  2746. Matrix.LookAtLHToRef = Matrix.LookAtLHToRefSIMD;
  2747. Vector3.TransformCoordinatesToRef = Vector3.TransformCoordinatesToRefSIMD;
  2748. Vector3.TransformCoordinatesFromFloatsToRef = Vector3.TransformCoordinatesFromFloatsToRefSIMD;
  2749. Object.defineProperty(BABYLON.Vector3.prototype, "x", {
  2750. get: function () {
  2751. return this._data[0];
  2752. },
  2753. set: function (value) {
  2754. if (!this._data) {
  2755. this._data = new Float32Array(3);
  2756. }
  2757. this._data[0] = value;
  2758. }
  2759. });
  2760. Object.defineProperty(BABYLON.Vector3.prototype, "y", {
  2761. get: function () {
  2762. return this._data[1];
  2763. },
  2764. set: function (value) {
  2765. this._data[1] = value;
  2766. }
  2767. });
  2768. Object.defineProperty(BABYLON.Vector3.prototype, "z", {
  2769. get: function () {
  2770. return this._data[2];
  2771. },
  2772. set: function (value) {
  2773. this._data[2] = value;
  2774. }
  2775. });
  2776. }
  2777. })(BABYLON || (BABYLON = {}));
  2778. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2779. (function (BABYLON) {
  2780. // Screenshots
  2781. var screenshotCanvas;
  2782. var cloneValue = function (source, destinationObject) {
  2783. if (!source)
  2784. return null;
  2785. if (source instanceof BABYLON.Mesh) {
  2786. return null;
  2787. }
  2788. if (source instanceof BABYLON.SubMesh) {
  2789. return source.clone(destinationObject);
  2790. }
  2791. else if (source.clone) {
  2792. return source.clone();
  2793. }
  2794. return null;
  2795. };
  2796. var Tools = (function () {
  2797. function Tools() {
  2798. }
  2799. Tools.GetFilename = function (path) {
  2800. var index = path.lastIndexOf("/");
  2801. if (index < 0)
  2802. return path;
  2803. return path.substring(index + 1);
  2804. };
  2805. Tools.GetDOMTextContent = function (element) {
  2806. var result = "";
  2807. var child = element.firstChild;
  2808. while (child) {
  2809. if (child.nodeType === 3) {
  2810. result += child.textContent;
  2811. }
  2812. child = child.nextSibling;
  2813. }
  2814. return result;
  2815. };
  2816. Tools.ToDegrees = function (angle) {
  2817. return angle * 180 / Math.PI;
  2818. };
  2819. Tools.ToRadians = function (angle) {
  2820. return angle * Math.PI / 180;
  2821. };
  2822. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2823. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2824. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2825. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2826. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2827. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2828. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2829. }
  2830. return {
  2831. minimum: minimum,
  2832. maximum: maximum
  2833. };
  2834. };
  2835. Tools.ExtractMinAndMax = function (positions, start, count) {
  2836. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2837. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2838. for (var index = start; index < start + count; index++) {
  2839. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2840. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2841. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2842. }
  2843. return {
  2844. minimum: minimum,
  2845. maximum: maximum
  2846. };
  2847. };
  2848. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2849. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2850. return undefined;
  2851. return Array.isArray(obj) ? obj : [obj];
  2852. };
  2853. // Misc.
  2854. Tools.GetPointerPrefix = function () {
  2855. var eventPrefix = "pointer";
  2856. // Check if hand.js is referenced or if the browser natively supports pointer events
  2857. if (!navigator.pointerEnabled) {
  2858. eventPrefix = "mouse";
  2859. }
  2860. return eventPrefix;
  2861. };
  2862. Tools.QueueNewFrame = function (func) {
  2863. if (window.requestAnimationFrame)
  2864. window.requestAnimationFrame(func);
  2865. else if (window.msRequestAnimationFrame)
  2866. window.msRequestAnimationFrame(func);
  2867. else if (window.webkitRequestAnimationFrame)
  2868. window.webkitRequestAnimationFrame(func);
  2869. else if (window.mozRequestAnimationFrame)
  2870. window.mozRequestAnimationFrame(func);
  2871. else if (window.oRequestAnimationFrame)
  2872. window.oRequestAnimationFrame(func);
  2873. else {
  2874. window.setTimeout(func, 16);
  2875. }
  2876. };
  2877. Tools.RequestFullscreen = function (element) {
  2878. if (element.requestFullscreen)
  2879. element.requestFullscreen();
  2880. else if (element.msRequestFullscreen)
  2881. element.msRequestFullscreen();
  2882. else if (element.webkitRequestFullscreen)
  2883. element.webkitRequestFullscreen();
  2884. else if (element.mozRequestFullScreen)
  2885. element.mozRequestFullScreen();
  2886. };
  2887. Tools.ExitFullscreen = function () {
  2888. if (document.exitFullscreen) {
  2889. document.exitFullscreen();
  2890. }
  2891. else if (document.mozCancelFullScreen) {
  2892. document.mozCancelFullScreen();
  2893. }
  2894. else if (document.webkitCancelFullScreen) {
  2895. document.webkitCancelFullScreen();
  2896. }
  2897. else if (document.msCancelFullScreen) {
  2898. document.msCancelFullScreen();
  2899. }
  2900. };
  2901. // External files
  2902. Tools.CleanUrl = function (url) {
  2903. url = url.replace(/#/mg, "%23");
  2904. return url;
  2905. };
  2906. Tools.LoadImage = function (url, onload, onerror, database) {
  2907. url = Tools.CleanUrl(url);
  2908. var img = new Image();
  2909. if (url.substr(0, 5) !== "data:")
  2910. img.crossOrigin = 'anonymous';
  2911. img.onload = function () {
  2912. onload(img);
  2913. };
  2914. img.onerror = function (err) {
  2915. onerror(img, err);
  2916. };
  2917. var noIndexedDB = function () {
  2918. img.src = url;
  2919. };
  2920. var loadFromIndexedDB = function () {
  2921. database.loadImageFromDB(url, img);
  2922. };
  2923. //ANY database to do!
  2924. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2925. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2926. }
  2927. else {
  2928. if (url.indexOf("file:") === -1) {
  2929. noIndexedDB();
  2930. }
  2931. else {
  2932. try {
  2933. var textureName = url.substring(5);
  2934. var blobURL;
  2935. try {
  2936. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2937. }
  2938. catch (ex) {
  2939. // Chrome doesn't support oneTimeOnly parameter
  2940. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2941. }
  2942. img.src = blobURL;
  2943. }
  2944. catch (e) {
  2945. Tools.Log("Error while trying to load texture: " + textureName);
  2946. img.src = null;
  2947. }
  2948. }
  2949. }
  2950. return img;
  2951. };
  2952. //ANY
  2953. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2954. url = Tools.CleanUrl(url);
  2955. var noIndexedDB = function () {
  2956. var request = new XMLHttpRequest();
  2957. var loadUrl = Tools.BaseUrl + url;
  2958. request.open('GET', loadUrl, true);
  2959. if (useArrayBuffer) {
  2960. request.responseType = "arraybuffer";
  2961. }
  2962. request.onprogress = progressCallBack;
  2963. request.onreadystatechange = function () {
  2964. if (request.readyState === 4) {
  2965. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2966. callback(!useArrayBuffer ? request.responseText : request.response);
  2967. }
  2968. else {
  2969. if (onError) {
  2970. onError();
  2971. }
  2972. else {
  2973. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2974. }
  2975. }
  2976. }
  2977. };
  2978. request.send(null);
  2979. };
  2980. var loadFromIndexedDB = function () {
  2981. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2982. };
  2983. if (url.indexOf("file:") !== -1) {
  2984. var fileName = url.substring(5);
  2985. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2986. }
  2987. else {
  2988. // Caching all files
  2989. if (database && database.enableSceneOffline) {
  2990. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2991. }
  2992. else {
  2993. noIndexedDB();
  2994. }
  2995. }
  2996. };
  2997. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2998. var reader = new FileReader();
  2999. reader.onload = function (e) {
  3000. //target doesn't have result from ts 1.3
  3001. callback(e.target['result']);
  3002. };
  3003. reader.onprogress = progressCallback;
  3004. reader.readAsDataURL(fileToLoad);
  3005. };
  3006. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  3007. var reader = new FileReader();
  3008. reader.onerror = function (e) {
  3009. Tools.Log("Error while reading file: " + fileToLoad.name);
  3010. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  3011. };
  3012. reader.onload = function (e) {
  3013. //target doesn't have result from ts 1.3
  3014. callback(e.target['result']);
  3015. };
  3016. reader.onprogress = progressCallBack;
  3017. if (!useArrayBuffer) {
  3018. // Asynchronous read
  3019. reader.readAsText(fileToLoad);
  3020. }
  3021. else {
  3022. reader.readAsArrayBuffer(fileToLoad);
  3023. }
  3024. };
  3025. // Misc.
  3026. Tools.Clamp = function (value, min, max) {
  3027. if (min === void 0) { min = 0; }
  3028. if (max === void 0) { max = 1; }
  3029. return Math.min(max, Math.max(min, value));
  3030. };
  3031. // Returns -1 when value is a negative number and
  3032. // +1 when value is a positive number.
  3033. Tools.Sign = function (value) {
  3034. value = +value; // convert to a number
  3035. if (value === 0 || isNaN(value))
  3036. return value;
  3037. return value > 0 ? 1 : -1;
  3038. };
  3039. Tools.Format = function (value, decimals) {
  3040. if (decimals === void 0) { decimals = 2; }
  3041. return value.toFixed(decimals);
  3042. };
  3043. Tools.CheckExtends = function (v, min, max) {
  3044. if (v.x < min.x)
  3045. min.x = v.x;
  3046. if (v.y < min.y)
  3047. min.y = v.y;
  3048. if (v.z < min.z)
  3049. min.z = v.z;
  3050. if (v.x > max.x)
  3051. max.x = v.x;
  3052. if (v.y > max.y)
  3053. max.y = v.y;
  3054. if (v.z > max.z)
  3055. max.z = v.z;
  3056. };
  3057. Tools.WithinEpsilon = function (a, b, epsilon) {
  3058. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  3059. var num = a - b;
  3060. return -epsilon <= num && num <= epsilon;
  3061. };
  3062. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  3063. for (var prop in source) {
  3064. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  3065. continue;
  3066. }
  3067. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  3068. continue;
  3069. }
  3070. var sourceValue = source[prop];
  3071. var typeOfSourceValue = typeof sourceValue;
  3072. if (typeOfSourceValue === "function") {
  3073. continue;
  3074. }
  3075. if (typeOfSourceValue === "object") {
  3076. if (sourceValue instanceof Array) {
  3077. destination[prop] = [];
  3078. if (sourceValue.length > 0) {
  3079. if (typeof sourceValue[0] == "object") {
  3080. for (var index = 0; index < sourceValue.length; index++) {
  3081. var clonedValue = cloneValue(sourceValue[index], destination);
  3082. if (destination[prop].indexOf(clonedValue) === -1) {
  3083. destination[prop].push(clonedValue);
  3084. }
  3085. }
  3086. }
  3087. else {
  3088. destination[prop] = sourceValue.slice(0);
  3089. }
  3090. }
  3091. }
  3092. else {
  3093. destination[prop] = cloneValue(sourceValue, destination);
  3094. }
  3095. }
  3096. else {
  3097. destination[prop] = sourceValue;
  3098. }
  3099. }
  3100. };
  3101. Tools.IsEmpty = function (obj) {
  3102. for (var i in obj) {
  3103. return false;
  3104. }
  3105. return true;
  3106. };
  3107. Tools.RegisterTopRootEvents = function (events) {
  3108. for (var index = 0; index < events.length; index++) {
  3109. var event = events[index];
  3110. window.addEventListener(event.name, event.handler, false);
  3111. try {
  3112. if (window.parent) {
  3113. window.parent.addEventListener(event.name, event.handler, false);
  3114. }
  3115. }
  3116. catch (e) {
  3117. }
  3118. }
  3119. };
  3120. Tools.UnregisterTopRootEvents = function (events) {
  3121. for (var index = 0; index < events.length; index++) {
  3122. var event = events[index];
  3123. window.removeEventListener(event.name, event.handler);
  3124. try {
  3125. if (window.parent) {
  3126. window.parent.removeEventListener(event.name, event.handler);
  3127. }
  3128. }
  3129. catch (e) {
  3130. }
  3131. }
  3132. };
  3133. Tools.DumpFramebuffer = function (width, height, engine) {
  3134. // Read the contents of the framebuffer
  3135. var numberOfChannelsByLine = width * 4;
  3136. var halfHeight = height / 2;
  3137. //Reading datas from WebGL
  3138. var data = engine.readPixels(0, 0, width, height);
  3139. for (var i = 0; i < halfHeight; i++) {
  3140. for (var j = 0; j < numberOfChannelsByLine; j++) {
  3141. var currentCell = j + i * numberOfChannelsByLine;
  3142. var targetLine = height - i - 1;
  3143. var targetCell = j + targetLine * numberOfChannelsByLine;
  3144. var temp = data[currentCell];
  3145. data[currentCell] = data[targetCell];
  3146. data[targetCell] = temp;
  3147. }
  3148. }
  3149. // Create a 2D canvas to store the result
  3150. if (!screenshotCanvas) {
  3151. screenshotCanvas = document.createElement('canvas');
  3152. }
  3153. screenshotCanvas.width = width;
  3154. screenshotCanvas.height = height;
  3155. var context = screenshotCanvas.getContext('2d');
  3156. // Copy the pixels to a 2D canvas
  3157. var imageData = context.createImageData(width, height);
  3158. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  3159. var castData = imageData.data;
  3160. castData.set(data);
  3161. context.putImageData(imageData, 0, 0);
  3162. var base64Image = screenshotCanvas.toDataURL();
  3163. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  3164. if (("download" in document.createElement("a"))) {
  3165. var a = window.document.createElement("a");
  3166. a.href = base64Image;
  3167. var date = new Date();
  3168. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  3169. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  3170. window.document.body.appendChild(a);
  3171. a.addEventListener("click", function () {
  3172. a.parentElement.removeChild(a);
  3173. });
  3174. a.click();
  3175. }
  3176. else {
  3177. var newWindow = window.open("");
  3178. var img = newWindow.document.createElement("img");
  3179. img.src = base64Image;
  3180. newWindow.document.body.appendChild(img);
  3181. }
  3182. };
  3183. Tools.CreateScreenshot = function (engine, camera, size) {
  3184. var width;
  3185. var height;
  3186. var scene = camera.getScene();
  3187. var previousCamera = null;
  3188. if (scene.activeCamera !== camera) {
  3189. previousCamera = scene.activeCamera;
  3190. scene.activeCamera = camera;
  3191. }
  3192. //If a precision value is specified
  3193. if (size.precision) {
  3194. width = Math.round(engine.getRenderWidth() * size.precision);
  3195. height = Math.round(width / engine.getAspectRatio(camera));
  3196. size = { width: width, height: height };
  3197. }
  3198. else if (size.width && size.height) {
  3199. width = size.width;
  3200. height = size.height;
  3201. }
  3202. else if (size.width && !size.height) {
  3203. width = size.width;
  3204. height = Math.round(width / engine.getAspectRatio(camera));
  3205. size = { width: width, height: height };
  3206. }
  3207. else if (size.height && !size.width) {
  3208. height = size.height;
  3209. width = Math.round(height * engine.getAspectRatio(camera));
  3210. size = { width: width, height: height };
  3211. }
  3212. else if (!isNaN(size)) {
  3213. height = size;
  3214. width = size;
  3215. }
  3216. else {
  3217. Tools.Error("Invalid 'size' parameter !");
  3218. return;
  3219. }
  3220. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  3221. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  3222. texture.renderList = scene.meshes;
  3223. texture.onAfterRender = function () {
  3224. Tools.DumpFramebuffer(width, height, engine);
  3225. };
  3226. scene.incrementRenderId();
  3227. texture.render(true);
  3228. texture.dispose();
  3229. if (previousCamera) {
  3230. scene.activeCamera = previousCamera;
  3231. }
  3232. };
  3233. // XHR response validator for local file scenario
  3234. Tools.ValidateXHRData = function (xhr, dataType) {
  3235. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  3236. if (dataType === void 0) { dataType = 7; }
  3237. try {
  3238. if (dataType & 1) {
  3239. if (xhr.responseText && xhr.responseText.length > 0) {
  3240. return true;
  3241. }
  3242. else if (dataType === 1) {
  3243. return false;
  3244. }
  3245. }
  3246. if (dataType & 2) {
  3247. // Check header width and height since there is no "TGA" magic number
  3248. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3249. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3250. return true;
  3251. }
  3252. else if (dataType === 2) {
  3253. return false;
  3254. }
  3255. }
  3256. if (dataType & 4) {
  3257. // Check for the "DDS" magic number
  3258. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3259. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3260. return true;
  3261. }
  3262. else {
  3263. return false;
  3264. }
  3265. }
  3266. }
  3267. catch (e) {
  3268. }
  3269. return false;
  3270. };
  3271. Object.defineProperty(Tools, "NoneLogLevel", {
  3272. get: function () {
  3273. return Tools._NoneLogLevel;
  3274. },
  3275. enumerable: true,
  3276. configurable: true
  3277. });
  3278. Object.defineProperty(Tools, "MessageLogLevel", {
  3279. get: function () {
  3280. return Tools._MessageLogLevel;
  3281. },
  3282. enumerable: true,
  3283. configurable: true
  3284. });
  3285. Object.defineProperty(Tools, "WarningLogLevel", {
  3286. get: function () {
  3287. return Tools._WarningLogLevel;
  3288. },
  3289. enumerable: true,
  3290. configurable: true
  3291. });
  3292. Object.defineProperty(Tools, "ErrorLogLevel", {
  3293. get: function () {
  3294. return Tools._ErrorLogLevel;
  3295. },
  3296. enumerable: true,
  3297. configurable: true
  3298. });
  3299. Object.defineProperty(Tools, "AllLogLevel", {
  3300. get: function () {
  3301. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3302. },
  3303. enumerable: true,
  3304. configurable: true
  3305. });
  3306. Tools._AddLogEntry = function (entry) {
  3307. Tools._LogCache = entry + Tools._LogCache;
  3308. if (Tools.OnNewCacheEntry) {
  3309. Tools.OnNewCacheEntry(entry);
  3310. }
  3311. };
  3312. Tools._FormatMessage = function (message) {
  3313. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3314. var date = new Date();
  3315. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3316. };
  3317. Tools._LogDisabled = function (message) {
  3318. // nothing to do
  3319. };
  3320. Tools._LogEnabled = function (message) {
  3321. var formattedMessage = Tools._FormatMessage(message);
  3322. console.log("BJS - " + formattedMessage);
  3323. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3324. Tools._AddLogEntry(entry);
  3325. };
  3326. Tools._WarnDisabled = function (message) {
  3327. // nothing to do
  3328. };
  3329. Tools._WarnEnabled = function (message) {
  3330. var formattedMessage = Tools._FormatMessage(message);
  3331. console.warn("BJS - " + formattedMessage);
  3332. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3333. Tools._AddLogEntry(entry);
  3334. };
  3335. Tools._ErrorDisabled = function (message) {
  3336. // nothing to do
  3337. };
  3338. Tools._ErrorEnabled = function (message) {
  3339. var formattedMessage = Tools._FormatMessage(message);
  3340. console.error("BJS - " + formattedMessage);
  3341. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3342. Tools._AddLogEntry(entry);
  3343. };
  3344. Object.defineProperty(Tools, "LogCache", {
  3345. get: function () {
  3346. return Tools._LogCache;
  3347. },
  3348. enumerable: true,
  3349. configurable: true
  3350. });
  3351. Object.defineProperty(Tools, "LogLevels", {
  3352. set: function (level) {
  3353. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3354. Tools.Log = Tools._LogEnabled;
  3355. }
  3356. else {
  3357. Tools.Log = Tools._LogDisabled;
  3358. }
  3359. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3360. Tools.Warn = Tools._WarnEnabled;
  3361. }
  3362. else {
  3363. Tools.Warn = Tools._WarnDisabled;
  3364. }
  3365. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3366. Tools.Error = Tools._ErrorEnabled;
  3367. }
  3368. else {
  3369. Tools.Error = Tools._ErrorDisabled;
  3370. }
  3371. },
  3372. enumerable: true,
  3373. configurable: true
  3374. });
  3375. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3376. get: function () {
  3377. return Tools._PerformanceNoneLogLevel;
  3378. },
  3379. enumerable: true,
  3380. configurable: true
  3381. });
  3382. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3383. get: function () {
  3384. return Tools._PerformanceUserMarkLogLevel;
  3385. },
  3386. enumerable: true,
  3387. configurable: true
  3388. });
  3389. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3390. get: function () {
  3391. return Tools._PerformanceConsoleLogLevel;
  3392. },
  3393. enumerable: true,
  3394. configurable: true
  3395. });
  3396. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3397. set: function (level) {
  3398. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3399. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3400. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3401. return;
  3402. }
  3403. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3404. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3405. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3406. return;
  3407. }
  3408. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3409. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3410. },
  3411. enumerable: true,
  3412. configurable: true
  3413. });
  3414. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3415. };
  3416. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3417. };
  3418. Tools._StartUserMark = function (counterName, condition) {
  3419. if (condition === void 0) { condition = true; }
  3420. if (!condition || !Tools._performance.mark) {
  3421. return;
  3422. }
  3423. Tools._performance.mark(counterName + "-Begin");
  3424. };
  3425. Tools._EndUserMark = function (counterName, condition) {
  3426. if (condition === void 0) { condition = true; }
  3427. if (!condition || !Tools._performance.mark) {
  3428. return;
  3429. }
  3430. Tools._performance.mark(counterName + "-End");
  3431. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3432. };
  3433. Tools._StartPerformanceConsole = function (counterName, condition) {
  3434. if (condition === void 0) { condition = true; }
  3435. if (!condition) {
  3436. return;
  3437. }
  3438. Tools._StartUserMark(counterName, condition);
  3439. if (console.time) {
  3440. console.time(counterName);
  3441. }
  3442. };
  3443. Tools._EndPerformanceConsole = function (counterName, condition) {
  3444. if (condition === void 0) { condition = true; }
  3445. if (!condition) {
  3446. return;
  3447. }
  3448. Tools._EndUserMark(counterName, condition);
  3449. if (console.time) {
  3450. console.timeEnd(counterName);
  3451. }
  3452. };
  3453. Object.defineProperty(Tools, "Now", {
  3454. get: function () {
  3455. if (window.performance && window.performance.now) {
  3456. return window.performance.now();
  3457. }
  3458. return new Date().getTime();
  3459. },
  3460. enumerable: true,
  3461. configurable: true
  3462. });
  3463. // Deprecated
  3464. Tools.GetFps = function () {
  3465. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3466. return 0;
  3467. };
  3468. Tools.BaseUrl = "";
  3469. Tools.GetExponantOfTwo = function (value, max) {
  3470. var count = 1;
  3471. do {
  3472. count *= 2;
  3473. } while (count < value);
  3474. if (count > max)
  3475. count = max;
  3476. return count;
  3477. };
  3478. // Logs
  3479. Tools._NoneLogLevel = 0;
  3480. Tools._MessageLogLevel = 1;
  3481. Tools._WarningLogLevel = 2;
  3482. Tools._ErrorLogLevel = 4;
  3483. Tools._LogCache = "";
  3484. Tools.Log = Tools._LogEnabled;
  3485. Tools.Warn = Tools._WarnEnabled;
  3486. Tools.Error = Tools._ErrorEnabled;
  3487. // Performances
  3488. Tools._PerformanceNoneLogLevel = 0;
  3489. Tools._PerformanceUserMarkLogLevel = 1;
  3490. Tools._PerformanceConsoleLogLevel = 2;
  3491. Tools._performance = window.performance;
  3492. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3493. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3494. return Tools;
  3495. })();
  3496. BABYLON.Tools = Tools;
  3497. /**
  3498. * An implementation of a loop for asynchronous functions.
  3499. */
  3500. var AsyncLoop = (function () {
  3501. /**
  3502. * Constroctor.
  3503. * @param iterations the number of iterations.
  3504. * @param _fn the function to run each iteration
  3505. * @param _successCallback the callback that will be called upon succesful execution
  3506. * @param offset starting offset.
  3507. */
  3508. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3509. if (offset === void 0) { offset = 0; }
  3510. this.iterations = iterations;
  3511. this._fn = _fn;
  3512. this._successCallback = _successCallback;
  3513. this.index = offset - 1;
  3514. this._done = false;
  3515. }
  3516. /**
  3517. * Execute the next iteration. Must be called after the last iteration was finished.
  3518. */
  3519. AsyncLoop.prototype.executeNext = function () {
  3520. if (!this._done) {
  3521. if (this.index + 1 < this.iterations) {
  3522. ++this.index;
  3523. this._fn(this);
  3524. }
  3525. else {
  3526. this.breakLoop();
  3527. }
  3528. }
  3529. };
  3530. /**
  3531. * Break the loop and run the success callback.
  3532. */
  3533. AsyncLoop.prototype.breakLoop = function () {
  3534. this._done = true;
  3535. this._successCallback();
  3536. };
  3537. /**
  3538. * Helper function
  3539. */
  3540. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3541. if (offset === void 0) { offset = 0; }
  3542. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3543. loop.executeNext();
  3544. return loop;
  3545. };
  3546. /**
  3547. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3548. * @param iterations total number of iterations
  3549. * @param syncedIterations number of synchronous iterations in each async iteration.
  3550. * @param fn the function to call each iteration.
  3551. * @param callback a success call back that will be called when iterating stops.
  3552. * @param breakFunction a break condition (optional)
  3553. * @param timeout timeout settings for the setTimeout function. default - 0.
  3554. * @constructor
  3555. */
  3556. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3557. if (timeout === void 0) { timeout = 0; }
  3558. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3559. if (breakFunction && breakFunction())
  3560. loop.breakLoop();
  3561. else {
  3562. setTimeout(function () {
  3563. for (var i = 0; i < syncedIterations; ++i) {
  3564. var iteration = (loop.index * syncedIterations) + i;
  3565. if (iteration >= iterations)
  3566. break;
  3567. fn(iteration);
  3568. if (breakFunction && breakFunction()) {
  3569. loop.breakLoop();
  3570. break;
  3571. }
  3572. }
  3573. loop.executeNext();
  3574. }, timeout);
  3575. }
  3576. }, callback);
  3577. };
  3578. return AsyncLoop;
  3579. })();
  3580. BABYLON.AsyncLoop = AsyncLoop;
  3581. })(BABYLON || (BABYLON = {}));
  3582. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3583. (function (BABYLON) {
  3584. var _DepthCullingState = (function () {
  3585. function _DepthCullingState() {
  3586. this._isDepthTestDirty = false;
  3587. this._isDepthMaskDirty = false;
  3588. this._isDepthFuncDirty = false;
  3589. this._isCullFaceDirty = false;
  3590. this._isCullDirty = false;
  3591. }
  3592. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3593. get: function () {
  3594. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3595. },
  3596. enumerable: true,
  3597. configurable: true
  3598. });
  3599. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3600. get: function () {
  3601. return this._cullFace;
  3602. },
  3603. set: function (value) {
  3604. if (this._cullFace === value) {
  3605. return;
  3606. }
  3607. this._cullFace = value;
  3608. this._isCullFaceDirty = true;
  3609. },
  3610. enumerable: true,
  3611. configurable: true
  3612. });
  3613. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3614. get: function () {
  3615. return this._cull;
  3616. },
  3617. set: function (value) {
  3618. if (this._cull === value) {
  3619. return;
  3620. }
  3621. this._cull = value;
  3622. this._isCullDirty = true;
  3623. },
  3624. enumerable: true,
  3625. configurable: true
  3626. });
  3627. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3628. get: function () {
  3629. return this._depthFunc;
  3630. },
  3631. set: function (value) {
  3632. if (this._depthFunc === value) {
  3633. return;
  3634. }
  3635. this._depthFunc = value;
  3636. this._isDepthFuncDirty = true;
  3637. },
  3638. enumerable: true,
  3639. configurable: true
  3640. });
  3641. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3642. get: function () {
  3643. return this._depthMask;
  3644. },
  3645. set: function (value) {
  3646. if (this._depthMask === value) {
  3647. return;
  3648. }
  3649. this._depthMask = value;
  3650. this._isDepthMaskDirty = true;
  3651. },
  3652. enumerable: true,
  3653. configurable: true
  3654. });
  3655. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3656. get: function () {
  3657. return this._depthTest;
  3658. },
  3659. set: function (value) {
  3660. if (this._depthTest === value) {
  3661. return;
  3662. }
  3663. this._depthTest = value;
  3664. this._isDepthTestDirty = true;
  3665. },
  3666. enumerable: true,
  3667. configurable: true
  3668. });
  3669. _DepthCullingState.prototype.reset = function () {
  3670. this._depthMask = true;
  3671. this._depthTest = true;
  3672. this._depthFunc = null;
  3673. this._cull = null;
  3674. this._cullFace = null;
  3675. this._isDepthTestDirty = true;
  3676. this._isDepthMaskDirty = true;
  3677. this._isDepthFuncDirty = false;
  3678. this._isCullFaceDirty = false;
  3679. this._isCullDirty = false;
  3680. };
  3681. _DepthCullingState.prototype.apply = function (gl) {
  3682. if (!this.isDirty) {
  3683. return;
  3684. }
  3685. // Cull
  3686. if (this._isCullDirty) {
  3687. if (this.cull) {
  3688. gl.enable(gl.CULL_FACE);
  3689. }
  3690. else {
  3691. gl.disable(gl.CULL_FACE);
  3692. }
  3693. this._isCullDirty = false;
  3694. }
  3695. // Cull face
  3696. if (this._isCullFaceDirty) {
  3697. gl.cullFace(this.cullFace);
  3698. this._isCullFaceDirty = false;
  3699. }
  3700. // Depth mask
  3701. if (this._isDepthMaskDirty) {
  3702. gl.depthMask(this.depthMask);
  3703. this._isDepthMaskDirty = false;
  3704. }
  3705. // Depth test
  3706. if (this._isDepthTestDirty) {
  3707. if (this.depthTest) {
  3708. gl.enable(gl.DEPTH_TEST);
  3709. }
  3710. else {
  3711. gl.disable(gl.DEPTH_TEST);
  3712. }
  3713. this._isDepthTestDirty = false;
  3714. }
  3715. // Depth func
  3716. if (this._isDepthFuncDirty) {
  3717. gl.depthFunc(this.depthFunc);
  3718. this._isDepthFuncDirty = false;
  3719. }
  3720. };
  3721. return _DepthCullingState;
  3722. })();
  3723. BABYLON._DepthCullingState = _DepthCullingState;
  3724. var _AlphaState = (function () {
  3725. function _AlphaState() {
  3726. this._isAlphaBlendDirty = false;
  3727. this._isBlendFunctionParametersDirty = false;
  3728. this._alphaBlend = false;
  3729. this._blendFunctionParameters = new Array(4);
  3730. }
  3731. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3732. get: function () {
  3733. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3734. },
  3735. enumerable: true,
  3736. configurable: true
  3737. });
  3738. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3739. get: function () {
  3740. return this._alphaBlend;
  3741. },
  3742. set: function (value) {
  3743. if (this._alphaBlend === value) {
  3744. return;
  3745. }
  3746. this._alphaBlend = value;
  3747. this._isAlphaBlendDirty = true;
  3748. },
  3749. enumerable: true,
  3750. configurable: true
  3751. });
  3752. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3753. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3754. return;
  3755. }
  3756. this._blendFunctionParameters[0] = value0;
  3757. this._blendFunctionParameters[1] = value1;
  3758. this._blendFunctionParameters[2] = value2;
  3759. this._blendFunctionParameters[3] = value3;
  3760. this._isBlendFunctionParametersDirty = true;
  3761. };
  3762. _AlphaState.prototype.reset = function () {
  3763. this._alphaBlend = false;
  3764. this._blendFunctionParameters[0] = null;
  3765. this._blendFunctionParameters[1] = null;
  3766. this._blendFunctionParameters[2] = null;
  3767. this._blendFunctionParameters[3] = null;
  3768. this._isAlphaBlendDirty = true;
  3769. this._isBlendFunctionParametersDirty = false;
  3770. };
  3771. _AlphaState.prototype.apply = function (gl) {
  3772. if (!this.isDirty) {
  3773. return;
  3774. }
  3775. // Alpha blend
  3776. if (this._isAlphaBlendDirty) {
  3777. if (this._alphaBlend) {
  3778. gl.enable(gl.BLEND);
  3779. }
  3780. else {
  3781. gl.disable(gl.BLEND);
  3782. }
  3783. this._isAlphaBlendDirty = false;
  3784. }
  3785. // Alpha function
  3786. if (this._isBlendFunctionParametersDirty) {
  3787. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3788. this._isBlendFunctionParametersDirty = false;
  3789. }
  3790. };
  3791. return _AlphaState;
  3792. })();
  3793. BABYLON._AlphaState = _AlphaState;
  3794. var compileShader = function (gl, source, type, defines) {
  3795. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3796. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3797. gl.compileShader(shader);
  3798. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3799. throw new Error(gl.getShaderInfoLog(shader));
  3800. }
  3801. return shader;
  3802. };
  3803. var getWebGLTextureType = function (gl, type) {
  3804. var textureType = gl.UNSIGNED_BYTE;
  3805. if (type === Engine.TEXTURETYPE_FLOAT)
  3806. textureType = gl.FLOAT;
  3807. return textureType;
  3808. };
  3809. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3810. var magFilter = gl.NEAREST;
  3811. var minFilter = gl.NEAREST;
  3812. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3813. magFilter = gl.LINEAR;
  3814. if (generateMipMaps) {
  3815. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3816. }
  3817. else {
  3818. minFilter = gl.LINEAR;
  3819. }
  3820. }
  3821. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3822. magFilter = gl.LINEAR;
  3823. if (generateMipMaps) {
  3824. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3825. }
  3826. else {
  3827. minFilter = gl.LINEAR;
  3828. }
  3829. }
  3830. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3831. magFilter = gl.NEAREST;
  3832. if (generateMipMaps) {
  3833. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3834. }
  3835. else {
  3836. minFilter = gl.NEAREST;
  3837. }
  3838. }
  3839. return {
  3840. min: minFilter,
  3841. mag: magFilter
  3842. };
  3843. };
  3844. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3846. var engine = scene.getEngine();
  3847. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3848. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3849. gl.bindTexture(gl.TEXTURE_2D, texture);
  3850. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3851. processFunction(potWidth, potHeight);
  3852. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3853. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3855. if (!noMipmap && !isCompressed) {
  3856. gl.generateMipmap(gl.TEXTURE_2D);
  3857. }
  3858. gl.bindTexture(gl.TEXTURE_2D, null);
  3859. engine._activeTexturesCache = [];
  3860. texture._baseWidth = width;
  3861. texture._baseHeight = height;
  3862. texture._width = potWidth;
  3863. texture._height = potHeight;
  3864. texture.isReady = true;
  3865. texture.samplingMode = samplingMode;
  3866. scene._removePendingData(texture);
  3867. };
  3868. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3869. var onload = function () {
  3870. loadedImages[index] = img;
  3871. loadedImages._internalCount++;
  3872. scene._removePendingData(img);
  3873. if (loadedImages._internalCount === 6) {
  3874. onfinish(loadedImages);
  3875. }
  3876. };
  3877. var onerror = function () {
  3878. scene._removePendingData(img);
  3879. };
  3880. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3881. scene._addPendingData(img);
  3882. };
  3883. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3884. var loadedImages = [];
  3885. loadedImages._internalCount = 0;
  3886. for (var index = 0; index < 6; index++) {
  3887. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3888. }
  3889. };
  3890. var EngineCapabilities = (function () {
  3891. function EngineCapabilities() {
  3892. }
  3893. return EngineCapabilities;
  3894. })();
  3895. BABYLON.EngineCapabilities = EngineCapabilities;
  3896. /**
  3897. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3898. */
  3899. var Engine = (function () {
  3900. /**
  3901. * @constructor
  3902. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3903. * @param {boolean} [antialias] - enable antialias
  3904. * @param options - further options to be sent to the getContext function
  3905. */
  3906. function Engine(canvas, antialias, options) {
  3907. var _this = this;
  3908. // Public members
  3909. this.isFullscreen = false;
  3910. this.isPointerLock = false;
  3911. this.cullBackFaces = true;
  3912. this.renderEvenInBackground = true;
  3913. this.scenes = new Array();
  3914. this._windowIsBackground = false;
  3915. this._loadingDivBackgroundColor = "black";
  3916. this._drawCalls = 0;
  3917. this._renderingQueueLaunched = false;
  3918. this._activeRenderLoops = [];
  3919. // FPS
  3920. this.fpsRange = 60;
  3921. this.previousFramesDuration = [];
  3922. this.fps = 60;
  3923. this.deltaTime = 0;
  3924. // States
  3925. this._depthCullingState = new _DepthCullingState();
  3926. this._alphaState = new _AlphaState();
  3927. this._alphaMode = Engine.ALPHA_DISABLE;
  3928. // Cache
  3929. this._loadedTexturesCache = new Array();
  3930. this._activeTexturesCache = new Array();
  3931. this._compiledEffects = {};
  3932. this._uintIndicesCurrentlySet = false;
  3933. this._renderingCanvas = canvas;
  3934. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3935. options = options || {};
  3936. options.antialias = antialias;
  3937. try {
  3938. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3939. }
  3940. catch (e) {
  3941. throw new Error("WebGL not supported");
  3942. }
  3943. if (!this._gl) {
  3944. throw new Error("WebGL not supported");
  3945. }
  3946. this._onBlur = function () {
  3947. _this._windowIsBackground = true;
  3948. };
  3949. this._onFocus = function () {
  3950. _this._windowIsBackground = false;
  3951. };
  3952. window.addEventListener("blur", this._onBlur);
  3953. window.addEventListener("focus", this._onFocus);
  3954. // Textures
  3955. this._workingCanvas = document.createElement("canvas");
  3956. this._workingContext = this._workingCanvas.getContext("2d");
  3957. // Viewport
  3958. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3959. this.resize();
  3960. // Caps
  3961. this._caps = new EngineCapabilities();
  3962. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3963. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3964. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3965. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3966. // Infos
  3967. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3968. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3969. if (rendererInfo != null) {
  3970. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3971. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3972. }
  3973. if (!this._glVendor) {
  3974. this._glVendor = "Unknown vendor";
  3975. }
  3976. if (!this._glRenderer) {
  3977. this._glRenderer = "Unknown renderer";
  3978. }
  3979. // Extensions
  3980. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3981. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3982. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3983. 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');
  3984. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3985. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3986. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3987. // Depth buffer
  3988. this.setDepthBuffer(true);
  3989. this.setDepthFunctionToLessOrEqual();
  3990. this.setDepthWrite(true);
  3991. // Fullscreen
  3992. this._onFullscreenChange = function () {
  3993. if (document.fullscreen !== undefined) {
  3994. _this.isFullscreen = document.fullscreen;
  3995. }
  3996. else if (document.mozFullScreen !== undefined) {
  3997. _this.isFullscreen = document.mozFullScreen;
  3998. }
  3999. else if (document.webkitIsFullScreen !== undefined) {
  4000. _this.isFullscreen = document.webkitIsFullScreen;
  4001. }
  4002. else if (document.msIsFullScreen !== undefined) {
  4003. _this.isFullscreen = document.msIsFullScreen;
  4004. }
  4005. // Pointer lock
  4006. if (_this.isFullscreen && _this._pointerLockRequested) {
  4007. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  4008. if (canvas.requestPointerLock) {
  4009. canvas.requestPointerLock();
  4010. }
  4011. }
  4012. };
  4013. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  4014. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  4015. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  4016. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  4017. // Pointer lock
  4018. this._onPointerLockChange = function () {
  4019. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  4020. };
  4021. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  4022. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  4023. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  4024. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  4025. if (!Engine.audioEngine) {
  4026. Engine.audioEngine = new BABYLON.AudioEngine();
  4027. }
  4028. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  4029. }
  4030. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  4031. get: function () {
  4032. return Engine._ALPHA_DISABLE;
  4033. },
  4034. enumerable: true,
  4035. configurable: true
  4036. });
  4037. Object.defineProperty(Engine, "ALPHA_ADD", {
  4038. get: function () {
  4039. return Engine._ALPHA_ADD;
  4040. },
  4041. enumerable: true,
  4042. configurable: true
  4043. });
  4044. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  4045. get: function () {
  4046. return Engine._ALPHA_COMBINE;
  4047. },
  4048. enumerable: true,
  4049. configurable: true
  4050. });
  4051. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  4052. get: function () {
  4053. return Engine._DELAYLOADSTATE_NONE;
  4054. },
  4055. enumerable: true,
  4056. configurable: true
  4057. });
  4058. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  4059. get: function () {
  4060. return Engine._DELAYLOADSTATE_LOADED;
  4061. },
  4062. enumerable: true,
  4063. configurable: true
  4064. });
  4065. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  4066. get: function () {
  4067. return Engine._DELAYLOADSTATE_LOADING;
  4068. },
  4069. enumerable: true,
  4070. configurable: true
  4071. });
  4072. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  4073. get: function () {
  4074. return Engine._DELAYLOADSTATE_NOTLOADED;
  4075. },
  4076. enumerable: true,
  4077. configurable: true
  4078. });
  4079. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  4080. get: function () {
  4081. return Engine._TEXTUREFORMAT_ALPHA;
  4082. },
  4083. enumerable: true,
  4084. configurable: true
  4085. });
  4086. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  4087. get: function () {
  4088. return Engine._TEXTUREFORMAT_LUMINANCE;
  4089. },
  4090. enumerable: true,
  4091. configurable: true
  4092. });
  4093. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  4094. get: function () {
  4095. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  4096. },
  4097. enumerable: true,
  4098. configurable: true
  4099. });
  4100. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  4101. get: function () {
  4102. return Engine._TEXTUREFORMAT_RGB;
  4103. },
  4104. enumerable: true,
  4105. configurable: true
  4106. });
  4107. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  4108. get: function () {
  4109. return Engine._TEXTUREFORMAT_RGBA;
  4110. },
  4111. enumerable: true,
  4112. configurable: true
  4113. });
  4114. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  4115. get: function () {
  4116. return Engine._TEXTURETYPE_UNSIGNED_INT;
  4117. },
  4118. enumerable: true,
  4119. configurable: true
  4120. });
  4121. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  4122. get: function () {
  4123. return Engine._TEXTURETYPE_FLOAT;
  4124. },
  4125. enumerable: true,
  4126. configurable: true
  4127. });
  4128. Object.defineProperty(Engine, "Version", {
  4129. get: function () {
  4130. return "2.1.0 alpha";
  4131. },
  4132. enumerable: true,
  4133. configurable: true
  4134. });
  4135. Engine.prototype.getGlInfo = function () {
  4136. return {
  4137. vendor: this._glVendor,
  4138. renderer: this._glRenderer,
  4139. version: this._glVersion
  4140. };
  4141. };
  4142. Engine.prototype.getAspectRatio = function (camera) {
  4143. var viewport = camera.viewport;
  4144. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  4145. };
  4146. Engine.prototype.getRenderWidth = function () {
  4147. if (this._currentRenderTarget) {
  4148. return this._currentRenderTarget._width;
  4149. }
  4150. return this._renderingCanvas.width;
  4151. };
  4152. Engine.prototype.getRenderHeight = function () {
  4153. if (this._currentRenderTarget) {
  4154. return this._currentRenderTarget._height;
  4155. }
  4156. return this._renderingCanvas.height;
  4157. };
  4158. Engine.prototype.getRenderingCanvas = function () {
  4159. return this._renderingCanvas;
  4160. };
  4161. Engine.prototype.getRenderingCanvasClientRect = function () {
  4162. return this._renderingCanvas.getBoundingClientRect();
  4163. };
  4164. Engine.prototype.setHardwareScalingLevel = function (level) {
  4165. this._hardwareScalingLevel = level;
  4166. this.resize();
  4167. };
  4168. Engine.prototype.getHardwareScalingLevel = function () {
  4169. return this._hardwareScalingLevel;
  4170. };
  4171. Engine.prototype.getLoadedTexturesCache = function () {
  4172. return this._loadedTexturesCache;
  4173. };
  4174. Engine.prototype.getCaps = function () {
  4175. return this._caps;
  4176. };
  4177. Object.defineProperty(Engine.prototype, "drawCalls", {
  4178. get: function () {
  4179. return this._drawCalls;
  4180. },
  4181. enumerable: true,
  4182. configurable: true
  4183. });
  4184. // Methods
  4185. Engine.prototype.resetDrawCalls = function () {
  4186. this._drawCalls = 0;
  4187. };
  4188. Engine.prototype.setDepthFunctionToGreater = function () {
  4189. this._depthCullingState.depthFunc = this._gl.GREATER;
  4190. };
  4191. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  4192. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  4193. };
  4194. Engine.prototype.setDepthFunctionToLess = function () {
  4195. this._depthCullingState.depthFunc = this._gl.LESS;
  4196. };
  4197. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  4198. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  4199. };
  4200. /**
  4201. * stop executing a render loop function and remove it from the execution array
  4202. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  4203. */
  4204. Engine.prototype.stopRenderLoop = function (renderFunction) {
  4205. if (!renderFunction) {
  4206. this._activeRenderLoops = [];
  4207. return;
  4208. }
  4209. var index = this._activeRenderLoops.indexOf(renderFunction);
  4210. if (index >= 0) {
  4211. this._activeRenderLoops.splice(index, 1);
  4212. }
  4213. };
  4214. Engine.prototype._renderLoop = function () {
  4215. var _this = this;
  4216. var shouldRender = true;
  4217. if (!this.renderEvenInBackground && this._windowIsBackground) {
  4218. shouldRender = false;
  4219. }
  4220. if (shouldRender) {
  4221. // Start new frame
  4222. this.beginFrame();
  4223. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  4224. var renderFunction = this._activeRenderLoops[index];
  4225. renderFunction();
  4226. }
  4227. // Present
  4228. this.endFrame();
  4229. }
  4230. if (this._activeRenderLoops.length > 0) {
  4231. // Register new frame
  4232. BABYLON.Tools.QueueNewFrame(function () {
  4233. _this._renderLoop();
  4234. });
  4235. }
  4236. else {
  4237. this._renderingQueueLaunched = false;
  4238. }
  4239. };
  4240. /**
  4241. * Register and execute a render loop. The engine can have more than one render function.
  4242. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4243. * @example
  4244. * engine.runRenderLoop(function () {
  4245. * scene.render()
  4246. * })
  4247. */
  4248. Engine.prototype.runRenderLoop = function (renderFunction) {
  4249. var _this = this;
  4250. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4251. return;
  4252. }
  4253. this._activeRenderLoops.push(renderFunction);
  4254. if (!this._renderingQueueLaunched) {
  4255. this._renderingQueueLaunched = true;
  4256. BABYLON.Tools.QueueNewFrame(function () {
  4257. _this._renderLoop();
  4258. });
  4259. }
  4260. };
  4261. /**
  4262. * Toggle full screen mode.
  4263. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4264. */
  4265. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4266. if (this.isFullscreen) {
  4267. BABYLON.Tools.ExitFullscreen();
  4268. }
  4269. else {
  4270. this._pointerLockRequested = requestPointerLock;
  4271. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4272. }
  4273. };
  4274. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4275. this.applyStates();
  4276. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4277. if (this._depthCullingState.depthMask) {
  4278. this._gl.clearDepth(1.0);
  4279. }
  4280. var mode = 0;
  4281. if (backBuffer)
  4282. mode |= this._gl.COLOR_BUFFER_BIT;
  4283. if (depthStencil && this._depthCullingState.depthMask)
  4284. mode |= this._gl.DEPTH_BUFFER_BIT;
  4285. this._gl.clear(mode);
  4286. };
  4287. /**
  4288. * Set the WebGL's viewport
  4289. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4290. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4291. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4292. */
  4293. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4294. var width = requiredWidth || this._renderingCanvas.width;
  4295. var height = requiredHeight || this._renderingCanvas.height;
  4296. var x = viewport.x || 0;
  4297. var y = viewport.y || 0;
  4298. this._cachedViewport = viewport;
  4299. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4300. };
  4301. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4302. this._cachedViewport = null;
  4303. this._gl.viewport(x, y, width, height);
  4304. };
  4305. Engine.prototype.beginFrame = function () {
  4306. this._measureFps();
  4307. };
  4308. Engine.prototype.endFrame = function () {
  4309. //this.flushFramebuffer();
  4310. };
  4311. /**
  4312. * resize the view according to the canvas' size.
  4313. * @example
  4314. * window.addEventListener("resize", function () {
  4315. * engine.resize();
  4316. * });
  4317. */
  4318. Engine.prototype.resize = function () {
  4319. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4320. };
  4321. /**
  4322. * force a specific size of the canvas
  4323. * @param {number} width - the new canvas' width
  4324. * @param {number} height - the new canvas' height
  4325. */
  4326. Engine.prototype.setSize = function (width, height) {
  4327. this._renderingCanvas.width = width;
  4328. this._renderingCanvas.height = height;
  4329. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4330. };
  4331. Engine.prototype.bindFramebuffer = function (texture) {
  4332. this._currentRenderTarget = texture;
  4333. var gl = this._gl;
  4334. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4335. this._gl.viewport(0, 0, texture._width, texture._height);
  4336. this.wipeCaches();
  4337. };
  4338. Engine.prototype.unBindFramebuffer = function (texture) {
  4339. this._currentRenderTarget = null;
  4340. if (texture.generateMipMaps) {
  4341. var gl = this._gl;
  4342. gl.bindTexture(gl.TEXTURE_2D, texture);
  4343. gl.generateMipmap(gl.TEXTURE_2D);
  4344. gl.bindTexture(gl.TEXTURE_2D, null);
  4345. }
  4346. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4347. };
  4348. Engine.prototype.flushFramebuffer = function () {
  4349. this._gl.flush();
  4350. };
  4351. Engine.prototype.restoreDefaultFramebuffer = function () {
  4352. this._currentRenderTarget = null;
  4353. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4354. this.setViewport(this._cachedViewport);
  4355. this.wipeCaches();
  4356. };
  4357. // VBOs
  4358. Engine.prototype._resetVertexBufferBinding = function () {
  4359. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4360. this._cachedVertexBuffers = null;
  4361. };
  4362. Engine.prototype.createVertexBuffer = function (vertices) {
  4363. var vbo = this._gl.createBuffer();
  4364. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4365. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4366. this._resetVertexBufferBinding();
  4367. vbo.references = 1;
  4368. return vbo;
  4369. };
  4370. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4371. var vbo = this._gl.createBuffer();
  4372. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4373. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4374. this._resetVertexBufferBinding();
  4375. vbo.references = 1;
  4376. return vbo;
  4377. };
  4378. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4379. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4380. if (offset === undefined) {
  4381. offset = 0;
  4382. }
  4383. if (vertices instanceof Float32Array) {
  4384. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4385. }
  4386. else {
  4387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4388. }
  4389. this._resetVertexBufferBinding();
  4390. };
  4391. Engine.prototype._resetIndexBufferBinding = function () {
  4392. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4393. this._cachedIndexBuffer = null;
  4394. };
  4395. Engine.prototype.createIndexBuffer = function (indices) {
  4396. var vbo = this._gl.createBuffer();
  4397. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4398. // Check for 32 bits indices
  4399. var arrayBuffer;
  4400. var need32Bits = false;
  4401. if (this._caps.uintIndices) {
  4402. for (var index = 0; index < indices.length; index++) {
  4403. if (indices[index] > 65535) {
  4404. need32Bits = true;
  4405. break;
  4406. }
  4407. }
  4408. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4409. }
  4410. else {
  4411. arrayBuffer = new Uint16Array(indices);
  4412. }
  4413. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4414. this._resetIndexBufferBinding();
  4415. vbo.references = 1;
  4416. vbo.is32Bits = need32Bits;
  4417. return vbo;
  4418. };
  4419. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4420. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4421. this._cachedVertexBuffers = vertexBuffer;
  4422. this._cachedEffectForVertexBuffers = effect;
  4423. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4424. var offset = 0;
  4425. for (var index = 0; index < vertexDeclaration.length; index++) {
  4426. var order = effect.getAttributeLocation(index);
  4427. if (order >= 0) {
  4428. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4429. }
  4430. offset += vertexDeclaration[index] * 4;
  4431. }
  4432. }
  4433. if (this._cachedIndexBuffer !== indexBuffer) {
  4434. this._cachedIndexBuffer = indexBuffer;
  4435. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4436. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4437. }
  4438. };
  4439. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4440. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4441. this._cachedVertexBuffers = vertexBuffers;
  4442. this._cachedEffectForVertexBuffers = effect;
  4443. var attributes = effect.getAttributesNames();
  4444. for (var index = 0; index < attributes.length; index++) {
  4445. var order = effect.getAttributeLocation(index);
  4446. if (order >= 0) {
  4447. var vertexBuffer = vertexBuffers[attributes[index]];
  4448. if (!vertexBuffer) {
  4449. continue;
  4450. }
  4451. var stride = vertexBuffer.getStrideSize();
  4452. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4453. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4454. }
  4455. }
  4456. }
  4457. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4458. this._cachedIndexBuffer = indexBuffer;
  4459. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4460. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4461. }
  4462. };
  4463. Engine.prototype._releaseBuffer = function (buffer) {
  4464. buffer.references--;
  4465. if (buffer.references === 0) {
  4466. this._gl.deleteBuffer(buffer);
  4467. return true;
  4468. }
  4469. return false;
  4470. };
  4471. Engine.prototype.createInstancesBuffer = function (capacity) {
  4472. var buffer = this._gl.createBuffer();
  4473. buffer.capacity = capacity;
  4474. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4475. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4476. return buffer;
  4477. };
  4478. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4479. this._gl.deleteBuffer(buffer);
  4480. };
  4481. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4482. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4484. for (var index = 0; index < 4; index++) {
  4485. var offsetLocation = offsetLocations[index];
  4486. this._gl.enableVertexAttribArray(offsetLocation);
  4487. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4488. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4489. }
  4490. };
  4491. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4492. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4493. for (var index = 0; index < 4; index++) {
  4494. var offsetLocation = offsetLocations[index];
  4495. this._gl.disableVertexAttribArray(offsetLocation);
  4496. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4497. }
  4498. };
  4499. Engine.prototype.applyStates = function () {
  4500. this._depthCullingState.apply(this._gl);
  4501. this._alphaState.apply(this._gl);
  4502. };
  4503. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4504. // Apply states
  4505. this.applyStates();
  4506. this._drawCalls++;
  4507. // Render
  4508. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4509. if (instancesCount) {
  4510. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4511. return;
  4512. }
  4513. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4514. };
  4515. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4516. // Apply states
  4517. this.applyStates();
  4518. this._drawCalls++;
  4519. if (instancesCount) {
  4520. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4521. return;
  4522. }
  4523. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4524. };
  4525. // Shaders
  4526. Engine.prototype._releaseEffect = function (effect) {
  4527. if (this._compiledEffects[effect._key]) {
  4528. delete this._compiledEffects[effect._key];
  4529. if (effect.getProgram()) {
  4530. this._gl.deleteProgram(effect.getProgram());
  4531. }
  4532. }
  4533. };
  4534. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4535. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4536. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4537. var name = vertex + "+" + fragment + "@" + defines;
  4538. if (this._compiledEffects[name]) {
  4539. return this._compiledEffects[name];
  4540. }
  4541. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4542. effect._key = name;
  4543. this._compiledEffects[name] = effect;
  4544. return effect;
  4545. };
  4546. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4547. if (uniformsNames === void 0) { uniformsNames = []; }
  4548. if (samplers === void 0) { samplers = []; }
  4549. if (defines === void 0) { defines = ""; }
  4550. return this.createEffect({
  4551. vertex: "particles",
  4552. fragmentElement: fragmentName
  4553. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4554. };
  4555. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4556. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4557. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4558. var shaderProgram = this._gl.createProgram();
  4559. this._gl.attachShader(shaderProgram, vertexShader);
  4560. this._gl.attachShader(shaderProgram, fragmentShader);
  4561. this._gl.linkProgram(shaderProgram);
  4562. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4563. if (!linked) {
  4564. var error = this._gl.getProgramInfoLog(shaderProgram);
  4565. if (error) {
  4566. throw new Error(error);
  4567. }
  4568. }
  4569. this._gl.deleteShader(vertexShader);
  4570. this._gl.deleteShader(fragmentShader);
  4571. return shaderProgram;
  4572. };
  4573. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4574. var results = [];
  4575. for (var index = 0; index < uniformsNames.length; index++) {
  4576. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4577. }
  4578. return results;
  4579. };
  4580. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4581. var results = [];
  4582. for (var index = 0; index < attributesNames.length; index++) {
  4583. try {
  4584. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4585. }
  4586. catch (e) {
  4587. results.push(-1);
  4588. }
  4589. }
  4590. return results;
  4591. };
  4592. Engine.prototype.enableEffect = function (effect) {
  4593. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4594. if (effect && effect.onBind) {
  4595. effect.onBind(effect);
  4596. }
  4597. return;
  4598. }
  4599. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4600. // Use program
  4601. this._gl.useProgram(effect.getProgram());
  4602. for (var i in this._vertexAttribArrays) {
  4603. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4604. continue;
  4605. }
  4606. this._vertexAttribArrays[i] = false;
  4607. this._gl.disableVertexAttribArray(i);
  4608. }
  4609. var attributesCount = effect.getAttributesCount();
  4610. for (var index = 0; index < attributesCount; index++) {
  4611. // Attributes
  4612. var order = effect.getAttributeLocation(index);
  4613. if (order >= 0) {
  4614. this._vertexAttribArrays[order] = true;
  4615. this._gl.enableVertexAttribArray(order);
  4616. }
  4617. }
  4618. this._currentEffect = effect;
  4619. if (effect.onBind) {
  4620. effect.onBind(effect);
  4621. }
  4622. };
  4623. Engine.prototype.setArray = function (uniform, array) {
  4624. if (!uniform)
  4625. return;
  4626. this._gl.uniform1fv(uniform, array);
  4627. };
  4628. Engine.prototype.setArray2 = function (uniform, array) {
  4629. if (!uniform || array.length % 2 !== 0)
  4630. return;
  4631. this._gl.uniform2fv(uniform, array);
  4632. };
  4633. Engine.prototype.setArray3 = function (uniform, array) {
  4634. if (!uniform || array.length % 3 !== 0)
  4635. return;
  4636. this._gl.uniform3fv(uniform, array);
  4637. };
  4638. Engine.prototype.setArray4 = function (uniform, array) {
  4639. if (!uniform || array.length % 4 !== 0)
  4640. return;
  4641. this._gl.uniform4fv(uniform, array);
  4642. };
  4643. Engine.prototype.setMatrices = function (uniform, matrices) {
  4644. if (!uniform)
  4645. return;
  4646. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4647. };
  4648. Engine.prototype.setMatrix = function (uniform, matrix) {
  4649. if (!uniform)
  4650. return;
  4651. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4652. };
  4653. Engine.prototype.setFloat = function (uniform, value) {
  4654. if (!uniform)
  4655. return;
  4656. this._gl.uniform1f(uniform, value);
  4657. };
  4658. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4659. if (!uniform)
  4660. return;
  4661. this._gl.uniform2f(uniform, x, y);
  4662. };
  4663. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4664. if (!uniform)
  4665. return;
  4666. this._gl.uniform3f(uniform, x, y, z);
  4667. };
  4668. Engine.prototype.setBool = function (uniform, bool) {
  4669. if (!uniform)
  4670. return;
  4671. this._gl.uniform1i(uniform, bool);
  4672. };
  4673. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4674. if (!uniform)
  4675. return;
  4676. this._gl.uniform4f(uniform, x, y, z, w);
  4677. };
  4678. Engine.prototype.setColor3 = function (uniform, color3) {
  4679. if (!uniform)
  4680. return;
  4681. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4682. };
  4683. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4684. if (!uniform)
  4685. return;
  4686. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4687. };
  4688. // States
  4689. Engine.prototype.setState = function (culling, force) {
  4690. // Culling
  4691. if (this._depthCullingState.cull !== culling || force) {
  4692. if (culling) {
  4693. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4694. this._depthCullingState.cull = true;
  4695. }
  4696. else {
  4697. this._depthCullingState.cull = false;
  4698. }
  4699. }
  4700. };
  4701. Engine.prototype.setDepthBuffer = function (enable) {
  4702. this._depthCullingState.depthTest = enable;
  4703. };
  4704. Engine.prototype.getDepthWrite = function () {
  4705. return this._depthCullingState.depthMask;
  4706. };
  4707. Engine.prototype.setDepthWrite = function (enable) {
  4708. this._depthCullingState.depthMask = enable;
  4709. };
  4710. Engine.prototype.setColorWrite = function (enable) {
  4711. this._gl.colorMask(enable, enable, enable, enable);
  4712. };
  4713. Engine.prototype.setAlphaMode = function (mode) {
  4714. switch (mode) {
  4715. case Engine.ALPHA_DISABLE:
  4716. this.setDepthWrite(true);
  4717. this._alphaState.alphaBlend = false;
  4718. break;
  4719. case Engine.ALPHA_COMBINE:
  4720. this.setDepthWrite(false);
  4721. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4722. this._alphaState.alphaBlend = true;
  4723. break;
  4724. case Engine.ALPHA_ADD:
  4725. this.setDepthWrite(false);
  4726. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4727. this._alphaState.alphaBlend = true;
  4728. break;
  4729. }
  4730. this._alphaMode = mode;
  4731. };
  4732. Engine.prototype.getAlphaMode = function () {
  4733. return this._alphaMode;
  4734. };
  4735. Engine.prototype.setAlphaTesting = function (enable) {
  4736. this._alphaTest = enable;
  4737. };
  4738. Engine.prototype.getAlphaTesting = function () {
  4739. return this._alphaTest;
  4740. };
  4741. // Textures
  4742. Engine.prototype.wipeCaches = function () {
  4743. this._activeTexturesCache = [];
  4744. this._currentEffect = null;
  4745. this._depthCullingState.reset();
  4746. this._alphaState.reset();
  4747. this._cachedVertexBuffers = null;
  4748. this._cachedIndexBuffer = null;
  4749. this._cachedEffectForVertexBuffers = null;
  4750. };
  4751. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4752. var gl = this._gl;
  4753. gl.bindTexture(gl.TEXTURE_2D, texture);
  4754. var magFilter = gl.NEAREST;
  4755. var minFilter = gl.NEAREST;
  4756. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4757. magFilter = gl.LINEAR;
  4758. minFilter = gl.LINEAR;
  4759. }
  4760. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4761. magFilter = gl.LINEAR;
  4762. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4763. }
  4764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4766. gl.bindTexture(gl.TEXTURE_2D, null);
  4767. texture.samplingMode = samplingMode;
  4768. };
  4769. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4770. var _this = this;
  4771. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4772. if (onLoad === void 0) { onLoad = null; }
  4773. if (onError === void 0) { onError = null; }
  4774. if (buffer === void 0) { buffer = null; }
  4775. var texture = this._gl.createTexture();
  4776. var extension;
  4777. var fromData = false;
  4778. if (url.substr(0, 5) === "data:") {
  4779. fromData = true;
  4780. }
  4781. if (!fromData)
  4782. extension = url.substr(url.length - 4, 4).toLowerCase();
  4783. else {
  4784. var oldUrl = url;
  4785. fromData = oldUrl.split(':');
  4786. url = oldUrl;
  4787. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4788. }
  4789. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4790. var isTGA = (extension === ".tga");
  4791. scene._addPendingData(texture);
  4792. texture.url = url;
  4793. texture.noMipmap = noMipmap;
  4794. texture.references = 1;
  4795. this._loadedTexturesCache.push(texture);
  4796. var onerror = function () {
  4797. scene._removePendingData(texture);
  4798. if (onError) {
  4799. onError();
  4800. }
  4801. };
  4802. if (isTGA) {
  4803. var callback = function (arrayBuffer) {
  4804. var data = new Uint8Array(arrayBuffer);
  4805. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4806. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4807. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4808. if (onLoad) {
  4809. onLoad();
  4810. }
  4811. }, samplingMode);
  4812. };
  4813. if (!(fromData instanceof Array))
  4814. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4815. callback(arrayBuffer);
  4816. }, onerror, scene.database, true);
  4817. else
  4818. callback(buffer);
  4819. }
  4820. else if (isDDS) {
  4821. callback = function (data) {
  4822. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4823. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4824. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4825. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4826. if (onLoad) {
  4827. onLoad();
  4828. }
  4829. }, samplingMode);
  4830. };
  4831. if (!(fromData instanceof Array))
  4832. BABYLON.Tools.LoadFile(url, function (data) {
  4833. callback(data);
  4834. }, onerror, scene.database, true);
  4835. else
  4836. callback(buffer);
  4837. }
  4838. else {
  4839. var onload = function (img) {
  4840. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4841. var isPot = (img.width === potWidth && img.height === potHeight);
  4842. if (!isPot) {
  4843. _this._workingCanvas.width = potWidth;
  4844. _this._workingCanvas.height = potHeight;
  4845. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4846. _this._workingContext.imageSmoothingEnabled = false;
  4847. _this._workingContext.mozImageSmoothingEnabled = false;
  4848. _this._workingContext.oImageSmoothingEnabled = false;
  4849. _this._workingContext.webkitImageSmoothingEnabled = false;
  4850. _this._workingContext.msImageSmoothingEnabled = false;
  4851. }
  4852. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4853. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4854. _this._workingContext.imageSmoothingEnabled = true;
  4855. _this._workingContext.mozImageSmoothingEnabled = true;
  4856. _this._workingContext.oImageSmoothingEnabled = true;
  4857. _this._workingContext.webkitImageSmoothingEnabled = true;
  4858. _this._workingContext.msImageSmoothingEnabled = true;
  4859. }
  4860. }
  4861. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4862. if (onLoad) {
  4863. onLoad();
  4864. }
  4865. }, samplingMode);
  4866. };
  4867. if (!(fromData instanceof Array))
  4868. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4869. else
  4870. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4871. }
  4872. return texture;
  4873. };
  4874. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4875. var texture = this._gl.createTexture();
  4876. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4877. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4878. // Format
  4879. var internalFormat = this._gl.RGBA;
  4880. switch (format) {
  4881. case Engine.TEXTUREFORMAT_ALPHA:
  4882. internalFormat = this._gl.ALPHA;
  4883. break;
  4884. case Engine.TEXTUREFORMAT_LUMINANCE:
  4885. internalFormat = this._gl.LUMINANCE;
  4886. break;
  4887. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4888. internalFormat = this._gl.LUMINANCE_ALPHA;
  4889. break;
  4890. case Engine.TEXTUREFORMAT_RGB:
  4891. internalFormat = this._gl.RGB;
  4892. break;
  4893. case Engine.TEXTUREFORMAT_RGBA:
  4894. internalFormat = this._gl.RGBA;
  4895. break;
  4896. }
  4897. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4898. if (generateMipMaps) {
  4899. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4900. }
  4901. // Filters
  4902. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4903. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4904. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4905. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4906. this._activeTexturesCache = [];
  4907. texture._baseWidth = width;
  4908. texture._baseHeight = height;
  4909. texture._width = width;
  4910. texture._height = height;
  4911. texture.isReady = true;
  4912. texture.references = 1;
  4913. texture.samplingMode = samplingMode;
  4914. this._loadedTexturesCache.push(texture);
  4915. return texture;
  4916. };
  4917. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4918. var texture = this._gl.createTexture();
  4919. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4920. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4921. this._activeTexturesCache = [];
  4922. texture._baseWidth = width;
  4923. texture._baseHeight = height;
  4924. texture._width = width;
  4925. texture._height = height;
  4926. texture.isReady = false;
  4927. texture.generateMipMaps = generateMipMaps;
  4928. texture.references = 1;
  4929. texture.samplingMode = samplingMode;
  4930. this.updateTextureSamplingMode(samplingMode, texture);
  4931. this._loadedTexturesCache.push(texture);
  4932. return texture;
  4933. };
  4934. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  4935. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  4936. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4937. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4938. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4939. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4940. };
  4941. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4942. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4943. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4944. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4945. if (texture.generateMipMaps) {
  4946. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4947. }
  4948. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4949. this._activeTexturesCache = [];
  4950. texture.isReady = true;
  4951. };
  4952. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4953. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4954. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4955. // Scale the video if it is a NPOT using the current working canvas
  4956. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4957. if (!texture._workingCanvas) {
  4958. texture._workingCanvas = document.createElement("canvas");
  4959. texture._workingContext = texture._workingCanvas.getContext("2d");
  4960. texture._workingCanvas.width = texture._width;
  4961. texture._workingCanvas.height = texture._height;
  4962. }
  4963. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4964. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4965. }
  4966. else {
  4967. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4968. }
  4969. if (texture.generateMipMaps) {
  4970. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4971. }
  4972. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4973. this._activeTexturesCache = [];
  4974. texture.isReady = true;
  4975. };
  4976. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4977. // old version had a "generateMipMaps" arg instead of options.
  4978. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4979. // in the same way, generateDepthBuffer is defaulted to true
  4980. var generateMipMaps = false;
  4981. var generateDepthBuffer = true;
  4982. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4983. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4984. if (options !== undefined) {
  4985. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4986. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4987. type = options.type === undefined ? type : options.type;
  4988. if (options.samplingMode !== undefined) {
  4989. samplingMode = options.samplingMode;
  4990. }
  4991. if (type === Engine.TEXTURETYPE_FLOAT) {
  4992. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4993. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4994. }
  4995. }
  4996. var gl = this._gl;
  4997. var texture = gl.createTexture();
  4998. gl.bindTexture(gl.TEXTURE_2D, texture);
  4999. var width = size.width || size;
  5000. var height = size.height || size;
  5001. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  5002. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  5003. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  5004. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  5005. }
  5006. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  5007. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  5008. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5009. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5010. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  5011. var depthBuffer;
  5012. // Create the depth buffer
  5013. if (generateDepthBuffer) {
  5014. depthBuffer = gl.createRenderbuffer();
  5015. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  5016. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  5017. }
  5018. // Create the framebuffer
  5019. var framebuffer = gl.createFramebuffer();
  5020. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  5021. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  5022. if (generateDepthBuffer) {
  5023. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  5024. }
  5025. // Unbind
  5026. gl.bindTexture(gl.TEXTURE_2D, null);
  5027. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  5028. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  5029. texture._framebuffer = framebuffer;
  5030. if (generateDepthBuffer) {
  5031. texture._depthBuffer = depthBuffer;
  5032. }
  5033. texture._width = width;
  5034. texture._height = height;
  5035. texture.isReady = true;
  5036. texture.generateMipMaps = generateMipMaps;
  5037. texture.references = 1;
  5038. texture.samplingMode = samplingMode;
  5039. this._activeTexturesCache = [];
  5040. this._loadedTexturesCache.push(texture);
  5041. return texture;
  5042. };
  5043. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  5044. var _this = this;
  5045. var gl = this._gl;
  5046. var texture = gl.createTexture();
  5047. texture.isCube = true;
  5048. texture.url = rootUrl;
  5049. texture.references = 1;
  5050. this._loadedTexturesCache.push(texture);
  5051. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  5052. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  5053. if (isDDS) {
  5054. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  5055. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  5056. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  5057. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5058. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  5059. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  5060. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  5061. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5062. }
  5063. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5064. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  5065. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5066. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5067. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5068. _this._activeTexturesCache = [];
  5069. texture._width = info.width;
  5070. texture._height = info.height;
  5071. texture.isReady = true;
  5072. }, null, null, true);
  5073. }
  5074. else {
  5075. cascadeLoad(rootUrl, scene, function (imgs) {
  5076. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  5077. var height = width;
  5078. _this._workingCanvas.width = width;
  5079. _this._workingCanvas.height = height;
  5080. var faces = [
  5081. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  5082. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  5083. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  5084. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  5085. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  5086. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  5087. ];
  5088. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  5089. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  5090. for (var index = 0; index < faces.length; index++) {
  5091. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  5092. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  5093. }
  5094. if (!noMipmap) {
  5095. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  5096. }
  5097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  5098. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  5099. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  5100. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  5101. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  5102. _this._activeTexturesCache = [];
  5103. texture._width = width;
  5104. texture._height = height;
  5105. texture.isReady = true;
  5106. }, extensions);
  5107. }
  5108. return texture;
  5109. };
  5110. Engine.prototype._releaseTexture = function (texture) {
  5111. var gl = this._gl;
  5112. if (texture._framebuffer) {
  5113. gl.deleteFramebuffer(texture._framebuffer);
  5114. }
  5115. if (texture._depthBuffer) {
  5116. gl.deleteRenderbuffer(texture._depthBuffer);
  5117. }
  5118. gl.deleteTexture(texture);
  5119. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  5120. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5121. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5122. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5123. this._activeTexturesCache[channel] = null;
  5124. }
  5125. var index = this._loadedTexturesCache.indexOf(texture);
  5126. if (index !== -1) {
  5127. this._loadedTexturesCache.splice(index, 1);
  5128. }
  5129. };
  5130. Engine.prototype.bindSamplers = function (effect) {
  5131. this._gl.useProgram(effect.getProgram());
  5132. var samplers = effect.getSamplers();
  5133. for (var index = 0; index < samplers.length; index++) {
  5134. var uniform = effect.getUniform(samplers[index]);
  5135. this._gl.uniform1i(uniform, index);
  5136. }
  5137. this._currentEffect = null;
  5138. };
  5139. Engine.prototype._bindTexture = function (channel, texture) {
  5140. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5141. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  5142. this._activeTexturesCache[channel] = null;
  5143. };
  5144. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  5145. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  5146. };
  5147. Engine.prototype.setTexture = function (channel, texture) {
  5148. if (channel < 0) {
  5149. return;
  5150. }
  5151. // Not ready?
  5152. if (!texture || !texture.isReady()) {
  5153. if (this._activeTexturesCache[channel] != null) {
  5154. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5155. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  5156. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  5157. this._activeTexturesCache[channel] = null;
  5158. }
  5159. return;
  5160. }
  5161. // Video
  5162. if (texture instanceof BABYLON.VideoTexture) {
  5163. if (texture.update()) {
  5164. this._activeTexturesCache[channel] = null;
  5165. }
  5166. }
  5167. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  5168. texture.delayLoad();
  5169. return;
  5170. }
  5171. if (this._activeTexturesCache[channel] === texture) {
  5172. return;
  5173. }
  5174. this._activeTexturesCache[channel] = texture;
  5175. var internalTexture = texture.getInternalTexture();
  5176. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  5177. if (internalTexture.isCube) {
  5178. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  5179. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  5180. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  5181. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  5182. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  5183. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  5184. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  5185. }
  5186. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  5187. }
  5188. else {
  5189. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  5190. if (internalTexture._cachedWrapU !== texture.wrapU) {
  5191. internalTexture._cachedWrapU = texture.wrapU;
  5192. switch (texture.wrapU) {
  5193. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  5195. break;
  5196. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5197. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  5198. break;
  5199. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5200. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  5201. break;
  5202. }
  5203. }
  5204. if (internalTexture._cachedWrapV !== texture.wrapV) {
  5205. internalTexture._cachedWrapV = texture.wrapV;
  5206. switch (texture.wrapV) {
  5207. case BABYLON.Texture.WRAP_ADDRESSMODE:
  5208. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  5209. break;
  5210. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  5211. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  5212. break;
  5213. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  5214. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  5215. break;
  5216. }
  5217. }
  5218. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  5219. }
  5220. };
  5221. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  5222. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  5223. var value = texture.anisotropicFilteringLevel;
  5224. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  5225. value = 1;
  5226. }
  5227. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  5228. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  5229. texture._cachedAnisotropicFilteringLevel = value;
  5230. }
  5231. };
  5232. Engine.prototype.readPixels = function (x, y, width, height) {
  5233. var data = new Uint8Array(height * width * 4);
  5234. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  5235. return data;
  5236. };
  5237. // Dispose
  5238. Engine.prototype.dispose = function () {
  5239. this.hideLoadingUI();
  5240. this.stopRenderLoop();
  5241. while (this.scenes.length) {
  5242. this.scenes[0].dispose();
  5243. }
  5244. // Release audio engine
  5245. Engine.audioEngine.dispose();
  5246. for (var name in this._compiledEffects) {
  5247. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5248. }
  5249. for (var i in this._vertexAttribArrays) {
  5250. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5251. continue;
  5252. }
  5253. this._gl.disableVertexAttribArray(i);
  5254. }
  5255. // Events
  5256. window.removeEventListener("blur", this._onBlur);
  5257. window.removeEventListener("focus", this._onFocus);
  5258. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5259. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5260. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5261. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5262. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5263. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5264. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5265. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5266. };
  5267. // Loading screen
  5268. Engine.prototype.displayLoadingUI = function () {
  5269. var _this = this;
  5270. this._loadingDiv = document.createElement("div");
  5271. this._loadingDiv.style.opacity = "0";
  5272. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5273. // Loading text
  5274. this._loadingTextDiv = document.createElement("div");
  5275. this._loadingTextDiv.style.position = "absolute";
  5276. this._loadingTextDiv.style.left = "0";
  5277. this._loadingTextDiv.style.top = "50%";
  5278. this._loadingTextDiv.style.marginTop = "80px";
  5279. this._loadingTextDiv.style.width = "100%";
  5280. this._loadingTextDiv.style.height = "20px";
  5281. this._loadingTextDiv.style.fontFamily = "Arial";
  5282. this._loadingTextDiv.style.fontSize = "14px";
  5283. this._loadingTextDiv.style.color = "white";
  5284. this._loadingTextDiv.style.textAlign = "center";
  5285. this._loadingTextDiv.innerHTML = "Loading";
  5286. this._loadingDiv.appendChild(this._loadingTextDiv);
  5287. // Loading img
  5288. var imgBack = new Image();
  5289. 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==";
  5290. imgBack.style.position = "absolute";
  5291. imgBack.style.left = "50%";
  5292. imgBack.style.top = "50%";
  5293. imgBack.style.marginLeft = "-50px";
  5294. imgBack.style.marginTop = "-50px";
  5295. imgBack.style.transition = "transform 1.0s ease";
  5296. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5297. var deg = 360;
  5298. var onTransitionEnd = function () {
  5299. deg += 360;
  5300. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5301. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5302. };
  5303. imgBack.addEventListener("transitionend", onTransitionEnd);
  5304. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5305. this._loadingDiv.appendChild(imgBack);
  5306. // front image
  5307. var imgFront = new Image();
  5308. 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=";
  5309. imgFront.style.position = "absolute";
  5310. imgFront.style.left = "50%";
  5311. imgFront.style.top = "50%";
  5312. imgFront.style.marginLeft = "-50px";
  5313. imgFront.style.marginTop = "-50px";
  5314. this._loadingDiv.appendChild(imgFront);
  5315. // Resize
  5316. this._resizeLoadingUI = function () {
  5317. var canvasRect = _this.getRenderingCanvasClientRect();
  5318. _this._loadingDiv.style.position = "absolute";
  5319. _this._loadingDiv.style.left = canvasRect.left + "px";
  5320. _this._loadingDiv.style.top = canvasRect.top + "px";
  5321. _this._loadingDiv.style.width = canvasRect.width + "px";
  5322. _this._loadingDiv.style.height = canvasRect.height + "px";
  5323. };
  5324. this._resizeLoadingUI();
  5325. window.addEventListener("resize", this._resizeLoadingUI);
  5326. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5327. document.body.appendChild(this._loadingDiv);
  5328. setTimeout(function () {
  5329. _this._loadingDiv.style.opacity = "1";
  5330. imgBack.style.transform = "rotateZ(360deg)";
  5331. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5332. }, 0);
  5333. };
  5334. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5335. set: function (text) {
  5336. if (!this._loadingDiv) {
  5337. return;
  5338. }
  5339. this._loadingTextDiv.innerHTML = text;
  5340. },
  5341. enumerable: true,
  5342. configurable: true
  5343. });
  5344. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5345. get: function () {
  5346. return this._loadingDivBackgroundColor;
  5347. },
  5348. set: function (color) {
  5349. this._loadingDivBackgroundColor = color;
  5350. if (!this._loadingDiv) {
  5351. return;
  5352. }
  5353. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. Engine.prototype.hideLoadingUI = function () {
  5359. var _this = this;
  5360. if (!this._loadingDiv) {
  5361. return;
  5362. }
  5363. var onTransitionEnd = function () {
  5364. if (!_this._loadingDiv) {
  5365. return;
  5366. }
  5367. document.body.removeChild(_this._loadingDiv);
  5368. window.removeEventListener("resize", _this._resizeLoadingUI);
  5369. _this._loadingDiv = null;
  5370. };
  5371. this._loadingDiv.style.opacity = "0";
  5372. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5373. };
  5374. // FPS
  5375. Engine.prototype.getFps = function () {
  5376. return this.fps;
  5377. };
  5378. Engine.prototype.getDeltaTime = function () {
  5379. return this.deltaTime;
  5380. };
  5381. Engine.prototype._measureFps = function () {
  5382. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5383. var length = this.previousFramesDuration.length;
  5384. if (length >= 2) {
  5385. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5386. }
  5387. if (length >= this.fpsRange) {
  5388. if (length > this.fpsRange) {
  5389. this.previousFramesDuration.splice(0, 1);
  5390. length = this.previousFramesDuration.length;
  5391. }
  5392. var sum = 0;
  5393. for (var id = 0; id < length - 1; id++) {
  5394. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5395. }
  5396. this.fps = 1000.0 / (sum / (length - 1));
  5397. }
  5398. };
  5399. // Statics
  5400. Engine.isSupported = function () {
  5401. try {
  5402. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5403. if (navigator.isCocoonJS) {
  5404. return true;
  5405. }
  5406. var tempcanvas = document.createElement("canvas");
  5407. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5408. return gl != null && !!window.WebGLRenderingContext;
  5409. }
  5410. catch (e) {
  5411. return false;
  5412. }
  5413. };
  5414. // Const statics
  5415. Engine._ALPHA_DISABLE = 0;
  5416. Engine._ALPHA_ADD = 1;
  5417. Engine._ALPHA_COMBINE = 2;
  5418. Engine._DELAYLOADSTATE_NONE = 0;
  5419. Engine._DELAYLOADSTATE_LOADED = 1;
  5420. Engine._DELAYLOADSTATE_LOADING = 2;
  5421. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5422. Engine._TEXTUREFORMAT_ALPHA = 0;
  5423. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5424. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5425. Engine._TEXTUREFORMAT_RGB = 4;
  5426. Engine._TEXTUREFORMAT_RGBA = 4;
  5427. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5428. Engine._TEXTURETYPE_FLOAT = 1;
  5429. // Updatable statics so stick with vars here
  5430. Engine.Epsilon = 0.001;
  5431. Engine.CollisionsEpsilon = 0.001;
  5432. Engine.ShadersRepository = "Babylon/Shaders/";
  5433. return Engine;
  5434. })();
  5435. BABYLON.Engine = Engine;
  5436. })(BABYLON || (BABYLON = {}));
  5437. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5438. (function (BABYLON) {
  5439. /**
  5440. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5441. */
  5442. var Node = (function () {
  5443. /**
  5444. * @constructor
  5445. * @param {string} name - the name and id to be given to this node
  5446. * @param {BABYLON.Scene} the scene this node will be added to
  5447. */
  5448. function Node(name, scene) {
  5449. this.state = "";
  5450. this.animations = new Array();
  5451. this._childrenFlag = -1;
  5452. this._isEnabled = true;
  5453. this._isReady = true;
  5454. this._currentRenderId = -1;
  5455. this._parentRenderId = -1;
  5456. this.name = name;
  5457. this.id = name;
  5458. this._scene = scene;
  5459. this._initCache();
  5460. }
  5461. Node.prototype.getScene = function () {
  5462. return this._scene;
  5463. };
  5464. Node.prototype.getEngine = function () {
  5465. return this._scene.getEngine();
  5466. };
  5467. // override it in derived class
  5468. Node.prototype.getWorldMatrix = function () {
  5469. return BABYLON.Matrix.Identity();
  5470. };
  5471. // override it in derived class if you add new variables to the cache
  5472. // and call the parent class method
  5473. Node.prototype._initCache = function () {
  5474. this._cache = {};
  5475. this._cache.parent = undefined;
  5476. };
  5477. Node.prototype.updateCache = function (force) {
  5478. if (!force && this.isSynchronized())
  5479. return;
  5480. this._cache.parent = this.parent;
  5481. this._updateCache();
  5482. };
  5483. // override it in derived class if you add new variables to the cache
  5484. // and call the parent class method if !ignoreParentClass
  5485. Node.prototype._updateCache = function (ignoreParentClass) {
  5486. };
  5487. // override it in derived class if you add new variables to the cache
  5488. Node.prototype._isSynchronized = function () {
  5489. return true;
  5490. };
  5491. Node.prototype.isSynchronizedWithParent = function () {
  5492. if (!this.parent) {
  5493. return true;
  5494. }
  5495. if (this._parentRenderId !== this.parent._currentRenderId) {
  5496. return false;
  5497. }
  5498. this._parentRenderId = this.parent._currentRenderId;
  5499. return this.parent._currentRenderId <= this._currentRenderId && this.parent.isSynchronized();
  5500. };
  5501. Node.prototype.isSynchronized = function (updateCache) {
  5502. var check = this.hasNewParent();
  5503. check = check || !this.isSynchronizedWithParent();
  5504. check = check || !this._isSynchronized();
  5505. if (updateCache)
  5506. this.updateCache(true);
  5507. return !check;
  5508. };
  5509. Node.prototype.hasNewParent = function (update) {
  5510. if (this._cache.parent === this.parent)
  5511. return false;
  5512. if (update)
  5513. this._cache.parent = this.parent;
  5514. return true;
  5515. };
  5516. /**
  5517. * Is this node ready to be used/rendered
  5518. * @return {boolean} is it ready
  5519. */
  5520. Node.prototype.isReady = function () {
  5521. return this._isReady;
  5522. };
  5523. /**
  5524. * Is this node enabled.
  5525. * If the node has a parent and is enabled, the parent will be inspected as well.
  5526. * @return {boolean} whether this node (and its parent) is enabled.
  5527. * @see setEnabled
  5528. */
  5529. Node.prototype.isEnabled = function () {
  5530. if (!this._isEnabled) {
  5531. return false;
  5532. }
  5533. if (this.parent) {
  5534. return this.parent.isEnabled();
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Set the enabled state of this node.
  5540. * @param {boolean} value - the new enabled state
  5541. * @see isEnabled
  5542. */
  5543. Node.prototype.setEnabled = function (value) {
  5544. this._isEnabled = value;
  5545. };
  5546. /**
  5547. * Is this node a descendant of the given node.
  5548. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5549. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5550. * @see parent
  5551. */
  5552. Node.prototype.isDescendantOf = function (ancestor) {
  5553. if (this.parent) {
  5554. if (this.parent === ancestor) {
  5555. return true;
  5556. }
  5557. return this.parent.isDescendantOf(ancestor);
  5558. }
  5559. return false;
  5560. };
  5561. Node.prototype._getDescendants = function (list, results) {
  5562. for (var index = 0; index < list.length; index++) {
  5563. var item = list[index];
  5564. if (item.isDescendantOf(this)) {
  5565. results.push(item);
  5566. }
  5567. }
  5568. };
  5569. /**
  5570. * Will return all nodes that have this node as parent.
  5571. * @return {BABYLON.Node[]} all children nodes of all types.
  5572. */
  5573. Node.prototype.getDescendants = function () {
  5574. var results = [];
  5575. this._getDescendants(this._scene.meshes, results);
  5576. this._getDescendants(this._scene.lights, results);
  5577. this._getDescendants(this._scene.cameras, results);
  5578. return results;
  5579. };
  5580. Node.prototype._setReady = function (state) {
  5581. if (state == this._isReady) {
  5582. return;
  5583. }
  5584. if (!state) {
  5585. this._isReady = false;
  5586. return;
  5587. }
  5588. this._isReady = true;
  5589. if (this.onReady) {
  5590. this.onReady(this);
  5591. }
  5592. };
  5593. return Node;
  5594. })();
  5595. BABYLON.Node = Node;
  5596. })(BABYLON || (BABYLON = {}));
  5597. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5598. (function (BABYLON) {
  5599. var BoundingSphere = (function () {
  5600. function BoundingSphere(minimum, maximum) {
  5601. this.minimum = minimum;
  5602. this.maximum = maximum;
  5603. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5604. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5605. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5606. this.radius = distance * 0.5;
  5607. this.centerWorld = BABYLON.Vector3.Zero();
  5608. this._update(BABYLON.Matrix.Identity());
  5609. }
  5610. // Methods
  5611. BoundingSphere.prototype._update = function (world) {
  5612. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5613. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5614. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5615. };
  5616. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5617. for (var i = 0; i < 6; i++) {
  5618. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5619. return false;
  5620. }
  5621. return true;
  5622. };
  5623. BoundingSphere.prototype.intersectsPoint = function (point) {
  5624. var x = this.centerWorld.x - point.x;
  5625. var y = this.centerWorld.y - point.y;
  5626. var z = this.centerWorld.z - point.z;
  5627. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5628. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5629. return false;
  5630. return true;
  5631. };
  5632. // Statics
  5633. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5634. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5635. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5636. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5637. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5638. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5639. return false;
  5640. return true;
  5641. };
  5642. return BoundingSphere;
  5643. })();
  5644. BABYLON.BoundingSphere = BoundingSphere;
  5645. })(BABYLON || (BABYLON = {}));
  5646. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5647. (function (BABYLON) {
  5648. var BoundingBox = (function () {
  5649. function BoundingBox(minimum, maximum) {
  5650. this.minimum = minimum;
  5651. this.maximum = maximum;
  5652. this.vectors = new Array();
  5653. this.vectorsWorld = new Array();
  5654. // Bounding vectors
  5655. this.vectors.push(this.minimum.clone());
  5656. this.vectors.push(this.maximum.clone());
  5657. this.vectors.push(this.minimum.clone());
  5658. this.vectors[2].x = this.maximum.x;
  5659. this.vectors.push(this.minimum.clone());
  5660. this.vectors[3].y = this.maximum.y;
  5661. this.vectors.push(this.minimum.clone());
  5662. this.vectors[4].z = this.maximum.z;
  5663. this.vectors.push(this.maximum.clone());
  5664. this.vectors[5].z = this.minimum.z;
  5665. this.vectors.push(this.maximum.clone());
  5666. this.vectors[6].x = this.minimum.x;
  5667. this.vectors.push(this.maximum.clone());
  5668. this.vectors[7].y = this.minimum.y;
  5669. // OBB
  5670. this.center = this.maximum.add(this.minimum).scale(0.5);
  5671. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5672. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5673. for (var index = 0; index < this.vectors.length; index++) {
  5674. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5675. }
  5676. this.minimumWorld = BABYLON.Vector3.Zero();
  5677. this.maximumWorld = BABYLON.Vector3.Zero();
  5678. this._update(BABYLON.Matrix.Identity());
  5679. }
  5680. // Methods
  5681. BoundingBox.prototype.getWorldMatrix = function () {
  5682. return this._worldMatrix;
  5683. };
  5684. BoundingBox.prototype._update = function (world) {
  5685. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5686. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5687. for (var index = 0; index < this.vectors.length; index++) {
  5688. var v = this.vectorsWorld[index];
  5689. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5690. if (v.x < this.minimumWorld.x)
  5691. this.minimumWorld.x = v.x;
  5692. if (v.y < this.minimumWorld.y)
  5693. this.minimumWorld.y = v.y;
  5694. if (v.z < this.minimumWorld.z)
  5695. this.minimumWorld.z = v.z;
  5696. if (v.x > this.maximumWorld.x)
  5697. this.maximumWorld.x = v.x;
  5698. if (v.y > this.maximumWorld.y)
  5699. this.maximumWorld.y = v.y;
  5700. if (v.z > this.maximumWorld.z)
  5701. this.maximumWorld.z = v.z;
  5702. }
  5703. // OBB
  5704. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5705. this.center.scaleInPlace(0.5);
  5706. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5707. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5708. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5709. this._worldMatrix = world;
  5710. };
  5711. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5712. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5713. };
  5714. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5715. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5716. };
  5717. BoundingBox.prototype.intersectsPoint = function (point) {
  5718. var delta = BABYLON.Engine.Epsilon;
  5719. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5720. return false;
  5721. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5722. return false;
  5723. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5724. return false;
  5725. return true;
  5726. };
  5727. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5728. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5729. };
  5730. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5731. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5732. return false;
  5733. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5734. return false;
  5735. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5736. return false;
  5737. return true;
  5738. };
  5739. // Statics
  5740. BoundingBox.Intersects = function (box0, box1) {
  5741. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5742. return false;
  5743. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5744. return false;
  5745. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5746. return false;
  5747. return true;
  5748. };
  5749. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5750. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5751. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5752. return (num <= (sphereRadius * sphereRadius));
  5753. };
  5754. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5755. for (var p = 0; p < 6; p++) {
  5756. for (var i = 0; i < 8; i++) {
  5757. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5758. return false;
  5759. }
  5760. }
  5761. }
  5762. return true;
  5763. };
  5764. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5765. for (var p = 0; p < 6; p++) {
  5766. var inCount = 8;
  5767. for (var i = 0; i < 8; i++) {
  5768. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5769. --inCount;
  5770. }
  5771. else {
  5772. break;
  5773. }
  5774. }
  5775. if (inCount === 0)
  5776. return false;
  5777. }
  5778. return true;
  5779. };
  5780. return BoundingBox;
  5781. })();
  5782. BABYLON.BoundingBox = BoundingBox;
  5783. })(BABYLON || (BABYLON = {}));
  5784. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5785. (function (BABYLON) {
  5786. var computeBoxExtents = function (axis, box) {
  5787. var p = BABYLON.Vector3.Dot(box.center, axis);
  5788. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5789. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5790. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5791. var r = r0 + r1 + r2;
  5792. return {
  5793. min: p - r,
  5794. max: p + r
  5795. };
  5796. };
  5797. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5798. var axisOverlap = function (axis, box0, box1) {
  5799. var result0 = computeBoxExtents(axis, box0);
  5800. var result1 = computeBoxExtents(axis, box1);
  5801. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5802. };
  5803. var BoundingInfo = (function () {
  5804. function BoundingInfo(minimum, maximum) {
  5805. this.minimum = minimum;
  5806. this.maximum = maximum;
  5807. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5808. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5809. }
  5810. // Methods
  5811. BoundingInfo.prototype._update = function (world) {
  5812. this.boundingBox._update(world);
  5813. this.boundingSphere._update(world);
  5814. };
  5815. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5816. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5817. return false;
  5818. return this.boundingBox.isInFrustum(frustumPlanes);
  5819. };
  5820. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5821. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5822. };
  5823. BoundingInfo.prototype._checkCollision = function (collider) {
  5824. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5825. };
  5826. BoundingInfo.prototype.intersectsPoint = function (point) {
  5827. if (!this.boundingSphere.centerWorld) {
  5828. return false;
  5829. }
  5830. if (!this.boundingSphere.intersectsPoint(point)) {
  5831. return false;
  5832. }
  5833. if (!this.boundingBox.intersectsPoint(point)) {
  5834. return false;
  5835. }
  5836. return true;
  5837. };
  5838. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5839. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5840. return false;
  5841. }
  5842. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5843. return false;
  5844. }
  5845. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5846. return false;
  5847. }
  5848. if (!precise) {
  5849. return true;
  5850. }
  5851. var box0 = this.boundingBox;
  5852. var box1 = boundingInfo.boundingBox;
  5853. if (!axisOverlap(box0.directions[0], box0, box1))
  5854. return false;
  5855. if (!axisOverlap(box0.directions[1], box0, box1))
  5856. return false;
  5857. if (!axisOverlap(box0.directions[2], box0, box1))
  5858. return false;
  5859. if (!axisOverlap(box1.directions[0], box0, box1))
  5860. return false;
  5861. if (!axisOverlap(box1.directions[1], box0, box1))
  5862. return false;
  5863. if (!axisOverlap(box1.directions[2], box0, box1))
  5864. return false;
  5865. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5866. return false;
  5867. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5868. return false;
  5869. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5870. return false;
  5871. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5872. return false;
  5873. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5874. return false;
  5875. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5876. return false;
  5877. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5878. return false;
  5879. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5880. return false;
  5881. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5882. return false;
  5883. return true;
  5884. };
  5885. return BoundingInfo;
  5886. })();
  5887. BABYLON.BoundingInfo = BoundingInfo;
  5888. })(BABYLON || (BABYLON = {}));
  5889. //# sourceMappingURL=babylon.boundingInfo.js.map
  5890. var BABYLON;
  5891. (function (BABYLON) {
  5892. var Light = (function (_super) {
  5893. __extends(Light, _super);
  5894. function Light(name, scene) {
  5895. _super.call(this, name, scene);
  5896. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5897. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5898. this.intensity = 1.0;
  5899. this.range = Number.MAX_VALUE;
  5900. this.includedOnlyMeshes = new Array();
  5901. this.excludedMeshes = new Array();
  5902. this._excludedMeshesIds = new Array();
  5903. this._includedOnlyMeshesIds = new Array();
  5904. scene.addLight(this);
  5905. }
  5906. Light.prototype.getShadowGenerator = function () {
  5907. return this._shadowGenerator;
  5908. };
  5909. Light.prototype.getAbsolutePosition = function () {
  5910. return BABYLON.Vector3.Zero();
  5911. };
  5912. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5913. };
  5914. Light.prototype._getWorldMatrix = function () {
  5915. return BABYLON.Matrix.Identity();
  5916. };
  5917. Light.prototype.canAffectMesh = function (mesh) {
  5918. if (!mesh) {
  5919. return true;
  5920. }
  5921. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5922. return false;
  5923. }
  5924. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5925. return false;
  5926. }
  5927. return true;
  5928. };
  5929. Light.prototype.getWorldMatrix = function () {
  5930. this._currentRenderId = this.getScene().getRenderId();
  5931. var worldMatrix = this._getWorldMatrix();
  5932. if (this.parent && this.parent.getWorldMatrix) {
  5933. if (!this._parentedWorldMatrix) {
  5934. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5935. }
  5936. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5937. return this._parentedWorldMatrix;
  5938. }
  5939. return worldMatrix;
  5940. };
  5941. Light.prototype.dispose = function () {
  5942. if (this._shadowGenerator) {
  5943. this._shadowGenerator.dispose();
  5944. this._shadowGenerator = null;
  5945. }
  5946. // Remove from scene
  5947. this.getScene().removeLight(this);
  5948. };
  5949. return Light;
  5950. })(BABYLON.Node);
  5951. BABYLON.Light = Light;
  5952. })(BABYLON || (BABYLON = {}));
  5953. //# sourceMappingURL=babylon.light.js.map
  5954. var BABYLON;
  5955. (function (BABYLON) {
  5956. var PointLight = (function (_super) {
  5957. __extends(PointLight, _super);
  5958. function PointLight(name, position, scene) {
  5959. _super.call(this, name, scene);
  5960. this.position = position;
  5961. }
  5962. PointLight.prototype.getAbsolutePosition = function () {
  5963. return this._transformedPosition ? this._transformedPosition : this.position;
  5964. };
  5965. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5966. if (this.parent && this.parent.getWorldMatrix) {
  5967. if (!this._transformedPosition) {
  5968. this._transformedPosition = BABYLON.Vector3.Zero();
  5969. }
  5970. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5971. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5972. return;
  5973. }
  5974. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5975. };
  5976. PointLight.prototype.getShadowGenerator = function () {
  5977. return null;
  5978. };
  5979. PointLight.prototype._getWorldMatrix = function () {
  5980. if (!this._worldMatrix) {
  5981. this._worldMatrix = BABYLON.Matrix.Identity();
  5982. }
  5983. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5984. return this._worldMatrix;
  5985. };
  5986. return PointLight;
  5987. })(BABYLON.Light);
  5988. BABYLON.PointLight = PointLight;
  5989. })(BABYLON || (BABYLON = {}));
  5990. //# sourceMappingURL=babylon.pointLight.js.map
  5991. var BABYLON;
  5992. (function (BABYLON) {
  5993. var SpotLight = (function (_super) {
  5994. __extends(SpotLight, _super);
  5995. function SpotLight(name, position, direction, angle, exponent, scene) {
  5996. _super.call(this, name, scene);
  5997. this.position = position;
  5998. this.direction = direction;
  5999. this.angle = angle;
  6000. this.exponent = exponent;
  6001. }
  6002. SpotLight.prototype.getAbsolutePosition = function () {
  6003. return this.transformedPosition ? this.transformedPosition : this.position;
  6004. };
  6005. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6006. var activeCamera = this.getScene().activeCamera;
  6007. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  6008. };
  6009. SpotLight.prototype.supportsVSM = function () {
  6010. return true;
  6011. };
  6012. SpotLight.prototype.needRefreshPerFrame = function () {
  6013. return false;
  6014. };
  6015. SpotLight.prototype.setDirectionToTarget = function (target) {
  6016. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6017. return this.direction;
  6018. };
  6019. SpotLight.prototype.computeTransformedPosition = function () {
  6020. if (this.parent && this.parent.getWorldMatrix) {
  6021. if (!this.transformedPosition) {
  6022. this.transformedPosition = BABYLON.Vector3.Zero();
  6023. }
  6024. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6025. return true;
  6026. }
  6027. return false;
  6028. };
  6029. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  6030. var normalizeDirection;
  6031. if (this.parent && this.parent.getWorldMatrix) {
  6032. if (!this._transformedDirection) {
  6033. this._transformedDirection = BABYLON.Vector3.Zero();
  6034. }
  6035. this.computeTransformedPosition();
  6036. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6037. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  6038. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  6039. }
  6040. else {
  6041. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  6042. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6043. }
  6044. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  6045. };
  6046. SpotLight.prototype._getWorldMatrix = function () {
  6047. if (!this._worldMatrix) {
  6048. this._worldMatrix = BABYLON.Matrix.Identity();
  6049. }
  6050. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6051. return this._worldMatrix;
  6052. };
  6053. return SpotLight;
  6054. })(BABYLON.Light);
  6055. BABYLON.SpotLight = SpotLight;
  6056. })(BABYLON || (BABYLON = {}));
  6057. //# sourceMappingURL=babylon.spotLight.js.map
  6058. var BABYLON;
  6059. (function (BABYLON) {
  6060. var DirectionalLight = (function (_super) {
  6061. __extends(DirectionalLight, _super);
  6062. function DirectionalLight(name, direction, scene) {
  6063. _super.call(this, name, scene);
  6064. this.direction = direction;
  6065. this.shadowOrthoScale = 0.1;
  6066. this.position = direction.scale(-1);
  6067. }
  6068. DirectionalLight.prototype.getAbsolutePosition = function () {
  6069. return this.transformedPosition ? this.transformedPosition : this.position;
  6070. };
  6071. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  6072. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  6073. return this.direction;
  6074. };
  6075. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  6076. var orthoLeft = Number.MAX_VALUE;
  6077. var orthoRight = Number.MIN_VALUE;
  6078. var orthoTop = Number.MIN_VALUE;
  6079. var orthoBottom = Number.MAX_VALUE;
  6080. var tempVector3 = BABYLON.Vector3.Zero();
  6081. var activeCamera = this.getScene().activeCamera;
  6082. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  6083. var mesh = renderList[meshIndex];
  6084. if (!mesh) {
  6085. continue;
  6086. }
  6087. var boundingInfo = mesh.getBoundingInfo();
  6088. if (!boundingInfo) {
  6089. continue;
  6090. }
  6091. var boundingBox = boundingInfo.boundingBox;
  6092. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  6093. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  6094. if (tempVector3.x < orthoLeft)
  6095. orthoLeft = tempVector3.x;
  6096. if (tempVector3.y < orthoBottom)
  6097. orthoBottom = tempVector3.y;
  6098. if (tempVector3.x > orthoRight)
  6099. orthoRight = tempVector3.x;
  6100. if (tempVector3.y > orthoTop)
  6101. orthoTop = tempVector3.y;
  6102. }
  6103. }
  6104. var xOffset = orthoRight - orthoLeft;
  6105. var yOffset = orthoTop - orthoBottom;
  6106. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  6107. };
  6108. DirectionalLight.prototype.supportsVSM = function () {
  6109. return true;
  6110. };
  6111. DirectionalLight.prototype.needRefreshPerFrame = function () {
  6112. return true;
  6113. };
  6114. DirectionalLight.prototype.computeTransformedPosition = function () {
  6115. if (this.parent && this.parent.getWorldMatrix) {
  6116. if (!this.transformedPosition) {
  6117. this.transformedPosition = BABYLON.Vector3.Zero();
  6118. }
  6119. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  6120. return true;
  6121. }
  6122. return false;
  6123. };
  6124. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  6125. if (this.parent && this.parent.getWorldMatrix) {
  6126. if (!this._transformedDirection) {
  6127. this._transformedDirection = BABYLON.Vector3.Zero();
  6128. }
  6129. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  6130. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  6131. return;
  6132. }
  6133. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  6134. };
  6135. DirectionalLight.prototype._getWorldMatrix = function () {
  6136. if (!this._worldMatrix) {
  6137. this._worldMatrix = BABYLON.Matrix.Identity();
  6138. }
  6139. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  6140. return this._worldMatrix;
  6141. };
  6142. return DirectionalLight;
  6143. })(BABYLON.Light);
  6144. BABYLON.DirectionalLight = DirectionalLight;
  6145. })(BABYLON || (BABYLON = {}));
  6146. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  6147. (function (BABYLON) {
  6148. var ShadowGenerator = (function () {
  6149. function ShadowGenerator(mapSize, light) {
  6150. var _this = this;
  6151. // Members
  6152. this._filter = ShadowGenerator.FILTER_NONE;
  6153. this.blurScale = 2;
  6154. this._blurBoxOffset = 0;
  6155. this._bias = 0.00005;
  6156. this._darkness = 0;
  6157. this._transparencyShadow = false;
  6158. this._viewMatrix = BABYLON.Matrix.Zero();
  6159. this._projectionMatrix = BABYLON.Matrix.Zero();
  6160. this._transformMatrix = BABYLON.Matrix.Zero();
  6161. this._worldViewProjection = BABYLON.Matrix.Zero();
  6162. this._light = light;
  6163. this._scene = light.getScene();
  6164. this._mapSize = mapSize;
  6165. light._shadowGenerator = this;
  6166. // Render target
  6167. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  6168. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6169. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6170. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6171. this._shadowMap.renderParticles = false;
  6172. this._shadowMap.onAfterUnbind = function () {
  6173. if (!_this.useBlurVarianceShadowMap) {
  6174. return;
  6175. }
  6176. if (!_this._shadowMap2) {
  6177. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  6178. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6179. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  6180. _this._shadowMap2.anisotropicFilteringLevel = 16;
  6181. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6182. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  6183. _this._downSamplePostprocess.onApply = function (effect) {
  6184. effect.setTexture("textureSampler", _this._shadowMap);
  6185. };
  6186. _this.blurBoxOffset = 1;
  6187. }
  6188. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  6189. };
  6190. // Custom render function
  6191. var renderSubMesh = function (subMesh) {
  6192. var mesh = subMesh.getRenderingMesh();
  6193. var scene = _this._scene;
  6194. var engine = scene.getEngine();
  6195. // Culling
  6196. engine.setState(subMesh.getMaterial().backFaceCulling);
  6197. // Managing instances
  6198. var batch = mesh._getInstancesRenderList(subMesh._id);
  6199. if (batch.mustReturn) {
  6200. return;
  6201. }
  6202. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  6203. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  6204. engine.enableEffect(_this._effect);
  6205. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  6206. var material = subMesh.getMaterial();
  6207. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  6208. // Alpha test
  6209. if (material && material.needAlphaTesting()) {
  6210. var alphaTexture = material.getAlphaTestTexture();
  6211. _this._effect.setTexture("diffuseSampler", alphaTexture);
  6212. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  6213. }
  6214. // Bones
  6215. if (mesh.useBones) {
  6216. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  6217. }
  6218. // Draw
  6219. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  6220. }
  6221. else {
  6222. // Need to reset refresh rate of the shadowMap
  6223. _this._shadowMap.resetRefreshCounter();
  6224. }
  6225. };
  6226. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  6227. var index;
  6228. for (index = 0; index < opaqueSubMeshes.length; index++) {
  6229. renderSubMesh(opaqueSubMeshes.data[index]);
  6230. }
  6231. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  6232. renderSubMesh(alphaTestSubMeshes.data[index]);
  6233. }
  6234. if (_this._transparencyShadow) {
  6235. for (index = 0; index < transparentSubMeshes.length; index++) {
  6236. renderSubMesh(transparentSubMeshes.data[index]);
  6237. }
  6238. }
  6239. };
  6240. this._shadowMap.onClear = function (engine) {
  6241. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  6242. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  6243. }
  6244. else {
  6245. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  6246. }
  6247. };
  6248. }
  6249. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  6250. // Static
  6251. get: function () {
  6252. return ShadowGenerator._FILTER_NONE;
  6253. },
  6254. enumerable: true,
  6255. configurable: true
  6256. });
  6257. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6258. get: function () {
  6259. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6260. },
  6261. enumerable: true,
  6262. configurable: true
  6263. });
  6264. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6265. get: function () {
  6266. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6267. },
  6268. enumerable: true,
  6269. configurable: true
  6270. });
  6271. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6272. get: function () {
  6273. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6274. },
  6275. enumerable: true,
  6276. configurable: true
  6277. });
  6278. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6279. get: function () {
  6280. return this._bias;
  6281. },
  6282. set: function (bias) {
  6283. this._bias = bias;
  6284. },
  6285. enumerable: true,
  6286. configurable: true
  6287. });
  6288. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6289. get: function () {
  6290. return this._blurBoxOffset;
  6291. },
  6292. set: function (value) {
  6293. var _this = this;
  6294. if (this._blurBoxOffset === value) {
  6295. return;
  6296. }
  6297. this._blurBoxOffset = value;
  6298. if (this._boxBlurPostprocess) {
  6299. this._boxBlurPostprocess.dispose();
  6300. }
  6301. 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);
  6302. this._boxBlurPostprocess.onApply = function (effect) {
  6303. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6304. };
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  6310. get: function () {
  6311. return this._filter;
  6312. },
  6313. set: function (value) {
  6314. if (this._filter === value) {
  6315. return;
  6316. }
  6317. this._filter = value;
  6318. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6319. this._shadowMap.anisotropicFilteringLevel = 16;
  6320. this._shadowMap.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  6321. }
  6322. else {
  6323. this._shadowMap.anisotropicFilteringLevel = 1;
  6324. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6325. }
  6326. },
  6327. enumerable: true,
  6328. configurable: true
  6329. });
  6330. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6331. get: function () {
  6332. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6333. },
  6334. set: function (value) {
  6335. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6336. },
  6337. enumerable: true,
  6338. configurable: true
  6339. });
  6340. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6341. get: function () {
  6342. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6343. },
  6344. set: function (value) {
  6345. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6346. },
  6347. enumerable: true,
  6348. configurable: true
  6349. });
  6350. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6351. get: function () {
  6352. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6353. },
  6354. set: function (value) {
  6355. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6356. },
  6357. enumerable: true,
  6358. configurable: true
  6359. });
  6360. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6361. var defines = [];
  6362. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6363. defines.push("#define VSM");
  6364. }
  6365. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6366. var mesh = subMesh.getMesh();
  6367. var material = subMesh.getMaterial();
  6368. // Alpha test
  6369. if (material && material.needAlphaTesting()) {
  6370. defines.push("#define ALPHATEST");
  6371. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6372. attribs.push(BABYLON.VertexBuffer.UVKind);
  6373. defines.push("#define UV1");
  6374. }
  6375. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6376. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6377. defines.push("#define UV2");
  6378. }
  6379. }
  6380. // Bones
  6381. if (mesh.useBones) {
  6382. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6383. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6384. defines.push("#define BONES");
  6385. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6386. }
  6387. // Instances
  6388. if (useInstances) {
  6389. defines.push("#define INSTANCES");
  6390. attribs.push("world0");
  6391. attribs.push("world1");
  6392. attribs.push("world2");
  6393. attribs.push("world3");
  6394. }
  6395. // Get correct effect
  6396. var join = defines.join("\n");
  6397. if (this._cachedDefines !== join) {
  6398. this._cachedDefines = join;
  6399. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6400. }
  6401. return this._effect.isReady();
  6402. };
  6403. ShadowGenerator.prototype.getShadowMap = function () {
  6404. return this._shadowMap;
  6405. };
  6406. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6407. if (this._shadowMap2) {
  6408. return this._shadowMap2;
  6409. }
  6410. return this._shadowMap;
  6411. };
  6412. ShadowGenerator.prototype.getLight = function () {
  6413. return this._light;
  6414. };
  6415. // Methods
  6416. ShadowGenerator.prototype.getTransformMatrix = function () {
  6417. var scene = this._scene;
  6418. if (this._currentRenderID === scene.getRenderId()) {
  6419. return this._transformMatrix;
  6420. }
  6421. this._currentRenderID = scene.getRenderId();
  6422. var lightPosition = this._light.position;
  6423. var lightDirection = this._light.direction;
  6424. if (this._light.computeTransformedPosition()) {
  6425. lightPosition = this._light.transformedPosition;
  6426. }
  6427. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6428. this._cachedPosition = lightPosition.clone();
  6429. this._cachedDirection = lightDirection.clone();
  6430. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6431. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6432. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6433. }
  6434. return this._transformMatrix;
  6435. };
  6436. ShadowGenerator.prototype.getDarkness = function () {
  6437. return this._darkness;
  6438. };
  6439. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6440. if (darkness >= 1.0)
  6441. this._darkness = 1.0;
  6442. else if (darkness <= 0.0)
  6443. this._darkness = 0.0;
  6444. else
  6445. this._darkness = darkness;
  6446. };
  6447. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6448. this._transparencyShadow = hasShadow;
  6449. };
  6450. ShadowGenerator.prototype._packHalf = function (depth) {
  6451. var scale = depth * 255.0;
  6452. var fract = scale - Math.floor(scale);
  6453. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6454. };
  6455. ShadowGenerator.prototype.dispose = function () {
  6456. this._shadowMap.dispose();
  6457. if (this._shadowMap2) {
  6458. this._shadowMap2.dispose();
  6459. }
  6460. if (this._downSamplePostprocess) {
  6461. this._downSamplePostprocess.dispose();
  6462. }
  6463. if (this._boxBlurPostprocess) {
  6464. this._boxBlurPostprocess.dispose();
  6465. }
  6466. };
  6467. ShadowGenerator._FILTER_NONE = 0;
  6468. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6469. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6470. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6471. return ShadowGenerator;
  6472. })();
  6473. BABYLON.ShadowGenerator = ShadowGenerator;
  6474. })(BABYLON || (BABYLON = {}));
  6475. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6476. var BABYLON;
  6477. (function (BABYLON) {
  6478. var HemisphericLight = (function (_super) {
  6479. __extends(HemisphericLight, _super);
  6480. function HemisphericLight(name, direction, scene) {
  6481. _super.call(this, name, scene);
  6482. this.direction = direction;
  6483. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6484. }
  6485. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6486. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6487. return this.direction;
  6488. };
  6489. HemisphericLight.prototype.getShadowGenerator = function () {
  6490. return null;
  6491. };
  6492. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6493. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6494. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6495. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6496. };
  6497. HemisphericLight.prototype._getWorldMatrix = function () {
  6498. if (!this._worldMatrix) {
  6499. this._worldMatrix = BABYLON.Matrix.Identity();
  6500. }
  6501. return this._worldMatrix;
  6502. };
  6503. return HemisphericLight;
  6504. })(BABYLON.Light);
  6505. BABYLON.HemisphericLight = HemisphericLight;
  6506. })(BABYLON || (BABYLON = {}));
  6507. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6508. (function (BABYLON) {
  6509. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6510. if (boxMin.x > sphereCenter.x + sphereRadius)
  6511. return false;
  6512. if (sphereCenter.x - sphereRadius > boxMax.x)
  6513. return false;
  6514. if (boxMin.y > sphereCenter.y + sphereRadius)
  6515. return false;
  6516. if (sphereCenter.y - sphereRadius > boxMax.y)
  6517. return false;
  6518. if (boxMin.z > sphereCenter.z + sphereRadius)
  6519. return false;
  6520. if (sphereCenter.z - sphereRadius > boxMax.z)
  6521. return false;
  6522. return true;
  6523. };
  6524. var getLowestRoot = function (a, b, c, maxR) {
  6525. var determinant = b * b - 4.0 * a * c;
  6526. var result = { root: 0, found: false };
  6527. if (determinant < 0)
  6528. return result;
  6529. var sqrtD = Math.sqrt(determinant);
  6530. var r1 = (-b - sqrtD) / (2.0 * a);
  6531. var r2 = (-b + sqrtD) / (2.0 * a);
  6532. if (r1 > r2) {
  6533. var temp = r2;
  6534. r2 = r1;
  6535. r1 = temp;
  6536. }
  6537. if (r1 > 0 && r1 < maxR) {
  6538. result.root = r1;
  6539. result.found = true;
  6540. return result;
  6541. }
  6542. if (r2 > 0 && r2 < maxR) {
  6543. result.root = r2;
  6544. result.found = true;
  6545. return result;
  6546. }
  6547. return result;
  6548. };
  6549. var Collider = (function () {
  6550. function Collider() {
  6551. this.radius = new BABYLON.Vector3(1, 1, 1);
  6552. this.retry = 0;
  6553. this.basePointWorld = BABYLON.Vector3.Zero();
  6554. this.velocityWorld = BABYLON.Vector3.Zero();
  6555. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6556. this._collisionPoint = BABYLON.Vector3.Zero();
  6557. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6558. this._tempVector = BABYLON.Vector3.Zero();
  6559. this._tempVector2 = BABYLON.Vector3.Zero();
  6560. this._tempVector3 = BABYLON.Vector3.Zero();
  6561. this._tempVector4 = BABYLON.Vector3.Zero();
  6562. this._edge = BABYLON.Vector3.Zero();
  6563. this._baseToVertex = BABYLON.Vector3.Zero();
  6564. this._destinationPoint = BABYLON.Vector3.Zero();
  6565. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6566. this._displacementVector = BABYLON.Vector3.Zero();
  6567. }
  6568. // Methods
  6569. Collider.prototype._initialize = function (source, dir, e) {
  6570. this.velocity = dir;
  6571. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6572. this.basePoint = source;
  6573. source.multiplyToRef(this.radius, this.basePointWorld);
  6574. dir.multiplyToRef(this.radius, this.velocityWorld);
  6575. this.velocityWorldLength = this.velocityWorld.length();
  6576. this.epsilon = e;
  6577. this.collisionFound = false;
  6578. };
  6579. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6580. pa.subtractToRef(point, this._tempVector);
  6581. pb.subtractToRef(point, this._tempVector2);
  6582. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6583. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6584. if (d < 0)
  6585. return false;
  6586. pc.subtractToRef(point, this._tempVector3);
  6587. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6588. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6589. if (d < 0)
  6590. return false;
  6591. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6592. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6593. return d >= 0;
  6594. };
  6595. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6596. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6597. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6598. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6599. return false;
  6600. }
  6601. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6602. return false;
  6603. return true;
  6604. };
  6605. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6606. var t0;
  6607. var embeddedInPlane = false;
  6608. if (!subMesh._trianglePlanes) {
  6609. subMesh._trianglePlanes = [];
  6610. }
  6611. if (!subMesh._trianglePlanes[faceIndex]) {
  6612. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6613. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6614. }
  6615. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6616. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6617. return;
  6618. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6619. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6620. if (normalDotVelocity == 0) {
  6621. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6622. return;
  6623. embeddedInPlane = true;
  6624. t0 = 0;
  6625. }
  6626. else {
  6627. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6628. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6629. if (t0 > t1) {
  6630. var temp = t1;
  6631. t1 = t0;
  6632. t0 = temp;
  6633. }
  6634. if (t0 > 1.0 || t1 < 0.0)
  6635. return;
  6636. if (t0 < 0)
  6637. t0 = 0;
  6638. if (t0 > 1.0)
  6639. t0 = 1.0;
  6640. }
  6641. this._collisionPoint.copyFromFloats(0, 0, 0);
  6642. var found = false;
  6643. var t = 1.0;
  6644. if (!embeddedInPlane) {
  6645. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6646. this.velocity.scaleToRef(t0, this._tempVector);
  6647. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6648. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6649. found = true;
  6650. t = t0;
  6651. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6652. }
  6653. }
  6654. if (!found) {
  6655. var velocitySquaredLength = this.velocity.lengthSquared();
  6656. var a = velocitySquaredLength;
  6657. this.basePoint.subtractToRef(p1, this._tempVector);
  6658. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6659. var c = this._tempVector.lengthSquared() - 1.0;
  6660. var lowestRoot = getLowestRoot(a, b, c, t);
  6661. if (lowestRoot.found) {
  6662. t = lowestRoot.root;
  6663. found = true;
  6664. this._collisionPoint.copyFrom(p1);
  6665. }
  6666. this.basePoint.subtractToRef(p2, this._tempVector);
  6667. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6668. c = this._tempVector.lengthSquared() - 1.0;
  6669. lowestRoot = getLowestRoot(a, b, c, t);
  6670. if (lowestRoot.found) {
  6671. t = lowestRoot.root;
  6672. found = true;
  6673. this._collisionPoint.copyFrom(p2);
  6674. }
  6675. this.basePoint.subtractToRef(p3, this._tempVector);
  6676. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6677. c = this._tempVector.lengthSquared() - 1.0;
  6678. lowestRoot = getLowestRoot(a, b, c, t);
  6679. if (lowestRoot.found) {
  6680. t = lowestRoot.root;
  6681. found = true;
  6682. this._collisionPoint.copyFrom(p3);
  6683. }
  6684. p2.subtractToRef(p1, this._edge);
  6685. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6686. var edgeSquaredLength = this._edge.lengthSquared();
  6687. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6688. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6689. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6690. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6691. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6692. lowestRoot = getLowestRoot(a, b, c, t);
  6693. if (lowestRoot.found) {
  6694. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6695. if (f >= 0.0 && f <= 1.0) {
  6696. t = lowestRoot.root;
  6697. found = true;
  6698. this._edge.scaleInPlace(f);
  6699. p1.addToRef(this._edge, this._collisionPoint);
  6700. }
  6701. }
  6702. p3.subtractToRef(p2, this._edge);
  6703. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6704. edgeSquaredLength = this._edge.lengthSquared();
  6705. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6706. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6707. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6708. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6709. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6710. lowestRoot = getLowestRoot(a, b, c, t);
  6711. if (lowestRoot.found) {
  6712. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6713. if (f >= 0.0 && f <= 1.0) {
  6714. t = lowestRoot.root;
  6715. found = true;
  6716. this._edge.scaleInPlace(f);
  6717. p2.addToRef(this._edge, this._collisionPoint);
  6718. }
  6719. }
  6720. p1.subtractToRef(p3, this._edge);
  6721. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6722. edgeSquaredLength = this._edge.lengthSquared();
  6723. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6724. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6725. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6726. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6727. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6728. lowestRoot = getLowestRoot(a, b, c, t);
  6729. if (lowestRoot.found) {
  6730. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6731. if (f >= 0.0 && f <= 1.0) {
  6732. t = lowestRoot.root;
  6733. found = true;
  6734. this._edge.scaleInPlace(f);
  6735. p3.addToRef(this._edge, this._collisionPoint);
  6736. }
  6737. }
  6738. }
  6739. if (found) {
  6740. var distToCollision = t * this.velocity.length();
  6741. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6742. if (!this.intersectionPoint) {
  6743. this.intersectionPoint = this._collisionPoint.clone();
  6744. }
  6745. else {
  6746. this.intersectionPoint.copyFrom(this._collisionPoint);
  6747. }
  6748. this.nearestDistance = distToCollision;
  6749. this.collisionFound = true;
  6750. this.collidedMesh = subMesh.getMesh();
  6751. }
  6752. }
  6753. };
  6754. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6755. for (var i = indexStart; i < indexEnd; i += 3) {
  6756. var p1 = pts[indices[i] - decal];
  6757. var p2 = pts[indices[i + 1] - decal];
  6758. var p3 = pts[indices[i + 2] - decal];
  6759. this._testTriangle(i, subMesh, p3, p2, p1);
  6760. }
  6761. };
  6762. Collider.prototype._getResponse = function (pos, vel) {
  6763. pos.addToRef(vel, this._destinationPoint);
  6764. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6765. this.basePoint.addToRef(vel, pos);
  6766. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6767. this._slidePlaneNormal.normalize();
  6768. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6769. pos.addInPlace(this._displacementVector);
  6770. this.intersectionPoint.addInPlace(this._displacementVector);
  6771. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6772. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6773. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6774. };
  6775. return Collider;
  6776. })();
  6777. BABYLON.Collider = Collider;
  6778. })(BABYLON || (BABYLON = {}));
  6779. //# sourceMappingURL=babylon.collider.js.map
  6780. var BABYLON;
  6781. (function (BABYLON) {
  6782. var Camera = (function (_super) {
  6783. __extends(Camera, _super);
  6784. function Camera(name, position, scene) {
  6785. _super.call(this, name, scene);
  6786. this.position = position;
  6787. // Members
  6788. this.upVector = BABYLON.Vector3.Up();
  6789. this.orthoLeft = null;
  6790. this.orthoRight = null;
  6791. this.orthoBottom = null;
  6792. this.orthoTop = null;
  6793. this.fov = 0.8;
  6794. this.minZ = 1.0;
  6795. this.maxZ = 10000.0;
  6796. this.inertia = 0.9;
  6797. this.mode = Camera.PERSPECTIVE_CAMERA;
  6798. this.isIntermediate = false;
  6799. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6800. this.subCameras = [];
  6801. this.layerMask = 0xFFFFFFFF;
  6802. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6803. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6804. this._projectionMatrix = new BABYLON.Matrix();
  6805. this._postProcesses = new Array();
  6806. this._postProcessesTakenIndices = [];
  6807. this._activeMeshes = new BABYLON.SmartArray(256);
  6808. scene.addCamera(this);
  6809. if (!scene.activeCamera) {
  6810. scene.activeCamera = this;
  6811. }
  6812. }
  6813. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6814. get: function () {
  6815. return Camera._PERSPECTIVE_CAMERA;
  6816. },
  6817. enumerable: true,
  6818. configurable: true
  6819. });
  6820. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6821. get: function () {
  6822. return Camera._ORTHOGRAPHIC_CAMERA;
  6823. },
  6824. enumerable: true,
  6825. configurable: true
  6826. });
  6827. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6828. get: function () {
  6829. return Camera._FOVMODE_VERTICAL_FIXED;
  6830. },
  6831. enumerable: true,
  6832. configurable: true
  6833. });
  6834. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6835. get: function () {
  6836. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6837. },
  6838. enumerable: true,
  6839. configurable: true
  6840. });
  6841. Camera.prototype.getActiveMeshes = function () {
  6842. return this._activeMeshes;
  6843. };
  6844. Camera.prototype.isActiveMesh = function (mesh) {
  6845. return (this._activeMeshes.indexOf(mesh) !== -1);
  6846. };
  6847. //Cache
  6848. Camera.prototype._initCache = function () {
  6849. _super.prototype._initCache.call(this);
  6850. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6851. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6852. this._cache.mode = undefined;
  6853. this._cache.minZ = undefined;
  6854. this._cache.maxZ = undefined;
  6855. this._cache.fov = undefined;
  6856. this._cache.aspectRatio = undefined;
  6857. this._cache.orthoLeft = undefined;
  6858. this._cache.orthoRight = undefined;
  6859. this._cache.orthoBottom = undefined;
  6860. this._cache.orthoTop = undefined;
  6861. this._cache.renderWidth = undefined;
  6862. this._cache.renderHeight = undefined;
  6863. };
  6864. Camera.prototype._updateCache = function (ignoreParentClass) {
  6865. if (!ignoreParentClass) {
  6866. _super.prototype._updateCache.call(this);
  6867. }
  6868. var engine = this.getEngine();
  6869. this._cache.position.copyFrom(this.position);
  6870. this._cache.upVector.copyFrom(this.upVector);
  6871. this._cache.mode = this.mode;
  6872. this._cache.minZ = this.minZ;
  6873. this._cache.maxZ = this.maxZ;
  6874. this._cache.fov = this.fov;
  6875. this._cache.aspectRatio = engine.getAspectRatio(this);
  6876. this._cache.orthoLeft = this.orthoLeft;
  6877. this._cache.orthoRight = this.orthoRight;
  6878. this._cache.orthoBottom = this.orthoBottom;
  6879. this._cache.orthoTop = this.orthoTop;
  6880. this._cache.renderWidth = engine.getRenderWidth();
  6881. this._cache.renderHeight = engine.getRenderHeight();
  6882. };
  6883. Camera.prototype._updateFromScene = function () {
  6884. this.updateCache();
  6885. this._update();
  6886. };
  6887. // Synchronized
  6888. Camera.prototype._isSynchronized = function () {
  6889. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6890. };
  6891. Camera.prototype._isSynchronizedViewMatrix = function () {
  6892. if (!_super.prototype._isSynchronized.call(this))
  6893. return false;
  6894. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6895. };
  6896. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6897. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6898. if (!check) {
  6899. return false;
  6900. }
  6901. var engine = this.getEngine();
  6902. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6903. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6904. }
  6905. else {
  6906. 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();
  6907. }
  6908. return check;
  6909. };
  6910. // Controls
  6911. Camera.prototype.attachControl = function (element) {
  6912. };
  6913. Camera.prototype.detachControl = function (element) {
  6914. };
  6915. Camera.prototype._update = function () {
  6916. };
  6917. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6918. if (insertAt === void 0) { insertAt = null; }
  6919. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6920. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6921. return 0;
  6922. }
  6923. if (insertAt == null || insertAt < 0) {
  6924. this._postProcesses.push(postProcess);
  6925. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6926. return this._postProcesses.length - 1;
  6927. }
  6928. var add = 0;
  6929. if (this._postProcesses[insertAt]) {
  6930. var start = this._postProcesses.length - 1;
  6931. for (var i = start; i >= insertAt + 1; --i) {
  6932. this._postProcesses[i + 1] = this._postProcesses[i];
  6933. }
  6934. add = 1;
  6935. }
  6936. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6937. if (this._postProcessesTakenIndices[i] < insertAt) {
  6938. continue;
  6939. }
  6940. start = this._postProcessesTakenIndices.length - 1;
  6941. for (var j = start; j >= i; --j) {
  6942. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6943. }
  6944. this._postProcessesTakenIndices[i] = insertAt;
  6945. break;
  6946. }
  6947. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6948. this._postProcessesTakenIndices.push(insertAt);
  6949. }
  6950. var result = insertAt + add;
  6951. this._postProcesses[result] = postProcess;
  6952. return result;
  6953. };
  6954. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6955. if (atIndices === void 0) { atIndices = null; }
  6956. var result = [];
  6957. if (!atIndices) {
  6958. var length = this._postProcesses.length;
  6959. for (var i = 0; i < length; i++) {
  6960. if (this._postProcesses[i] !== postProcess) {
  6961. continue;
  6962. }
  6963. delete this._postProcesses[i];
  6964. var index = this._postProcessesTakenIndices.indexOf(i);
  6965. this._postProcessesTakenIndices.splice(index, 1);
  6966. }
  6967. }
  6968. else {
  6969. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6970. for (i = 0; i < atIndices.length; i++) {
  6971. var foundPostProcess = this._postProcesses[atIndices[i]];
  6972. if (foundPostProcess !== postProcess) {
  6973. result.push(i);
  6974. continue;
  6975. }
  6976. delete this._postProcesses[atIndices[i]];
  6977. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6978. this._postProcessesTakenIndices.splice(index, 1);
  6979. }
  6980. }
  6981. return result;
  6982. };
  6983. Camera.prototype.getWorldMatrix = function () {
  6984. if (!this._worldMatrix) {
  6985. this._worldMatrix = BABYLON.Matrix.Identity();
  6986. }
  6987. var viewMatrix = this.getViewMatrix();
  6988. viewMatrix.invertToRef(this._worldMatrix);
  6989. return this._worldMatrix;
  6990. };
  6991. Camera.prototype._getViewMatrix = function () {
  6992. return BABYLON.Matrix.Identity();
  6993. };
  6994. Camera.prototype.getViewMatrix = function () {
  6995. this._computedViewMatrix = this._computeViewMatrix();
  6996. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6997. return this._computedViewMatrix;
  6998. }
  6999. if (!this._worldMatrix) {
  7000. this._worldMatrix = BABYLON.Matrix.Identity();
  7001. }
  7002. this._computedViewMatrix.invertToRef(this._worldMatrix);
  7003. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  7004. this._computedViewMatrix.invert();
  7005. this._currentRenderId = this.getScene().getRenderId();
  7006. return this._computedViewMatrix;
  7007. };
  7008. Camera.prototype._computeViewMatrix = function (force) {
  7009. if (!force && this._isSynchronizedViewMatrix()) {
  7010. return this._computedViewMatrix;
  7011. }
  7012. this._computedViewMatrix = this._getViewMatrix();
  7013. if (!this.parent || !this.parent.getWorldMatrix) {
  7014. this._currentRenderId = this.getScene().getRenderId();
  7015. }
  7016. return this._computedViewMatrix;
  7017. };
  7018. Camera.prototype.getProjectionMatrix = function (force) {
  7019. if (!force && this._isSynchronizedProjectionMatrix()) {
  7020. return this._projectionMatrix;
  7021. }
  7022. var engine = this.getEngine();
  7023. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  7024. if (this.minZ <= 0) {
  7025. this.minZ = 0.1;
  7026. }
  7027. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  7028. return this._projectionMatrix;
  7029. }
  7030. var halfWidth = engine.getRenderWidth() / 2.0;
  7031. var halfHeight = engine.getRenderHeight() / 2.0;
  7032. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  7033. return this._projectionMatrix;
  7034. };
  7035. Camera.prototype.dispose = function () {
  7036. // Remove from scene
  7037. this.getScene().removeCamera(this);
  7038. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  7039. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  7040. }
  7041. };
  7042. // Statics
  7043. Camera._PERSPECTIVE_CAMERA = 0;
  7044. Camera._ORTHOGRAPHIC_CAMERA = 1;
  7045. Camera._FOVMODE_VERTICAL_FIXED = 0;
  7046. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  7047. return Camera;
  7048. })(BABYLON.Node);
  7049. BABYLON.Camera = Camera;
  7050. })(BABYLON || (BABYLON = {}));
  7051. //# sourceMappingURL=babylon.camera.js.map
  7052. var BABYLON;
  7053. (function (BABYLON) {
  7054. var TargetCamera = (function (_super) {
  7055. __extends(TargetCamera, _super);
  7056. function TargetCamera(name, position, scene) {
  7057. _super.call(this, name, position, scene);
  7058. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7059. this.cameraRotation = new BABYLON.Vector2(0, 0);
  7060. this.rotation = new BABYLON.Vector3(0, 0, 0);
  7061. this.speed = 2.0;
  7062. this.noRotationConstraint = false;
  7063. this.lockedTarget = null;
  7064. this._currentTarget = BABYLON.Vector3.Zero();
  7065. this._viewMatrix = BABYLON.Matrix.Zero();
  7066. this._camMatrix = BABYLON.Matrix.Zero();
  7067. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  7068. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  7069. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  7070. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  7071. this._lookAtTemp = BABYLON.Matrix.Zero();
  7072. this._tempMatrix = BABYLON.Matrix.Zero();
  7073. }
  7074. TargetCamera.prototype._getLockedTargetPosition = function () {
  7075. if (!this.lockedTarget) {
  7076. return null;
  7077. }
  7078. return this.lockedTarget.position || this.lockedTarget;
  7079. };
  7080. // Cache
  7081. TargetCamera.prototype._initCache = function () {
  7082. _super.prototype._initCache.call(this);
  7083. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7084. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7085. };
  7086. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  7087. if (!ignoreParentClass) {
  7088. _super.prototype._updateCache.call(this);
  7089. }
  7090. var lockedTargetPosition = this._getLockedTargetPosition();
  7091. if (!lockedTargetPosition) {
  7092. this._cache.lockedTarget = null;
  7093. }
  7094. else {
  7095. if (!this._cache.lockedTarget) {
  7096. this._cache.lockedTarget = lockedTargetPosition.clone();
  7097. }
  7098. else {
  7099. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  7100. }
  7101. }
  7102. this._cache.rotation.copyFrom(this.rotation);
  7103. };
  7104. // Synchronized
  7105. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  7106. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  7107. return false;
  7108. }
  7109. var lockedTargetPosition = this._getLockedTargetPosition();
  7110. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  7111. };
  7112. // Methods
  7113. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  7114. var engine = this.getEngine();
  7115. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  7116. };
  7117. // Target
  7118. TargetCamera.prototype.setTarget = function (target) {
  7119. this.upVector.normalize();
  7120. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  7121. this._camMatrix.invert();
  7122. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  7123. var vDir = target.subtract(this.position);
  7124. if (vDir.x >= 0.0) {
  7125. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  7126. }
  7127. else {
  7128. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  7129. }
  7130. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  7131. if (isNaN(this.rotation.x)) {
  7132. this.rotation.x = 0;
  7133. }
  7134. if (isNaN(this.rotation.y)) {
  7135. this.rotation.y = 0;
  7136. }
  7137. if (isNaN(this.rotation.z)) {
  7138. this.rotation.z = 0;
  7139. }
  7140. };
  7141. TargetCamera.prototype.getTarget = function () {
  7142. return this._currentTarget;
  7143. };
  7144. TargetCamera.prototype._decideIfNeedsToMove = function () {
  7145. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7146. };
  7147. TargetCamera.prototype._updatePosition = function () {
  7148. this.position.addInPlace(this.cameraDirection);
  7149. };
  7150. TargetCamera.prototype._update = function () {
  7151. var needToMove = this._decideIfNeedsToMove();
  7152. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  7153. // Move
  7154. if (needToMove) {
  7155. this._updatePosition();
  7156. }
  7157. // Rotate
  7158. if (needToRotate) {
  7159. this.rotation.x += this.cameraRotation.x;
  7160. this.rotation.y += this.cameraRotation.y;
  7161. if (!this.noRotationConstraint) {
  7162. var limit = (Math.PI / 2) * 0.95;
  7163. if (this.rotation.x > limit)
  7164. this.rotation.x = limit;
  7165. if (this.rotation.x < -limit)
  7166. this.rotation.x = -limit;
  7167. }
  7168. }
  7169. // Inertia
  7170. if (needToMove) {
  7171. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  7172. this.cameraDirection.x = 0;
  7173. }
  7174. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  7175. this.cameraDirection.y = 0;
  7176. }
  7177. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  7178. this.cameraDirection.z = 0;
  7179. }
  7180. this.cameraDirection.scaleInPlace(this.inertia);
  7181. }
  7182. if (needToRotate) {
  7183. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  7184. this.cameraRotation.x = 0;
  7185. }
  7186. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  7187. this.cameraRotation.y = 0;
  7188. }
  7189. this.cameraRotation.scaleInPlace(this.inertia);
  7190. }
  7191. };
  7192. TargetCamera.prototype._getViewMatrix = function () {
  7193. if (!this.lockedTarget) {
  7194. // Compute
  7195. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  7196. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  7197. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7198. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  7199. this._lookAtTemp.invert();
  7200. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  7201. }
  7202. else {
  7203. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  7204. }
  7205. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  7206. // Computing target and final matrix
  7207. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  7208. }
  7209. else {
  7210. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  7211. }
  7212. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  7213. return this._viewMatrix;
  7214. };
  7215. return TargetCamera;
  7216. })(BABYLON.Camera);
  7217. BABYLON.TargetCamera = TargetCamera;
  7218. })(BABYLON || (BABYLON = {}));
  7219. //# sourceMappingURL=babylon.targetCamera.js.map
  7220. var BABYLON;
  7221. (function (BABYLON) {
  7222. var FollowCamera = (function (_super) {
  7223. __extends(FollowCamera, _super);
  7224. function FollowCamera(name, position, scene) {
  7225. _super.call(this, name, position, scene);
  7226. this.radius = 12;
  7227. this.rotationOffset = 0;
  7228. this.heightOffset = 4;
  7229. this.cameraAcceleration = 0.05;
  7230. this.maxCameraSpeed = 20;
  7231. }
  7232. FollowCamera.prototype.getRadians = function (degrees) {
  7233. return degrees * Math.PI / 180;
  7234. };
  7235. FollowCamera.prototype.follow = function (cameraTarget) {
  7236. if (!cameraTarget)
  7237. return;
  7238. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  7239. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  7240. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  7241. var dx = targetX - this.position.x;
  7242. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  7243. var dz = (targetZ) - this.position.z;
  7244. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  7245. var vy = dy * this.cameraAcceleration;
  7246. var vz = dz * this.cameraAcceleration * 2;
  7247. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  7248. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7249. }
  7250. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  7251. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7252. }
  7253. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  7254. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  7255. }
  7256. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  7257. this.setTarget(cameraTarget.position);
  7258. };
  7259. FollowCamera.prototype._update = function () {
  7260. _super.prototype._update.call(this);
  7261. this.follow(this.target);
  7262. };
  7263. return FollowCamera;
  7264. })(BABYLON.TargetCamera);
  7265. BABYLON.FollowCamera = FollowCamera;
  7266. })(BABYLON || (BABYLON = {}));
  7267. //# sourceMappingURL=babylon.followCamera.js.map
  7268. var BABYLON;
  7269. (function (BABYLON) {
  7270. var FreeCamera = (function (_super) {
  7271. __extends(FreeCamera, _super);
  7272. function FreeCamera(name, position, scene) {
  7273. _super.call(this, name, position, scene);
  7274. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7275. this.keysUp = [38];
  7276. this.keysDown = [40];
  7277. this.keysLeft = [37];
  7278. this.keysRight = [39];
  7279. this.checkCollisions = false;
  7280. this.applyGravity = false;
  7281. this.angularSensibility = 2000.0;
  7282. this._keys = [];
  7283. this._collider = new BABYLON.Collider();
  7284. this._needMoveForGravity = true;
  7285. this._oldPosition = BABYLON.Vector3.Zero();
  7286. this._diffPosition = BABYLON.Vector3.Zero();
  7287. this._newPosition = BABYLON.Vector3.Zero();
  7288. }
  7289. // Controls
  7290. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7291. var _this = this;
  7292. var previousPosition;
  7293. var engine = this.getEngine();
  7294. if (this._attachedElement) {
  7295. return;
  7296. }
  7297. this._attachedElement = element;
  7298. if (this._onMouseDown === undefined) {
  7299. this._onMouseDown = function (evt) {
  7300. previousPosition = {
  7301. x: evt.clientX,
  7302. y: evt.clientY
  7303. };
  7304. if (!noPreventDefault) {
  7305. evt.preventDefault();
  7306. }
  7307. };
  7308. this._onMouseUp = function (evt) {
  7309. previousPosition = null;
  7310. if (!noPreventDefault) {
  7311. evt.preventDefault();
  7312. }
  7313. };
  7314. this._onMouseOut = function (evt) {
  7315. previousPosition = null;
  7316. _this._keys = [];
  7317. if (!noPreventDefault) {
  7318. evt.preventDefault();
  7319. }
  7320. };
  7321. this._onMouseMove = function (evt) {
  7322. if (!previousPosition && !engine.isPointerLock) {
  7323. return;
  7324. }
  7325. var offsetX;
  7326. var offsetY;
  7327. if (!engine.isPointerLock) {
  7328. offsetX = evt.clientX - previousPosition.x;
  7329. offsetY = evt.clientY - previousPosition.y;
  7330. }
  7331. else {
  7332. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7333. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7334. }
  7335. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7336. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7337. previousPosition = {
  7338. x: evt.clientX,
  7339. y: evt.clientY
  7340. };
  7341. if (!noPreventDefault) {
  7342. evt.preventDefault();
  7343. }
  7344. };
  7345. this._onKeyDown = function (evt) {
  7346. 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) {
  7347. var index = _this._keys.indexOf(evt.keyCode);
  7348. if (index === -1) {
  7349. _this._keys.push(evt.keyCode);
  7350. }
  7351. if (!noPreventDefault) {
  7352. evt.preventDefault();
  7353. }
  7354. }
  7355. };
  7356. this._onKeyUp = function (evt) {
  7357. 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) {
  7358. var index = _this._keys.indexOf(evt.keyCode);
  7359. if (index >= 0) {
  7360. _this._keys.splice(index, 1);
  7361. }
  7362. if (!noPreventDefault) {
  7363. evt.preventDefault();
  7364. }
  7365. }
  7366. };
  7367. this._onLostFocus = function () {
  7368. _this._keys = [];
  7369. };
  7370. this._reset = function () {
  7371. _this._keys = [];
  7372. previousPosition = null;
  7373. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7374. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7375. };
  7376. }
  7377. element.addEventListener("mousedown", this._onMouseDown, false);
  7378. element.addEventListener("mouseup", this._onMouseUp, false);
  7379. element.addEventListener("mouseout", this._onMouseOut, false);
  7380. element.addEventListener("mousemove", this._onMouseMove, false);
  7381. BABYLON.Tools.RegisterTopRootEvents([
  7382. { name: "keydown", handler: this._onKeyDown },
  7383. { name: "keyup", handler: this._onKeyUp },
  7384. { name: "blur", handler: this._onLostFocus }
  7385. ]);
  7386. };
  7387. FreeCamera.prototype.detachControl = function (element) {
  7388. if (this._attachedElement != element) {
  7389. return;
  7390. }
  7391. element.removeEventListener("mousedown", this._onMouseDown);
  7392. element.removeEventListener("mouseup", this._onMouseUp);
  7393. element.removeEventListener("mouseout", this._onMouseOut);
  7394. element.removeEventListener("mousemove", this._onMouseMove);
  7395. BABYLON.Tools.UnregisterTopRootEvents([
  7396. { name: "keydown", handler: this._onKeyDown },
  7397. { name: "keyup", handler: this._onKeyUp },
  7398. { name: "blur", handler: this._onLostFocus }
  7399. ]);
  7400. this._attachedElement = null;
  7401. if (this._reset) {
  7402. this._reset();
  7403. }
  7404. };
  7405. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7406. var globalPosition;
  7407. if (this.parent) {
  7408. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7409. }
  7410. else {
  7411. globalPosition = this.position;
  7412. }
  7413. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7414. this._collider.radius = this.ellipsoid;
  7415. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7416. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7417. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7418. this.position.addInPlace(this._diffPosition);
  7419. if (this.onCollide) {
  7420. this.onCollide(this._collider.collidedMesh);
  7421. }
  7422. }
  7423. };
  7424. FreeCamera.prototype._checkInputs = function () {
  7425. if (!this._localDirection) {
  7426. this._localDirection = BABYLON.Vector3.Zero();
  7427. this._transformedDirection = BABYLON.Vector3.Zero();
  7428. }
  7429. for (var index = 0; index < this._keys.length; index++) {
  7430. var keyCode = this._keys[index];
  7431. var speed = this._computeLocalCameraSpeed();
  7432. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7433. this._localDirection.copyFromFloats(-speed, 0, 0);
  7434. }
  7435. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7436. this._localDirection.copyFromFloats(0, 0, speed);
  7437. }
  7438. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7439. this._localDirection.copyFromFloats(speed, 0, 0);
  7440. }
  7441. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7442. this._localDirection.copyFromFloats(0, 0, -speed);
  7443. }
  7444. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7445. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7446. this.cameraDirection.addInPlace(this._transformedDirection);
  7447. }
  7448. };
  7449. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7450. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7451. };
  7452. FreeCamera.prototype._updatePosition = function () {
  7453. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7454. this._collideWithWorld(this.cameraDirection);
  7455. if (this.applyGravity) {
  7456. var oldPosition = this.position;
  7457. this._collideWithWorld(this.getScene().gravity);
  7458. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7459. }
  7460. }
  7461. else {
  7462. this.position.addInPlace(this.cameraDirection);
  7463. }
  7464. };
  7465. FreeCamera.prototype._update = function () {
  7466. this._checkInputs();
  7467. _super.prototype._update.call(this);
  7468. };
  7469. return FreeCamera;
  7470. })(BABYLON.TargetCamera);
  7471. BABYLON.FreeCamera = FreeCamera;
  7472. })(BABYLON || (BABYLON = {}));
  7473. //# sourceMappingURL=babylon.freeCamera.js.map
  7474. var BABYLON;
  7475. (function (BABYLON) {
  7476. // We're mainly based on the logic defined into the FreeCamera code
  7477. var TouchCamera = (function (_super) {
  7478. __extends(TouchCamera, _super);
  7479. function TouchCamera(name, position, scene) {
  7480. _super.call(this, name, position, scene);
  7481. this._offsetX = null;
  7482. this._offsetY = null;
  7483. this._pointerCount = 0;
  7484. this._pointerPressed = [];
  7485. this.angularSensibility = 200000.0;
  7486. this.moveSensibility = 500.0;
  7487. }
  7488. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7489. var _this = this;
  7490. var previousPosition;
  7491. if (this._attachedCanvas) {
  7492. return;
  7493. }
  7494. this._attachedCanvas = canvas;
  7495. if (this._onPointerDown === undefined) {
  7496. this._onPointerDown = function (evt) {
  7497. if (!noPreventDefault) {
  7498. evt.preventDefault();
  7499. }
  7500. _this._pointerPressed.push(evt.pointerId);
  7501. if (_this._pointerPressed.length !== 1) {
  7502. return;
  7503. }
  7504. previousPosition = {
  7505. x: evt.clientX,
  7506. y: evt.clientY
  7507. };
  7508. };
  7509. this._onPointerUp = function (evt) {
  7510. if (!noPreventDefault) {
  7511. evt.preventDefault();
  7512. }
  7513. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7514. if (index === -1) {
  7515. return;
  7516. }
  7517. _this._pointerPressed.splice(index, 1);
  7518. if (index != 0) {
  7519. return;
  7520. }
  7521. previousPosition = null;
  7522. _this._offsetX = null;
  7523. _this._offsetY = null;
  7524. };
  7525. this._onPointerMove = function (evt) {
  7526. if (!noPreventDefault) {
  7527. evt.preventDefault();
  7528. }
  7529. if (!previousPosition) {
  7530. return;
  7531. }
  7532. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7533. if (index != 0) {
  7534. return;
  7535. }
  7536. _this._offsetX = evt.clientX - previousPosition.x;
  7537. _this._offsetY = -(evt.clientY - previousPosition.y);
  7538. };
  7539. this._onLostFocus = function () {
  7540. _this._offsetX = null;
  7541. _this._offsetY = null;
  7542. };
  7543. }
  7544. canvas.addEventListener("pointerdown", this._onPointerDown);
  7545. canvas.addEventListener("pointerup", this._onPointerUp);
  7546. canvas.addEventListener("pointerout", this._onPointerUp);
  7547. canvas.addEventListener("pointermove", this._onPointerMove);
  7548. BABYLON.Tools.RegisterTopRootEvents([
  7549. { name: "blur", handler: this._onLostFocus }
  7550. ]);
  7551. };
  7552. TouchCamera.prototype.detachControl = function (canvas) {
  7553. if (this._attachedCanvas != canvas) {
  7554. return;
  7555. }
  7556. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7557. canvas.removeEventListener("pointerup", this._onPointerUp);
  7558. canvas.removeEventListener("pointerout", this._onPointerUp);
  7559. canvas.removeEventListener("pointermove", this._onPointerMove);
  7560. BABYLON.Tools.UnregisterTopRootEvents([
  7561. { name: "blur", handler: this._onLostFocus }
  7562. ]);
  7563. this._attachedCanvas = null;
  7564. };
  7565. TouchCamera.prototype._checkInputs = function () {
  7566. if (!this._offsetX) {
  7567. return;
  7568. }
  7569. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7570. if (this._pointerPressed.length > 1) {
  7571. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7572. }
  7573. else {
  7574. var speed = this._computeLocalCameraSpeed();
  7575. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7576. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7577. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7578. }
  7579. };
  7580. return TouchCamera;
  7581. })(BABYLON.FreeCamera);
  7582. BABYLON.TouchCamera = TouchCamera;
  7583. })(BABYLON || (BABYLON = {}));
  7584. //# sourceMappingURL=babylon.touchCamera.js.map
  7585. var BABYLON;
  7586. (function (BABYLON) {
  7587. // We're mainly based on the logic defined into the FreeCamera code
  7588. var DeviceOrientationCamera = (function (_super) {
  7589. __extends(DeviceOrientationCamera, _super);
  7590. function DeviceOrientationCamera(name, position, scene) {
  7591. var _this = this;
  7592. _super.call(this, name, position, scene);
  7593. this._offsetX = null;
  7594. this._offsetY = null;
  7595. this._orientationGamma = 0;
  7596. this._orientationBeta = 0;
  7597. this._initialOrientationGamma = 0;
  7598. this._initialOrientationBeta = 0;
  7599. this.angularSensibility = 10000.0;
  7600. this.moveSensibility = 50.0;
  7601. window.addEventListener("resize", function () {
  7602. _this._initialOrientationGamma = null;
  7603. }, false);
  7604. }
  7605. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7606. var _this = this;
  7607. if (this._attachedCanvas) {
  7608. return;
  7609. }
  7610. this._attachedCanvas = canvas;
  7611. if (!this._orientationChanged) {
  7612. this._orientationChanged = function (evt) {
  7613. if (!_this._initialOrientationGamma) {
  7614. _this._initialOrientationGamma = evt.gamma;
  7615. _this._initialOrientationBeta = evt.beta;
  7616. }
  7617. _this._orientationGamma = evt.gamma;
  7618. _this._orientationBeta = evt.beta;
  7619. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7620. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7621. };
  7622. }
  7623. window.addEventListener("deviceorientation", this._orientationChanged);
  7624. };
  7625. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7626. if (this._attachedCanvas != canvas) {
  7627. return;
  7628. }
  7629. window.removeEventListener("deviceorientation", this._orientationChanged);
  7630. this._attachedCanvas = null;
  7631. this._orientationGamma = 0;
  7632. this._orientationBeta = 0;
  7633. this._initialOrientationGamma = 0;
  7634. this._initialOrientationBeta = 0;
  7635. };
  7636. DeviceOrientationCamera.prototype._checkInputs = function () {
  7637. if (!this._offsetX) {
  7638. return;
  7639. }
  7640. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7641. var speed = this._computeLocalCameraSpeed();
  7642. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7643. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7644. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7645. };
  7646. return DeviceOrientationCamera;
  7647. })(BABYLON.FreeCamera);
  7648. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7649. })(BABYLON || (BABYLON = {}));
  7650. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7651. var BABYLON;
  7652. (function (BABYLON) {
  7653. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7654. var ArcRotateCamera = (function (_super) {
  7655. __extends(ArcRotateCamera, _super);
  7656. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7657. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7658. this.alpha = alpha;
  7659. this.beta = beta;
  7660. this.radius = radius;
  7661. this.target = target;
  7662. this.inertialAlphaOffset = 0;
  7663. this.inertialBetaOffset = 0;
  7664. this.inertialRadiusOffset = 0;
  7665. this.lowerAlphaLimit = null;
  7666. this.upperAlphaLimit = null;
  7667. this.lowerBetaLimit = 0.01;
  7668. this.upperBetaLimit = Math.PI;
  7669. this.lowerRadiusLimit = null;
  7670. this.upperRadiusLimit = null;
  7671. this.angularSensibility = 1000.0;
  7672. this.wheelPrecision = 3.0;
  7673. this.pinchPrecision = 2.0;
  7674. this.keysUp = [38];
  7675. this.keysDown = [40];
  7676. this.keysLeft = [37];
  7677. this.keysRight = [39];
  7678. this.zoomOnFactor = 1;
  7679. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7680. this._keys = [];
  7681. this._viewMatrix = new BABYLON.Matrix();
  7682. this.checkCollisions = false;
  7683. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7684. this._collider = new BABYLON.Collider();
  7685. this._previousPosition = BABYLON.Vector3.Zero();
  7686. this._collisionVelocity = BABYLON.Vector3.Zero();
  7687. this._newPosition = BABYLON.Vector3.Zero();
  7688. this.getViewMatrix();
  7689. }
  7690. ArcRotateCamera.prototype._getTargetPosition = function () {
  7691. return this.target.position || this.target;
  7692. };
  7693. // Cache
  7694. ArcRotateCamera.prototype._initCache = function () {
  7695. _super.prototype._initCache.call(this);
  7696. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7697. this._cache.alpha = undefined;
  7698. this._cache.beta = undefined;
  7699. this._cache.radius = undefined;
  7700. this._cache.targetScreenOffset = undefined;
  7701. };
  7702. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7703. if (!ignoreParentClass) {
  7704. _super.prototype._updateCache.call(this);
  7705. }
  7706. this._cache.target.copyFrom(this._getTargetPosition());
  7707. this._cache.alpha = this.alpha;
  7708. this._cache.beta = this.beta;
  7709. this._cache.radius = this.radius;
  7710. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7711. };
  7712. // Synchronized
  7713. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7714. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7715. return false;
  7716. 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);
  7717. };
  7718. // Methods
  7719. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7720. var _this = this;
  7721. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  7722. var previousPinchDistance = 0;
  7723. var pointers = new BABYLON.SmartCollection();
  7724. if (this._attachedElement) {
  7725. return;
  7726. }
  7727. this._attachedElement = element;
  7728. var engine = this.getEngine();
  7729. if (this._onPointerDown === undefined) {
  7730. this._onPointerDown = function (evt) {
  7731. pointers.add(evt.pointerId, { x: evt.clientX, y: evt.clientY, type: evt.pointerType });
  7732. cacheSoloPointer = pointers.item(evt.pointerId);
  7733. if (!noPreventDefault) {
  7734. evt.preventDefault();
  7735. }
  7736. };
  7737. this._onPointerUp = function (evt) {
  7738. cacheSoloPointer = null;
  7739. previousPinchDistance = 0;
  7740. pointers.remove(evt.pointerId);
  7741. if (!noPreventDefault) {
  7742. evt.preventDefault();
  7743. }
  7744. };
  7745. this._onPointerMove = function (evt) {
  7746. if (!noPreventDefault) {
  7747. evt.preventDefault();
  7748. }
  7749. switch (pointers.count) {
  7750. case 1:
  7751. //var offsetX = evt.clientX - pointers.item(evt.pointerId).x;
  7752. //var offsetY = evt.clientY - pointers.item(evt.pointerId).y;
  7753. var offsetX = evt.clientX - cacheSoloPointer.x;
  7754. var offsetY = evt.clientY - cacheSoloPointer.y;
  7755. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7756. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7757. //pointers.item(evt.pointerId).x = evt.clientX;
  7758. //pointers.item(evt.pointerId).y = evt.clientY;
  7759. cacheSoloPointer.x = evt.clientX;
  7760. cacheSoloPointer.y = evt.clientY;
  7761. break;
  7762. case 2:
  7763. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be usefull to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  7764. pointers.item(evt.pointerId).x = evt.clientX;
  7765. pointers.item(evt.pointerId).y = evt.clientY;
  7766. var direction = 1;
  7767. var distX = pointers.getItemByIndex(0).x - pointers.getItemByIndex(1).x;
  7768. var distY = pointers.getItemByIndex(0).y - pointers.getItemByIndex(1).y;
  7769. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  7770. if (previousPinchDistance === 0) {
  7771. previousPinchDistance = pinchSquaredDistance;
  7772. return;
  7773. }
  7774. if (pinchSquaredDistance != previousPinchDistance) {
  7775. if (pinchSquaredDistance > previousPinchDistance) {
  7776. direction = -1;
  7777. }
  7778. _this.inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) / (_this.pinchPrecision * _this.wheelPrecision * _this.angularSensibility);
  7779. previousPinchDistance = pinchSquaredDistance;
  7780. }
  7781. break;
  7782. default:
  7783. if (pointers.item(evt.pointerId)) {
  7784. pointers.item(evt.pointerId).x = evt.clientX;
  7785. pointers.item(evt.pointerId).y = evt.clientY;
  7786. }
  7787. }
  7788. };
  7789. this._onMouseMove = function (evt) {
  7790. if (!engine.isPointerLock) {
  7791. return;
  7792. }
  7793. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7794. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7795. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7796. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7797. if (!noPreventDefault) {
  7798. evt.preventDefault();
  7799. }
  7800. };
  7801. this._wheel = function (event) {
  7802. var delta = 0;
  7803. if (event.wheelDelta) {
  7804. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7805. }
  7806. else if (event.detail) {
  7807. delta = -event.detail / _this.wheelPrecision;
  7808. }
  7809. if (delta)
  7810. _this.inertialRadiusOffset += delta;
  7811. if (event.preventDefault) {
  7812. if (!noPreventDefault) {
  7813. event.preventDefault();
  7814. }
  7815. }
  7816. };
  7817. this._onKeyDown = function (evt) {
  7818. 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) {
  7819. var index = _this._keys.indexOf(evt.keyCode);
  7820. if (index === -1) {
  7821. _this._keys.push(evt.keyCode);
  7822. }
  7823. if (evt.preventDefault) {
  7824. if (!noPreventDefault) {
  7825. evt.preventDefault();
  7826. }
  7827. }
  7828. }
  7829. };
  7830. this._onKeyUp = function (evt) {
  7831. 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) {
  7832. var index = _this._keys.indexOf(evt.keyCode);
  7833. if (index >= 0) {
  7834. _this._keys.splice(index, 1);
  7835. }
  7836. if (evt.preventDefault) {
  7837. if (!noPreventDefault) {
  7838. evt.preventDefault();
  7839. }
  7840. }
  7841. }
  7842. };
  7843. this._onLostFocus = function () {
  7844. _this._keys = [];
  7845. pointers.empty();
  7846. previousPinchDistance = 0;
  7847. cacheSoloPointer = null;
  7848. };
  7849. this._onGestureStart = function (e) {
  7850. if (window.MSGesture === undefined) {
  7851. return;
  7852. }
  7853. if (!_this._MSGestureHandler) {
  7854. _this._MSGestureHandler = new MSGesture();
  7855. _this._MSGestureHandler.target = element;
  7856. }
  7857. _this._MSGestureHandler.addPointer(e.pointerId);
  7858. };
  7859. this._onGesture = function (e) {
  7860. _this.radius *= e.scale;
  7861. if (e.preventDefault) {
  7862. if (!noPreventDefault) {
  7863. e.stopPropagation();
  7864. e.preventDefault();
  7865. }
  7866. }
  7867. };
  7868. this._reset = function () {
  7869. _this._keys = [];
  7870. _this.inertialAlphaOffset = 0;
  7871. _this.inertialBetaOffset = 0;
  7872. _this.inertialRadiusOffset = 0;
  7873. pointers.empty();
  7874. previousPinchDistance = 0;
  7875. cacheSoloPointer = null;
  7876. };
  7877. }
  7878. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7879. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7880. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7881. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7882. element.addEventListener("mousemove", this._onMouseMove, false);
  7883. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7884. element.addEventListener("MSGestureChange", this._onGesture, false);
  7885. element.addEventListener('mousewheel', this._wheel, false);
  7886. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7887. BABYLON.Tools.RegisterTopRootEvents([
  7888. { name: "keydown", handler: this._onKeyDown },
  7889. { name: "keyup", handler: this._onKeyUp },
  7890. { name: "blur", handler: this._onLostFocus }
  7891. ]);
  7892. };
  7893. ArcRotateCamera.prototype.detachControl = function (element) {
  7894. if (this._attachedElement != element) {
  7895. return;
  7896. }
  7897. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7898. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7899. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7900. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7901. element.removeEventListener("mousemove", this._onMouseMove);
  7902. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7903. element.removeEventListener("MSGestureChange", this._onGesture);
  7904. element.removeEventListener('mousewheel', this._wheel);
  7905. element.removeEventListener('DOMMouseScroll', this._wheel);
  7906. BABYLON.Tools.UnregisterTopRootEvents([
  7907. { name: "keydown", handler: this._onKeyDown },
  7908. { name: "keyup", handler: this._onKeyUp },
  7909. { name: "blur", handler: this._onLostFocus }
  7910. ]);
  7911. this._MSGestureHandler = null;
  7912. this._attachedElement = null;
  7913. if (this._reset) {
  7914. this._reset();
  7915. }
  7916. };
  7917. ArcRotateCamera.prototype._update = function () {
  7918. for (var index = 0; index < this._keys.length; index++) {
  7919. var keyCode = this._keys[index];
  7920. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7921. this.inertialAlphaOffset -= 0.01;
  7922. }
  7923. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7924. this.inertialBetaOffset -= 0.01;
  7925. }
  7926. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7927. this.inertialAlphaOffset += 0.01;
  7928. }
  7929. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7930. this.inertialBetaOffset += 0.01;
  7931. }
  7932. }
  7933. // Inertia
  7934. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7935. this.alpha += this.inertialAlphaOffset;
  7936. this.beta += this.inertialBetaOffset;
  7937. this.radius -= this.inertialRadiusOffset;
  7938. this.inertialAlphaOffset *= this.inertia;
  7939. this.inertialBetaOffset *= this.inertia;
  7940. this.inertialRadiusOffset *= this.inertia;
  7941. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7942. this.inertialAlphaOffset = 0;
  7943. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7944. this.inertialBetaOffset = 0;
  7945. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7946. this.inertialRadiusOffset = 0;
  7947. }
  7948. // Limits
  7949. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7950. this.alpha = this.lowerAlphaLimit;
  7951. }
  7952. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7953. this.alpha = this.upperAlphaLimit;
  7954. }
  7955. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7956. this.beta = this.lowerBetaLimit;
  7957. }
  7958. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7959. this.beta = this.upperBetaLimit;
  7960. }
  7961. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7962. this.radius = this.lowerRadiusLimit;
  7963. }
  7964. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7965. this.radius = this.upperRadiusLimit;
  7966. }
  7967. };
  7968. ArcRotateCamera.prototype.setPosition = function (position) {
  7969. var radiusv3 = position.subtract(this._getTargetPosition());
  7970. this.radius = radiusv3.length();
  7971. // Alpha
  7972. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7973. if (radiusv3.z < 0) {
  7974. this.alpha = 2 * Math.PI - this.alpha;
  7975. }
  7976. // Beta
  7977. this.beta = Math.acos(radiusv3.y / this.radius);
  7978. };
  7979. ArcRotateCamera.prototype._getViewMatrix = function () {
  7980. // Compute
  7981. var cosa = Math.cos(this.alpha);
  7982. var sina = Math.sin(this.alpha);
  7983. var cosb = Math.cos(this.beta);
  7984. var sinb = Math.sin(this.beta);
  7985. var target = this._getTargetPosition();
  7986. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7987. if (this.checkCollisions) {
  7988. this._collider.radius = this.collisionRadius;
  7989. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7990. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7991. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7992. this.position.copyFrom(this._previousPosition);
  7993. this.alpha = this._previousAlpha;
  7994. this.beta = this._previousBeta;
  7995. this.radius = this._previousRadius;
  7996. if (this.onCollide) {
  7997. this.onCollide(this._collider.collidedMesh);
  7998. }
  7999. }
  8000. }
  8001. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  8002. this._previousAlpha = this.alpha;
  8003. this._previousBeta = this.beta;
  8004. this._previousRadius = this.radius;
  8005. this._previousPosition.copyFrom(this.position);
  8006. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  8007. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  8008. return this._viewMatrix;
  8009. };
  8010. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  8011. meshes = meshes || this.getScene().meshes;
  8012. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  8013. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  8014. this.radius = distance * this.zoomOnFactor;
  8015. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  8016. };
  8017. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  8018. var meshesOrMinMaxVector;
  8019. var distance;
  8020. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  8021. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  8022. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  8023. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  8024. }
  8025. else {
  8026. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  8027. distance = meshesOrMinMaxVectorAndDistance.distance;
  8028. }
  8029. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  8030. this.maxZ = distance * 2;
  8031. };
  8032. return ArcRotateCamera;
  8033. })(BABYLON.Camera);
  8034. BABYLON.ArcRotateCamera = ArcRotateCamera;
  8035. })(BABYLON || (BABYLON = {}));
  8036. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  8037. (function (BABYLON) {
  8038. /**
  8039. * Represents a scene to be rendered by the engine.
  8040. * @see http://doc.babylonjs.com/page.php?p=21911
  8041. */
  8042. var Scene = (function () {
  8043. /**
  8044. * @constructor
  8045. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  8046. */
  8047. function Scene(engine) {
  8048. // Members
  8049. this.autoClear = true;
  8050. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8051. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  8052. this.forceWireframe = false;
  8053. this.forcePointsCloud = false;
  8054. this.forceShowBoundingBoxes = false;
  8055. this.animationsEnabled = true;
  8056. 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
  8057. // Fog
  8058. /**
  8059. * is fog enabled on this scene.
  8060. * @type {boolean}
  8061. */
  8062. this.fogEnabled = true;
  8063. this.fogMode = Scene.FOGMODE_NONE;
  8064. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  8065. this.fogDensity = 0.1;
  8066. this.fogStart = 0;
  8067. this.fogEnd = 1000.0;
  8068. // Lights
  8069. /**
  8070. * is shadow enabled on this scene.
  8071. * @type {boolean}
  8072. */
  8073. this.shadowsEnabled = true;
  8074. /**
  8075. * is light enabled on this scene.
  8076. * @type {boolean}
  8077. */
  8078. this.lightsEnabled = true;
  8079. /**
  8080. * All of the lights added to this scene.
  8081. * @see BABYLON.Light
  8082. * @type {BABYLON.Light[]}
  8083. */
  8084. this.lights = new Array();
  8085. // Cameras
  8086. /**
  8087. * All of the cameras added to this scene.
  8088. * @see BABYLON.Camera
  8089. * @type {BABYLON.Camera[]}
  8090. */
  8091. this.cameras = new Array();
  8092. this.activeCameras = new Array();
  8093. // Meshes
  8094. /**
  8095. * All of the (abstract) meshes added to this scene.
  8096. * @see BABYLON.AbstractMesh
  8097. * @type {BABYLON.AbstractMesh[]}
  8098. */
  8099. this.meshes = new Array();
  8100. // Geometries
  8101. this._geometries = new Array();
  8102. this.materials = new Array();
  8103. this.multiMaterials = new Array();
  8104. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  8105. // Textures
  8106. this.texturesEnabled = true;
  8107. this.textures = new Array();
  8108. // Particles
  8109. this.particlesEnabled = true;
  8110. this.particleSystems = new Array();
  8111. // Sprites
  8112. this.spritesEnabled = true;
  8113. this.spriteManagers = new Array();
  8114. // Layers
  8115. this.layers = new Array();
  8116. // Skeletons
  8117. this.skeletonsEnabled = true;
  8118. this.skeletons = new Array();
  8119. // Lens flares
  8120. this.lensFlaresEnabled = true;
  8121. this.lensFlareSystems = new Array();
  8122. // Collisions
  8123. this.collisionsEnabled = true;
  8124. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  8125. // Postprocesses
  8126. this.postProcessesEnabled = true;
  8127. // Customs render targets
  8128. this.renderTargetsEnabled = true;
  8129. this.dumpNextRenderTargets = false;
  8130. this.customRenderTargets = new Array();
  8131. // Imported meshes
  8132. this.importedMeshesFiles = new Array();
  8133. this._actionManagers = new Array();
  8134. this._meshesForIntersections = new BABYLON.SmartArray(256);
  8135. // Procedural textures
  8136. this.proceduralTexturesEnabled = true;
  8137. this._proceduralTextures = new Array();
  8138. this.soundTracks = new Array();
  8139. this._audioEnabled = true;
  8140. this._headphone = false;
  8141. this._totalVertices = 0;
  8142. this._activeVertices = 0;
  8143. this._activeParticles = 0;
  8144. this._lastFrameDuration = 0;
  8145. this._evaluateActiveMeshesDuration = 0;
  8146. this._renderTargetsDuration = 0;
  8147. this._particlesDuration = 0;
  8148. this._renderDuration = 0;
  8149. this._spritesDuration = 0;
  8150. this._animationRatio = 0;
  8151. this._renderId = 0;
  8152. this._executeWhenReadyTimeoutId = -1;
  8153. this._toBeDisposed = new BABYLON.SmartArray(256);
  8154. this._onReadyCallbacks = new Array();
  8155. this._pendingData = []; //ANY
  8156. this._onBeforeRenderCallbacks = new Array();
  8157. this._onAfterRenderCallbacks = new Array();
  8158. this._activeMeshes = new BABYLON.SmartArray(256);
  8159. this._processedMaterials = new BABYLON.SmartArray(256);
  8160. this._renderTargets = new BABYLON.SmartArray(256);
  8161. this._activeParticleSystems = new BABYLON.SmartArray(256);
  8162. this._activeSkeletons = new BABYLON.SmartArray(32);
  8163. this._activeBones = 0;
  8164. this._activeAnimatables = new Array();
  8165. this._transformMatrix = BABYLON.Matrix.Zero();
  8166. this._scaledPosition = BABYLON.Vector3.Zero();
  8167. this._scaledVelocity = BABYLON.Vector3.Zero();
  8168. this._engine = engine;
  8169. engine.scenes.push(this);
  8170. this._renderingManager = new BABYLON.RenderingManager(this);
  8171. this.postProcessManager = new BABYLON.PostProcessManager(this);
  8172. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  8173. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  8174. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  8175. this.attachControl();
  8176. this._debugLayer = new BABYLON.DebugLayer(this);
  8177. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  8178. //simplification queue
  8179. this.simplificationQueue = new BABYLON.SimplificationQueue();
  8180. }
  8181. Object.defineProperty(Scene, "FOGMODE_NONE", {
  8182. get: function () {
  8183. return Scene._FOGMODE_NONE;
  8184. },
  8185. enumerable: true,
  8186. configurable: true
  8187. });
  8188. Object.defineProperty(Scene, "FOGMODE_EXP", {
  8189. get: function () {
  8190. return Scene._FOGMODE_EXP;
  8191. },
  8192. enumerable: true,
  8193. configurable: true
  8194. });
  8195. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  8196. get: function () {
  8197. return Scene._FOGMODE_EXP2;
  8198. },
  8199. enumerable: true,
  8200. configurable: true
  8201. });
  8202. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  8203. get: function () {
  8204. return Scene._FOGMODE_LINEAR;
  8205. },
  8206. enumerable: true,
  8207. configurable: true
  8208. });
  8209. Object.defineProperty(Scene.prototype, "debugLayer", {
  8210. // Properties
  8211. get: function () {
  8212. return this._debugLayer;
  8213. },
  8214. enumerable: true,
  8215. configurable: true
  8216. });
  8217. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  8218. /**
  8219. * The mesh that is currently under the pointer.
  8220. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8221. */
  8222. get: function () {
  8223. return this._meshUnderPointer;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Scene.prototype, "pointerX", {
  8229. /**
  8230. * Current on-screen X position of the pointer
  8231. * @return {number} X position of the pointer
  8232. */
  8233. get: function () {
  8234. return this._pointerX;
  8235. },
  8236. enumerable: true,
  8237. configurable: true
  8238. });
  8239. Object.defineProperty(Scene.prototype, "pointerY", {
  8240. /**
  8241. * Current on-screen Y position of the pointer
  8242. * @return {number} Y position of the pointer
  8243. */
  8244. get: function () {
  8245. return this._pointerY;
  8246. },
  8247. enumerable: true,
  8248. configurable: true
  8249. });
  8250. Scene.prototype.getCachedMaterial = function () {
  8251. return this._cachedMaterial;
  8252. };
  8253. Scene.prototype.getBoundingBoxRenderer = function () {
  8254. return this._boundingBoxRenderer;
  8255. };
  8256. Scene.prototype.getOutlineRenderer = function () {
  8257. return this._outlineRenderer;
  8258. };
  8259. Scene.prototype.getEngine = function () {
  8260. return this._engine;
  8261. };
  8262. Scene.prototype.getTotalVertices = function () {
  8263. return this._totalVertices;
  8264. };
  8265. Scene.prototype.getActiveVertices = function () {
  8266. return this._activeVertices;
  8267. };
  8268. Scene.prototype.getActiveParticles = function () {
  8269. return this._activeParticles;
  8270. };
  8271. Scene.prototype.getActiveBones = function () {
  8272. return this._activeBones;
  8273. };
  8274. // Stats
  8275. Scene.prototype.getLastFrameDuration = function () {
  8276. return this._lastFrameDuration;
  8277. };
  8278. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8279. return this._evaluateActiveMeshesDuration;
  8280. };
  8281. Scene.prototype.getActiveMeshes = function () {
  8282. return this._activeMeshes;
  8283. };
  8284. Scene.prototype.getRenderTargetsDuration = function () {
  8285. return this._renderTargetsDuration;
  8286. };
  8287. Scene.prototype.getRenderDuration = function () {
  8288. return this._renderDuration;
  8289. };
  8290. Scene.prototype.getParticlesDuration = function () {
  8291. return this._particlesDuration;
  8292. };
  8293. Scene.prototype.getSpritesDuration = function () {
  8294. return this._spritesDuration;
  8295. };
  8296. Scene.prototype.getAnimationRatio = function () {
  8297. return this._animationRatio;
  8298. };
  8299. Scene.prototype.getRenderId = function () {
  8300. return this._renderId;
  8301. };
  8302. Scene.prototype.incrementRenderId = function () {
  8303. this._renderId++;
  8304. };
  8305. Scene.prototype._updatePointerPosition = function (evt) {
  8306. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8307. this._pointerX = evt.clientX - canvasRect.left;
  8308. this._pointerY = evt.clientY - canvasRect.top;
  8309. if (this.cameraToUseForPointers) {
  8310. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8311. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8312. }
  8313. };
  8314. // Pointers handling
  8315. Scene.prototype.attachControl = function () {
  8316. var _this = this;
  8317. this._onPointerMove = function (evt) {
  8318. var canvas = _this._engine.getRenderingCanvas();
  8319. _this._updatePointerPosition(evt);
  8320. 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);
  8321. if (pickResult.hit) {
  8322. _this._meshUnderPointer = pickResult.pickedMesh;
  8323. _this.setPointerOverMesh(pickResult.pickedMesh);
  8324. canvas.style.cursor = "pointer";
  8325. }
  8326. else {
  8327. _this.setPointerOverMesh(null);
  8328. canvas.style.cursor = "";
  8329. _this._meshUnderPointer = null;
  8330. }
  8331. };
  8332. this._onPointerDown = function (evt) {
  8333. var predicate = null;
  8334. if (!_this.onPointerDown) {
  8335. predicate = function (mesh) {
  8336. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8337. };
  8338. }
  8339. _this._updatePointerPosition(evt);
  8340. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8341. if (pickResult.hit) {
  8342. if (pickResult.pickedMesh.actionManager) {
  8343. switch (evt.button) {
  8344. case 0:
  8345. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8346. break;
  8347. case 1:
  8348. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8349. break;
  8350. case 2:
  8351. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8352. break;
  8353. }
  8354. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8355. }
  8356. }
  8357. if (_this.onPointerDown) {
  8358. _this.onPointerDown(evt, pickResult);
  8359. }
  8360. };
  8361. this._onKeyDown = function (evt) {
  8362. if (_this.actionManager) {
  8363. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8364. }
  8365. };
  8366. this._onKeyUp = function (evt) {
  8367. if (_this.actionManager) {
  8368. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8369. }
  8370. };
  8371. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8372. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8373. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8374. BABYLON.Tools.RegisterTopRootEvents([
  8375. { name: "keydown", handler: this._onKeyDown },
  8376. { name: "keyup", handler: this._onKeyUp }
  8377. ]);
  8378. };
  8379. Scene.prototype.detachControl = function () {
  8380. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8381. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8382. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8383. BABYLON.Tools.UnregisterTopRootEvents([
  8384. { name: "keydown", handler: this._onKeyDown },
  8385. { name: "keyup", handler: this._onKeyUp }
  8386. ]);
  8387. };
  8388. // Ready
  8389. Scene.prototype.isReady = function () {
  8390. if (this._pendingData.length > 0) {
  8391. return false;
  8392. }
  8393. for (var index = 0; index < this._geometries.length; index++) {
  8394. var geometry = this._geometries[index];
  8395. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8396. return false;
  8397. }
  8398. }
  8399. for (index = 0; index < this.meshes.length; index++) {
  8400. var mesh = this.meshes[index];
  8401. if (!mesh.isReady()) {
  8402. return false;
  8403. }
  8404. var mat = mesh.material;
  8405. if (mat) {
  8406. if (!mat.isReady(mesh)) {
  8407. return false;
  8408. }
  8409. }
  8410. }
  8411. return true;
  8412. };
  8413. Scene.prototype.resetCachedMaterial = function () {
  8414. this._cachedMaterial = null;
  8415. };
  8416. Scene.prototype.registerBeforeRender = function (func) {
  8417. this._onBeforeRenderCallbacks.push(func);
  8418. };
  8419. Scene.prototype.unregisterBeforeRender = function (func) {
  8420. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8421. if (index > -1) {
  8422. this._onBeforeRenderCallbacks.splice(index, 1);
  8423. }
  8424. };
  8425. Scene.prototype.registerAfterRender = function (func) {
  8426. this._onAfterRenderCallbacks.push(func);
  8427. };
  8428. Scene.prototype.unregisterAfterRender = function (func) {
  8429. var index = this._onAfterRenderCallbacks.indexOf(func);
  8430. if (index > -1) {
  8431. this._onAfterRenderCallbacks.splice(index, 1);
  8432. }
  8433. };
  8434. Scene.prototype._addPendingData = function (data) {
  8435. this._pendingData.push(data);
  8436. };
  8437. Scene.prototype._removePendingData = function (data) {
  8438. var index = this._pendingData.indexOf(data);
  8439. if (index !== -1) {
  8440. this._pendingData.splice(index, 1);
  8441. }
  8442. };
  8443. Scene.prototype.getWaitingItemsCount = function () {
  8444. return this._pendingData.length;
  8445. };
  8446. /**
  8447. * Registers a function to be executed when the scene is ready.
  8448. * @param {Function} func - the function to be executed.
  8449. */
  8450. Scene.prototype.executeWhenReady = function (func) {
  8451. var _this = this;
  8452. this._onReadyCallbacks.push(func);
  8453. if (this._executeWhenReadyTimeoutId !== -1) {
  8454. return;
  8455. }
  8456. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8457. _this._checkIsReady();
  8458. }, 150);
  8459. };
  8460. Scene.prototype._checkIsReady = function () {
  8461. var _this = this;
  8462. if (this.isReady()) {
  8463. this._onReadyCallbacks.forEach(function (func) {
  8464. func();
  8465. });
  8466. this._onReadyCallbacks = [];
  8467. this._executeWhenReadyTimeoutId = -1;
  8468. return;
  8469. }
  8470. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8471. _this._checkIsReady();
  8472. }, 150);
  8473. };
  8474. // Animations
  8475. /**
  8476. * Will start the animation sequence of a given target
  8477. * @param target - the target
  8478. * @param {number} from - from which frame should animation start
  8479. * @param {number} to - till which frame should animation run.
  8480. * @param {boolean} [loop] - should the animation loop
  8481. * @param {number} [speedRatio] - the speed in which to run the animation
  8482. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8483. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8484. * @return {BABYLON.Animatable} the animatable object created for this animation
  8485. * @see BABYLON.Animatable
  8486. * @see http://doc.babylonjs.com/page.php?p=22081
  8487. */
  8488. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8489. if (speedRatio === undefined) {
  8490. speedRatio = 1.0;
  8491. }
  8492. this.stopAnimation(target);
  8493. if (!animatable) {
  8494. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8495. }
  8496. // Local animations
  8497. if (target.animations) {
  8498. animatable.appendAnimations(target, target.animations);
  8499. }
  8500. // Children animations
  8501. if (target.getAnimatables) {
  8502. var animatables = target.getAnimatables();
  8503. for (var index = 0; index < animatables.length; index++) {
  8504. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8505. }
  8506. }
  8507. return animatable;
  8508. };
  8509. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8510. if (speedRatio === undefined) {
  8511. speedRatio = 1.0;
  8512. }
  8513. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8514. return animatable;
  8515. };
  8516. Scene.prototype.getAnimatableByTarget = function (target) {
  8517. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8518. if (this._activeAnimatables[index].target === target) {
  8519. return this._activeAnimatables[index];
  8520. }
  8521. }
  8522. return null;
  8523. };
  8524. /**
  8525. * Will stop the animation of the given target
  8526. * @param target - the target
  8527. * @see beginAnimation
  8528. */
  8529. Scene.prototype.stopAnimation = function (target) {
  8530. var animatable = this.getAnimatableByTarget(target);
  8531. if (animatable) {
  8532. animatable.stop();
  8533. }
  8534. };
  8535. Scene.prototype._animate = function () {
  8536. if (!this.animationsEnabled) {
  8537. return;
  8538. }
  8539. if (!this._animationStartDate) {
  8540. this._animationStartDate = BABYLON.Tools.Now;
  8541. }
  8542. // Getting time
  8543. var now = BABYLON.Tools.Now;
  8544. var delay = now - this._animationStartDate;
  8545. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8546. if (!this._activeAnimatables[index]._animate(delay)) {
  8547. this._activeAnimatables.splice(index, 1);
  8548. index--;
  8549. }
  8550. }
  8551. };
  8552. // Matrix
  8553. Scene.prototype.getViewMatrix = function () {
  8554. return this._viewMatrix;
  8555. };
  8556. Scene.prototype.getProjectionMatrix = function () {
  8557. return this._projectionMatrix;
  8558. };
  8559. Scene.prototype.getTransformMatrix = function () {
  8560. return this._transformMatrix;
  8561. };
  8562. Scene.prototype.setTransformMatrix = function (view, projection) {
  8563. this._viewMatrix = view;
  8564. this._projectionMatrix = projection;
  8565. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8566. };
  8567. // Methods
  8568. Scene.prototype.addMesh = function (newMesh) {
  8569. var position = this.meshes.push(newMesh);
  8570. if (this.onNewMeshAdded) {
  8571. this.onNewMeshAdded(newMesh, position, this);
  8572. }
  8573. };
  8574. Scene.prototype.removeMesh = function (toRemove) {
  8575. var index = this.meshes.indexOf(toRemove);
  8576. if (index !== -1) {
  8577. // Remove from the scene if mesh found
  8578. this.meshes.splice(index, 1);
  8579. }
  8580. if (this.onMeshRemoved) {
  8581. this.onMeshRemoved(toRemove);
  8582. }
  8583. return index;
  8584. };
  8585. Scene.prototype.removeLight = function (toRemove) {
  8586. var index = this.lights.indexOf(toRemove);
  8587. if (index !== -1) {
  8588. // Remove from the scene if mesh found
  8589. this.lights.splice(index, 1);
  8590. }
  8591. if (this.onLightRemoved) {
  8592. this.onLightRemoved(toRemove);
  8593. }
  8594. return index;
  8595. };
  8596. Scene.prototype.removeCamera = function (toRemove) {
  8597. var index = this.cameras.indexOf(toRemove);
  8598. if (index !== -1) {
  8599. // Remove from the scene if mesh found
  8600. this.cameras.splice(index, 1);
  8601. }
  8602. if (this.onCameraRemoved) {
  8603. this.onCameraRemoved(toRemove);
  8604. }
  8605. return index;
  8606. };
  8607. Scene.prototype.addLight = function (newLight) {
  8608. var position = this.lights.push(newLight);
  8609. if (this.onNewLightAdded) {
  8610. this.onNewLightAdded(newLight, position, this);
  8611. }
  8612. };
  8613. Scene.prototype.addCamera = function (newCamera) {
  8614. var position = this.cameras.push(newCamera);
  8615. if (this.onNewCameraAdded) {
  8616. this.onNewCameraAdded(newCamera, position, this);
  8617. }
  8618. };
  8619. /**
  8620. * sets the active camera of the scene using its ID
  8621. * @param {string} id - the camera's ID
  8622. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8623. * @see activeCamera
  8624. */
  8625. Scene.prototype.setActiveCameraByID = function (id) {
  8626. var camera = this.getCameraByID(id);
  8627. if (camera) {
  8628. this.activeCamera = camera;
  8629. return camera;
  8630. }
  8631. return null;
  8632. };
  8633. /**
  8634. * sets the active camera of the scene using its name
  8635. * @param {string} name - the camera's name
  8636. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8637. * @see activeCamera
  8638. */
  8639. Scene.prototype.setActiveCameraByName = function (name) {
  8640. var camera = this.getCameraByName(name);
  8641. if (camera) {
  8642. this.activeCamera = camera;
  8643. return camera;
  8644. }
  8645. return null;
  8646. };
  8647. /**
  8648. * get a material using its id
  8649. * @param {string} the material's ID
  8650. * @return {BABYLON.Material|null} the material or null if none found.
  8651. */
  8652. Scene.prototype.getMaterialByID = function (id) {
  8653. for (var index = 0; index < this.materials.length; index++) {
  8654. if (this.materials[index].id === id) {
  8655. return this.materials[index];
  8656. }
  8657. }
  8658. return null;
  8659. };
  8660. /**
  8661. * get a material using its name
  8662. * @param {string} the material's name
  8663. * @return {BABYLON.Material|null} the material or null if none found.
  8664. */
  8665. Scene.prototype.getMaterialByName = function (name) {
  8666. for (var index = 0; index < this.materials.length; index++) {
  8667. if (this.materials[index].name === name) {
  8668. return this.materials[index];
  8669. }
  8670. }
  8671. return null;
  8672. };
  8673. Scene.prototype.getCameraByID = function (id) {
  8674. for (var index = 0; index < this.cameras.length; index++) {
  8675. if (this.cameras[index].id === id) {
  8676. return this.cameras[index];
  8677. }
  8678. }
  8679. return null;
  8680. };
  8681. /**
  8682. * get a camera using its name
  8683. * @param {string} the camera's name
  8684. * @return {BABYLON.Camera|null} the camera or null if none found.
  8685. */
  8686. Scene.prototype.getCameraByName = function (name) {
  8687. for (var index = 0; index < this.cameras.length; index++) {
  8688. if (this.cameras[index].name === name) {
  8689. return this.cameras[index];
  8690. }
  8691. }
  8692. return null;
  8693. };
  8694. /**
  8695. * get a light node using its name
  8696. * @param {string} the light's name
  8697. * @return {BABYLON.Light|null} the light or null if none found.
  8698. */
  8699. Scene.prototype.getLightByName = function (name) {
  8700. for (var index = 0; index < this.lights.length; index++) {
  8701. if (this.lights[index].name === name) {
  8702. return this.lights[index];
  8703. }
  8704. }
  8705. return null;
  8706. };
  8707. /**
  8708. * get a light node using its ID
  8709. * @param {string} the light's id
  8710. * @return {BABYLON.Light|null} the light or null if none found.
  8711. */
  8712. Scene.prototype.getLightByID = function (id) {
  8713. for (var index = 0; index < this.lights.length; index++) {
  8714. if (this.lights[index].id === id) {
  8715. return this.lights[index];
  8716. }
  8717. }
  8718. return null;
  8719. };
  8720. /**
  8721. * get a geometry using its ID
  8722. * @param {string} the geometry's id
  8723. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8724. */
  8725. Scene.prototype.getGeometryByID = function (id) {
  8726. for (var index = 0; index < this._geometries.length; index++) {
  8727. if (this._geometries[index].id === id) {
  8728. return this._geometries[index];
  8729. }
  8730. }
  8731. return null;
  8732. };
  8733. /**
  8734. * add a new geometry to this scene.
  8735. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8736. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8737. * @return {boolean} was the geometry added or not
  8738. */
  8739. Scene.prototype.pushGeometry = function (geometry, force) {
  8740. if (!force && this.getGeometryByID(geometry.id)) {
  8741. return false;
  8742. }
  8743. this._geometries.push(geometry);
  8744. return true;
  8745. };
  8746. Scene.prototype.getGeometries = function () {
  8747. return this._geometries;
  8748. };
  8749. /**
  8750. * Get a the first added mesh found of a given ID
  8751. * @param {string} id - the id to search for
  8752. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8753. */
  8754. Scene.prototype.getMeshByID = function (id) {
  8755. for (var index = 0; index < this.meshes.length; index++) {
  8756. if (this.meshes[index].id === id) {
  8757. return this.meshes[index];
  8758. }
  8759. }
  8760. return null;
  8761. };
  8762. /**
  8763. * Get a the last added mesh found of a given ID
  8764. * @param {string} id - the id to search for
  8765. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8766. */
  8767. Scene.prototype.getLastMeshByID = function (id) {
  8768. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8769. if (this.meshes[index].id === id) {
  8770. return this.meshes[index];
  8771. }
  8772. }
  8773. return null;
  8774. };
  8775. /**
  8776. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8777. * @param {string} id - the id to search for
  8778. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8779. */
  8780. Scene.prototype.getLastEntryByID = function (id) {
  8781. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8782. if (this.meshes[index].id === id) {
  8783. return this.meshes[index];
  8784. }
  8785. }
  8786. for (index = this.cameras.length - 1; index >= 0; index--) {
  8787. if (this.cameras[index].id === id) {
  8788. return this.cameras[index];
  8789. }
  8790. }
  8791. for (index = this.lights.length - 1; index >= 0; index--) {
  8792. if (this.lights[index].id === id) {
  8793. return this.lights[index];
  8794. }
  8795. }
  8796. return null;
  8797. };
  8798. Scene.prototype.getNodeByName = function (name) {
  8799. var mesh = this.getMeshByName(name);
  8800. if (mesh) {
  8801. return mesh;
  8802. }
  8803. var light = this.getLightByName(name);
  8804. if (light) {
  8805. return light;
  8806. }
  8807. return this.getCameraByName(name);
  8808. };
  8809. Scene.prototype.getMeshByName = function (name) {
  8810. for (var index = 0; index < this.meshes.length; index++) {
  8811. if (this.meshes[index].name === name) {
  8812. return this.meshes[index];
  8813. }
  8814. }
  8815. return null;
  8816. };
  8817. Scene.prototype.getSoundByName = function (name) {
  8818. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8819. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8820. return this.mainSoundTrack.soundCollection[index];
  8821. }
  8822. }
  8823. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8824. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8825. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8826. return this.soundTracks[sdIndex].soundCollection[index];
  8827. }
  8828. }
  8829. }
  8830. return null;
  8831. };
  8832. Scene.prototype.getLastSkeletonByID = function (id) {
  8833. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8834. if (this.skeletons[index].id === id) {
  8835. return this.skeletons[index];
  8836. }
  8837. }
  8838. return null;
  8839. };
  8840. Scene.prototype.getSkeletonById = function (id) {
  8841. for (var index = 0; index < this.skeletons.length; index++) {
  8842. if (this.skeletons[index].id === id) {
  8843. return this.skeletons[index];
  8844. }
  8845. }
  8846. return null;
  8847. };
  8848. Scene.prototype.getSkeletonByName = function (name) {
  8849. for (var index = 0; index < this.skeletons.length; index++) {
  8850. if (this.skeletons[index].name === name) {
  8851. return this.skeletons[index];
  8852. }
  8853. }
  8854. return null;
  8855. };
  8856. Scene.prototype.isActiveMesh = function (mesh) {
  8857. return (this._activeMeshes.indexOf(mesh) !== -1);
  8858. };
  8859. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8860. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8861. var material = subMesh.getMaterial();
  8862. if (mesh.showSubMeshesBoundingBox) {
  8863. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8864. }
  8865. if (material) {
  8866. // Render targets
  8867. if (material.getRenderTargetTextures) {
  8868. if (this._processedMaterials.indexOf(material) === -1) {
  8869. this._processedMaterials.push(material);
  8870. this._renderTargets.concat(material.getRenderTargetTextures());
  8871. }
  8872. }
  8873. // Dispatch
  8874. this._activeVertices += subMesh.indexCount;
  8875. this._renderingManager.dispatch(subMesh);
  8876. }
  8877. }
  8878. };
  8879. Scene.prototype._evaluateActiveMeshes = function () {
  8880. this.activeCamera._activeMeshes.reset();
  8881. this._activeMeshes.reset();
  8882. this._renderingManager.reset();
  8883. this._processedMaterials.reset();
  8884. this._activeParticleSystems.reset();
  8885. this._activeSkeletons.reset();
  8886. this._boundingBoxRenderer.reset();
  8887. if (!this._frustumPlanes) {
  8888. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8889. }
  8890. else {
  8891. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8892. }
  8893. // Meshes
  8894. var meshes;
  8895. var len;
  8896. if (this._selectionOctree) {
  8897. var selection = this._selectionOctree.select(this._frustumPlanes);
  8898. meshes = selection.data;
  8899. len = selection.length;
  8900. }
  8901. else {
  8902. len = this.meshes.length;
  8903. meshes = this.meshes;
  8904. }
  8905. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8906. var mesh = meshes[meshIndex];
  8907. if (mesh.isBlocked) {
  8908. continue;
  8909. }
  8910. this._totalVertices += mesh.getTotalVertices();
  8911. if (!mesh.isReady()) {
  8912. continue;
  8913. }
  8914. mesh.computeWorldMatrix();
  8915. // Intersections
  8916. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8917. this._meshesForIntersections.pushNoDuplicate(mesh);
  8918. }
  8919. // Switch to current LOD
  8920. var meshLOD = mesh.getLOD(this.activeCamera);
  8921. if (!meshLOD) {
  8922. continue;
  8923. }
  8924. mesh._preActivate();
  8925. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8926. this._activeMeshes.push(mesh);
  8927. this.activeCamera._activeMeshes.push(mesh);
  8928. mesh._activate(this._renderId);
  8929. this._activeMesh(meshLOD);
  8930. }
  8931. }
  8932. // Particle systems
  8933. var beforeParticlesDate = BABYLON.Tools.Now;
  8934. if (this.particlesEnabled) {
  8935. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8936. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8937. var particleSystem = this.particleSystems[particleIndex];
  8938. if (!particleSystem.isStarted()) {
  8939. continue;
  8940. }
  8941. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8942. this._activeParticleSystems.push(particleSystem);
  8943. particleSystem.animate();
  8944. }
  8945. }
  8946. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8947. }
  8948. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8949. };
  8950. Scene.prototype._activeMesh = function (mesh) {
  8951. if (mesh.skeleton && this.skeletonsEnabled) {
  8952. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8953. }
  8954. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8955. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8956. }
  8957. if (mesh && mesh.subMeshes) {
  8958. // Submeshes Octrees
  8959. var len;
  8960. var subMeshes;
  8961. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8962. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8963. len = intersections.length;
  8964. subMeshes = intersections.data;
  8965. }
  8966. else {
  8967. subMeshes = mesh.subMeshes;
  8968. len = subMeshes.length;
  8969. }
  8970. for (var subIndex = 0; subIndex < len; subIndex++) {
  8971. var subMesh = subMeshes[subIndex];
  8972. this._evaluateSubMesh(subMesh, mesh);
  8973. }
  8974. }
  8975. };
  8976. Scene.prototype.updateTransformMatrix = function (force) {
  8977. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8978. };
  8979. Scene.prototype._renderForCamera = function (camera) {
  8980. var engine = this._engine;
  8981. this.activeCamera = camera;
  8982. if (!this.activeCamera)
  8983. throw new Error("Active camera not set");
  8984. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8985. // Viewport
  8986. engine.setViewport(this.activeCamera.viewport);
  8987. // Camera
  8988. this._renderId++;
  8989. this.updateTransformMatrix();
  8990. if (this.beforeCameraRender) {
  8991. this.beforeCameraRender(this.activeCamera);
  8992. }
  8993. // Meshes
  8994. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8995. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8996. this._evaluateActiveMeshes();
  8997. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8998. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8999. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  9000. var skeleton = this._activeSkeletons.data[skeletonIndex];
  9001. skeleton.prepare();
  9002. }
  9003. // Render targets
  9004. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9005. if (this.renderTargetsEnabled) {
  9006. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9007. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  9008. var renderTarget = this._renderTargets.data[renderIndex];
  9009. if (renderTarget._shouldRender()) {
  9010. this._renderId++;
  9011. renderTarget.render(false, this.dumpNextRenderTargets);
  9012. }
  9013. }
  9014. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  9015. this._renderId++;
  9016. }
  9017. if (this._renderTargets.length > 0) {
  9018. engine.restoreDefaultFramebuffer();
  9019. }
  9020. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9021. // Prepare Frame
  9022. this.postProcessManager._prepareFrame();
  9023. var beforeRenderDate = BABYLON.Tools.Now;
  9024. // Backgrounds
  9025. if (this.layers.length) {
  9026. engine.setDepthBuffer(false);
  9027. var layerIndex;
  9028. var layer;
  9029. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9030. layer = this.layers[layerIndex];
  9031. if (layer.isBackground) {
  9032. layer.render();
  9033. }
  9034. }
  9035. engine.setDepthBuffer(true);
  9036. }
  9037. // Render
  9038. BABYLON.Tools.StartPerformanceCounter("Main render");
  9039. this._renderingManager.render(null, null, true, true);
  9040. BABYLON.Tools.EndPerformanceCounter("Main render");
  9041. // Bounding boxes
  9042. this._boundingBoxRenderer.render();
  9043. // Lens flares
  9044. if (this.lensFlaresEnabled) {
  9045. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9046. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  9047. this.lensFlareSystems[lensFlareSystemIndex].render();
  9048. }
  9049. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  9050. }
  9051. // Foregrounds
  9052. if (this.layers.length) {
  9053. engine.setDepthBuffer(false);
  9054. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  9055. layer = this.layers[layerIndex];
  9056. if (!layer.isBackground) {
  9057. layer.render();
  9058. }
  9059. }
  9060. engine.setDepthBuffer(true);
  9061. }
  9062. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  9063. // Finalize frame
  9064. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  9065. // Update camera
  9066. this.activeCamera._updateFromScene();
  9067. // Reset some special arrays
  9068. this._renderTargets.reset();
  9069. if (this.afterCameraRender) {
  9070. this.afterCameraRender(this.activeCamera);
  9071. }
  9072. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  9073. };
  9074. Scene.prototype._processSubCameras = function (camera) {
  9075. if (camera.subCameras.length === 0) {
  9076. this._renderForCamera(camera);
  9077. return;
  9078. }
  9079. for (var index = 0; index < camera.subCameras.length; index++) {
  9080. this._renderForCamera(camera.subCameras[index]);
  9081. }
  9082. this.activeCamera = camera;
  9083. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  9084. // Update camera
  9085. this.activeCamera._updateFromScene();
  9086. };
  9087. Scene.prototype._checkIntersections = function () {
  9088. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  9089. var sourceMesh = this._meshesForIntersections.data[index];
  9090. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  9091. var action = sourceMesh.actionManager.actions[actionIndex];
  9092. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9093. var parameters = action.getTriggerParameter();
  9094. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  9095. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  9096. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9097. if (areIntersecting && currentIntersectionInProgress === -1) {
  9098. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  9099. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9100. sourceMesh._intersectionsInProgress.push(otherMesh);
  9101. }
  9102. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9103. sourceMesh._intersectionsInProgress.push(otherMesh);
  9104. }
  9105. }
  9106. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  9107. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  9108. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  9109. if (indexOfOther > -1) {
  9110. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  9111. }
  9112. }
  9113. }
  9114. }
  9115. }
  9116. };
  9117. Scene.prototype.render = function () {
  9118. var startDate = BABYLON.Tools.Now;
  9119. this._particlesDuration = 0;
  9120. this._spritesDuration = 0;
  9121. this._activeParticles = 0;
  9122. this._renderDuration = 0;
  9123. this._renderTargetsDuration = 0;
  9124. this._evaluateActiveMeshesDuration = 0;
  9125. this._totalVertices = 0;
  9126. this._activeVertices = 0;
  9127. this._activeBones = 0;
  9128. this.getEngine().resetDrawCalls();
  9129. this._meshesForIntersections.reset();
  9130. this.resetCachedMaterial();
  9131. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  9132. // Actions
  9133. if (this.actionManager) {
  9134. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  9135. }
  9136. //Simplification Queue
  9137. if (!this.simplificationQueue.running) {
  9138. this.simplificationQueue.executeNext();
  9139. }
  9140. // Before render
  9141. if (this.beforeRender) {
  9142. this.beforeRender();
  9143. }
  9144. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  9145. this._onBeforeRenderCallbacks[callbackIndex]();
  9146. }
  9147. // Animations
  9148. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  9149. this._animationRatio = deltaTime * (60.0 / 1000.0);
  9150. this._animate();
  9151. // Physics
  9152. if (this._physicsEngine) {
  9153. BABYLON.Tools.StartPerformanceCounter("Physics");
  9154. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  9155. BABYLON.Tools.EndPerformanceCounter("Physics");
  9156. }
  9157. // Customs render targets
  9158. var beforeRenderTargetDate = BABYLON.Tools.Now;
  9159. var engine = this.getEngine();
  9160. var currentActiveCamera = this.activeCamera;
  9161. if (this.renderTargetsEnabled) {
  9162. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9163. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  9164. var renderTarget = this.customRenderTargets[customIndex];
  9165. if (renderTarget._shouldRender()) {
  9166. this._renderId++;
  9167. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  9168. if (!this.activeCamera)
  9169. throw new Error("Active camera not set");
  9170. // Viewport
  9171. engine.setViewport(this.activeCamera.viewport);
  9172. // Camera
  9173. this.updateTransformMatrix();
  9174. renderTarget.render(false, this.dumpNextRenderTargets);
  9175. }
  9176. }
  9177. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  9178. this._renderId++;
  9179. }
  9180. if (this.customRenderTargets.length > 0) {
  9181. engine.restoreDefaultFramebuffer();
  9182. }
  9183. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  9184. this.activeCamera = currentActiveCamera;
  9185. // Procedural textures
  9186. if (this.proceduralTexturesEnabled) {
  9187. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9188. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  9189. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  9190. if (proceduralTexture._shouldRender()) {
  9191. proceduralTexture.render();
  9192. }
  9193. }
  9194. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  9195. }
  9196. // Clear
  9197. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  9198. // Shadows
  9199. if (this.shadowsEnabled) {
  9200. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  9201. var light = this.lights[lightIndex];
  9202. var shadowGenerator = light.getShadowGenerator();
  9203. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  9204. this._renderTargets.push(shadowGenerator.getShadowMap());
  9205. }
  9206. }
  9207. }
  9208. // Depth renderer
  9209. if (this._depthRenderer) {
  9210. this._renderTargets.push(this._depthRenderer.getDepthMap());
  9211. }
  9212. // RenderPipeline
  9213. this.postProcessRenderPipelineManager.update();
  9214. // Multi-cameras?
  9215. if (this.activeCameras.length > 0) {
  9216. var currentRenderId = this._renderId;
  9217. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  9218. this._renderId = currentRenderId;
  9219. this._processSubCameras(this.activeCameras[cameraIndex]);
  9220. }
  9221. }
  9222. else {
  9223. if (!this.activeCamera) {
  9224. throw new Error("No camera defined");
  9225. }
  9226. this._processSubCameras(this.activeCamera);
  9227. }
  9228. // Intersection checks
  9229. this._checkIntersections();
  9230. // Update the audio listener attached to the camera
  9231. this._updateAudioParameters();
  9232. // After render
  9233. if (this.afterRender) {
  9234. this.afterRender();
  9235. }
  9236. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  9237. this._onAfterRenderCallbacks[callbackIndex]();
  9238. }
  9239. for (var index = 0; index < this._toBeDisposed.length; index++) {
  9240. this._toBeDisposed.data[index].dispose();
  9241. this._toBeDisposed[index] = null;
  9242. }
  9243. this._toBeDisposed.reset();
  9244. if (this.dumpNextRenderTargets) {
  9245. this.dumpNextRenderTargets = false;
  9246. }
  9247. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  9248. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  9249. };
  9250. Scene.prototype._updateAudioParameters = function () {
  9251. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  9252. return;
  9253. }
  9254. var listeningCamera;
  9255. var audioEngine = BABYLON.Engine.audioEngine;
  9256. if (this.activeCameras.length > 0) {
  9257. listeningCamera = this.activeCameras[0];
  9258. }
  9259. else {
  9260. listeningCamera = this.activeCamera;
  9261. }
  9262. if (listeningCamera && audioEngine.canUseWebAudio) {
  9263. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  9264. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  9265. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  9266. cameraDirection.normalize();
  9267. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  9268. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9269. var sound = this.mainSoundTrack.soundCollection[i];
  9270. if (sound.useCustomAttenuation) {
  9271. sound.updateDistanceFromListener();
  9272. }
  9273. }
  9274. for (i = 0; i < this.soundTracks.length; i++) {
  9275. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9276. sound = this.soundTracks[i].soundCollection[j];
  9277. if (sound.useCustomAttenuation) {
  9278. sound.updateDistanceFromListener();
  9279. }
  9280. }
  9281. }
  9282. }
  9283. };
  9284. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9285. // Audio
  9286. get: function () {
  9287. return this._audioEnabled;
  9288. },
  9289. set: function (value) {
  9290. this._audioEnabled = value;
  9291. if (this._audioEnabled) {
  9292. this._enableAudio();
  9293. }
  9294. else {
  9295. this._disableAudio();
  9296. }
  9297. },
  9298. enumerable: true,
  9299. configurable: true
  9300. });
  9301. Scene.prototype._disableAudio = function () {
  9302. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9303. this.mainSoundTrack.soundCollection[i].pause();
  9304. }
  9305. for (i = 0; i < this.soundTracks.length; i++) {
  9306. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9307. this.soundTracks[i].soundCollection[j].pause();
  9308. }
  9309. }
  9310. };
  9311. Scene.prototype._enableAudio = function () {
  9312. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9313. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9314. this.mainSoundTrack.soundCollection[i].play();
  9315. }
  9316. }
  9317. for (i = 0; i < this.soundTracks.length; i++) {
  9318. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9319. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9320. this.soundTracks[i].soundCollection[j].play();
  9321. }
  9322. }
  9323. }
  9324. };
  9325. Object.defineProperty(Scene.prototype, "headphone", {
  9326. get: function () {
  9327. return this._headphone;
  9328. },
  9329. set: function (value) {
  9330. this._headphone = value;
  9331. if (this._headphone) {
  9332. this._switchAudioModeForHeadphones();
  9333. }
  9334. else {
  9335. this._switchAudioModeForNormalSpeakers();
  9336. }
  9337. },
  9338. enumerable: true,
  9339. configurable: true
  9340. });
  9341. Scene.prototype._switchAudioModeForHeadphones = function () {
  9342. this.mainSoundTrack.switchPanningModelToHRTF();
  9343. for (var i = 0; i < this.soundTracks.length; i++) {
  9344. this.soundTracks[i].switchPanningModelToHRTF();
  9345. }
  9346. };
  9347. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9348. this.mainSoundTrack.switchPanningModelToEqualPower();
  9349. for (var i = 0; i < this.soundTracks.length; i++) {
  9350. this.soundTracks[i].switchPanningModelToEqualPower();
  9351. }
  9352. };
  9353. Scene.prototype.enableDepthRenderer = function () {
  9354. if (this._depthRenderer) {
  9355. return this._depthRenderer;
  9356. }
  9357. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9358. return this._depthRenderer;
  9359. };
  9360. Scene.prototype.disableDepthRenderer = function () {
  9361. if (!this._depthRenderer) {
  9362. return;
  9363. }
  9364. this._depthRenderer.dispose();
  9365. this._depthRenderer = null;
  9366. };
  9367. Scene.prototype.dispose = function () {
  9368. this.beforeRender = null;
  9369. this.afterRender = null;
  9370. this.skeletons = [];
  9371. this._boundingBoxRenderer.dispose();
  9372. if (this._depthRenderer) {
  9373. this._depthRenderer.dispose();
  9374. }
  9375. // Debug layer
  9376. this.debugLayer.hide();
  9377. // Events
  9378. if (this.onDispose) {
  9379. this.onDispose();
  9380. }
  9381. this._onBeforeRenderCallbacks = [];
  9382. this._onAfterRenderCallbacks = [];
  9383. this.detachControl();
  9384. // Release sounds & sounds tracks
  9385. this.disposeSounds();
  9386. // Detach cameras
  9387. var canvas = this._engine.getRenderingCanvas();
  9388. var index;
  9389. for (index = 0; index < this.cameras.length; index++) {
  9390. this.cameras[index].detachControl(canvas);
  9391. }
  9392. while (this.lights.length) {
  9393. this.lights[0].dispose();
  9394. }
  9395. while (this.meshes.length) {
  9396. this.meshes[0].dispose(true);
  9397. }
  9398. while (this.cameras.length) {
  9399. this.cameras[0].dispose();
  9400. }
  9401. while (this.materials.length) {
  9402. this.materials[0].dispose();
  9403. }
  9404. while (this.particleSystems.length) {
  9405. this.particleSystems[0].dispose();
  9406. }
  9407. while (this.spriteManagers.length) {
  9408. this.spriteManagers[0].dispose();
  9409. }
  9410. while (this.layers.length) {
  9411. this.layers[0].dispose();
  9412. }
  9413. while (this.textures.length) {
  9414. this.textures[0].dispose();
  9415. }
  9416. // Post-processes
  9417. this.postProcessManager.dispose();
  9418. // Physics
  9419. if (this._physicsEngine) {
  9420. this.disablePhysicsEngine();
  9421. }
  9422. // Remove from engine
  9423. index = this._engine.scenes.indexOf(this);
  9424. if (index > -1) {
  9425. this._engine.scenes.splice(index, 1);
  9426. }
  9427. this._engine.wipeCaches();
  9428. };
  9429. // Release sounds & sounds tracks
  9430. Scene.prototype.disposeSounds = function () {
  9431. this.mainSoundTrack.dispose();
  9432. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9433. this.soundTracks[scIndex].dispose();
  9434. }
  9435. };
  9436. // Collisions
  9437. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9438. if (excludedMesh === void 0) { excludedMesh = null; }
  9439. position.divideToRef(collider.radius, this._scaledPosition);
  9440. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9441. collider.retry = 0;
  9442. collider.initialVelocity = this._scaledVelocity;
  9443. collider.initialPosition = this._scaledPosition;
  9444. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9445. finalPosition.multiplyInPlace(collider.radius);
  9446. };
  9447. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9448. if (excludedMesh === void 0) { excludedMesh = null; }
  9449. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9450. if (collider.retry >= maximumRetry) {
  9451. finalPosition.copyFrom(position);
  9452. return;
  9453. }
  9454. collider._initialize(position, velocity, closeDistance);
  9455. for (var index = 0; index < this.meshes.length; index++) {
  9456. var mesh = this.meshes[index];
  9457. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9458. mesh._checkCollision(collider);
  9459. }
  9460. }
  9461. if (!collider.collisionFound) {
  9462. position.addToRef(velocity, finalPosition);
  9463. return;
  9464. }
  9465. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9466. collider._getResponse(position, velocity);
  9467. }
  9468. if (velocity.length() <= closeDistance) {
  9469. finalPosition.copyFrom(position);
  9470. return;
  9471. }
  9472. collider.retry++;
  9473. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9474. };
  9475. // Octrees
  9476. Scene.prototype.getWorldExtends = function () {
  9477. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9478. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9479. for (var index = 0; index < this.meshes.length; index++) {
  9480. var mesh = this.meshes[index];
  9481. mesh.computeWorldMatrix(true);
  9482. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9483. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9484. BABYLON.Tools.CheckExtends(minBox, min, max);
  9485. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9486. }
  9487. return {
  9488. min: min,
  9489. max: max
  9490. };
  9491. };
  9492. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9493. if (maxCapacity === void 0) { maxCapacity = 64; }
  9494. if (maxDepth === void 0) { maxDepth = 2; }
  9495. if (!this._selectionOctree) {
  9496. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9497. }
  9498. var worldExtends = this.getWorldExtends();
  9499. // Update octree
  9500. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9501. return this._selectionOctree;
  9502. };
  9503. // Picking
  9504. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9505. var engine = this._engine;
  9506. if (!camera) {
  9507. if (!this.activeCamera)
  9508. throw new Error("Active camera not set");
  9509. camera = this.activeCamera;
  9510. }
  9511. var cameraViewport = camera.viewport;
  9512. var viewport = cameraViewport.toGlobal(engine);
  9513. // Moving coordinates to local viewport world
  9514. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9515. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9516. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9517. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9518. };
  9519. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9520. var pickingInfo = null;
  9521. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9522. var mesh = this.meshes[meshIndex];
  9523. if (predicate) {
  9524. if (!predicate(mesh)) {
  9525. continue;
  9526. }
  9527. }
  9528. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9529. continue;
  9530. }
  9531. var world = mesh.getWorldMatrix();
  9532. var ray = rayFunction(world);
  9533. var result = mesh.intersects(ray, fastCheck);
  9534. if (!result || !result.hit)
  9535. continue;
  9536. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9537. continue;
  9538. pickingInfo = result;
  9539. if (fastCheck) {
  9540. break;
  9541. }
  9542. }
  9543. return pickingInfo || new BABYLON.PickingInfo();
  9544. };
  9545. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9546. var _this = this;
  9547. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9548. /// <param name="x">X position on screen</param>
  9549. /// <param name="y">Y position on screen</param>
  9550. /// <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>
  9551. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9552. /// <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>
  9553. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9554. };
  9555. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9556. var _this = this;
  9557. return this._internalPick(function (world) {
  9558. if (!_this._pickWithRayInverseMatrix) {
  9559. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9560. }
  9561. world.invertToRef(_this._pickWithRayInverseMatrix);
  9562. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9563. }, predicate, fastCheck);
  9564. };
  9565. Scene.prototype.setPointerOverMesh = function (mesh) {
  9566. if (this._pointerOverMesh === mesh) {
  9567. return;
  9568. }
  9569. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9570. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9571. }
  9572. this._pointerOverMesh = mesh;
  9573. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9574. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9575. }
  9576. };
  9577. Scene.prototype.getPointerOverMesh = function () {
  9578. return this._pointerOverMesh;
  9579. };
  9580. // Physics
  9581. Scene.prototype.getPhysicsEngine = function () {
  9582. return this._physicsEngine;
  9583. };
  9584. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9585. if (this._physicsEngine) {
  9586. return true;
  9587. }
  9588. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9589. if (!this._physicsEngine.isSupported()) {
  9590. this._physicsEngine = null;
  9591. return false;
  9592. }
  9593. this._physicsEngine._initialize(gravity);
  9594. return true;
  9595. };
  9596. Scene.prototype.disablePhysicsEngine = function () {
  9597. if (!this._physicsEngine) {
  9598. return;
  9599. }
  9600. this._physicsEngine.dispose();
  9601. this._physicsEngine = undefined;
  9602. };
  9603. Scene.prototype.isPhysicsEnabled = function () {
  9604. return this._physicsEngine !== undefined;
  9605. };
  9606. Scene.prototype.setGravity = function (gravity) {
  9607. if (!this._physicsEngine) {
  9608. return;
  9609. }
  9610. this._physicsEngine._setGravity(gravity);
  9611. };
  9612. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9613. if (parts.parts) {
  9614. options = parts;
  9615. parts = parts.parts;
  9616. }
  9617. if (!this._physicsEngine) {
  9618. return null;
  9619. }
  9620. for (var index = 0; index < parts.length; index++) {
  9621. var mesh = parts[index].mesh;
  9622. mesh._physicImpostor = parts[index].impostor;
  9623. mesh._physicsMass = options.mass / parts.length;
  9624. mesh._physicsFriction = options.friction;
  9625. mesh._physicRestitution = options.restitution;
  9626. }
  9627. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9628. };
  9629. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9630. for (var index = 0; index < compound.parts.length; index++) {
  9631. var mesh = compound.parts[index].mesh;
  9632. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9633. this._physicsEngine._unregisterMesh(mesh);
  9634. }
  9635. };
  9636. // Misc.
  9637. Scene.prototype.createDefaultCameraOrLight = function () {
  9638. // Light
  9639. if (this.lights.length === 0) {
  9640. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9641. }
  9642. // Camera
  9643. if (!this.activeCamera) {
  9644. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9645. // Compute position
  9646. var worldExtends = this.getWorldExtends();
  9647. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9648. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9649. camera.setTarget(worldCenter);
  9650. this.activeCamera = camera;
  9651. }
  9652. };
  9653. // Tags
  9654. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9655. if (tagsQuery === undefined) {
  9656. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9657. return list;
  9658. }
  9659. var listByTags = [];
  9660. forEach = forEach || (function (item) {
  9661. return;
  9662. });
  9663. for (var i in list) {
  9664. var item = list[i];
  9665. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9666. listByTags.push(item);
  9667. forEach(item);
  9668. }
  9669. }
  9670. return listByTags;
  9671. };
  9672. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9673. return this._getByTags(this.meshes, tagsQuery, forEach);
  9674. };
  9675. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9676. return this._getByTags(this.cameras, tagsQuery, forEach);
  9677. };
  9678. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9679. return this._getByTags(this.lights, tagsQuery, forEach);
  9680. };
  9681. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9682. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9683. };
  9684. // Statics
  9685. Scene._FOGMODE_NONE = 0;
  9686. Scene._FOGMODE_EXP = 1;
  9687. Scene._FOGMODE_EXP2 = 2;
  9688. Scene._FOGMODE_LINEAR = 3;
  9689. Scene.MinDeltaTime = 1.0;
  9690. Scene.MaxDeltaTime = 1000.0;
  9691. return Scene;
  9692. })();
  9693. BABYLON.Scene = Scene;
  9694. })(BABYLON || (BABYLON = {}));
  9695. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9696. (function (BABYLON) {
  9697. var VertexBuffer = (function () {
  9698. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9699. if (engine instanceof BABYLON.Mesh) {
  9700. this._engine = engine.getScene().getEngine();
  9701. }
  9702. else {
  9703. this._engine = engine;
  9704. }
  9705. this._updatable = updatable;
  9706. this._data = data;
  9707. if (!postponeInternalCreation) {
  9708. this.create();
  9709. }
  9710. this._kind = kind;
  9711. if (stride) {
  9712. this._strideSize = stride;
  9713. return;
  9714. }
  9715. switch (kind) {
  9716. case VertexBuffer.PositionKind:
  9717. this._strideSize = 3;
  9718. break;
  9719. case VertexBuffer.NormalKind:
  9720. this._strideSize = 3;
  9721. break;
  9722. case VertexBuffer.UVKind:
  9723. this._strideSize = 2;
  9724. break;
  9725. case VertexBuffer.UV2Kind:
  9726. this._strideSize = 2;
  9727. break;
  9728. case VertexBuffer.ColorKind:
  9729. this._strideSize = 4;
  9730. break;
  9731. case VertexBuffer.MatricesIndicesKind:
  9732. this._strideSize = 4;
  9733. break;
  9734. case VertexBuffer.MatricesWeightsKind:
  9735. this._strideSize = 4;
  9736. break;
  9737. }
  9738. }
  9739. // Properties
  9740. VertexBuffer.prototype.isUpdatable = function () {
  9741. return this._updatable;
  9742. };
  9743. VertexBuffer.prototype.getData = function () {
  9744. return this._data;
  9745. };
  9746. VertexBuffer.prototype.getBuffer = function () {
  9747. return this._buffer;
  9748. };
  9749. VertexBuffer.prototype.getStrideSize = function () {
  9750. return this._strideSize;
  9751. };
  9752. // Methods
  9753. VertexBuffer.prototype.create = function (data) {
  9754. if (!data && this._buffer) {
  9755. return; // nothing to do
  9756. }
  9757. data = data || this._data;
  9758. if (!this._buffer) {
  9759. if (this._updatable) {
  9760. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9761. }
  9762. else {
  9763. this._buffer = this._engine.createVertexBuffer(data);
  9764. }
  9765. }
  9766. if (this._updatable) {
  9767. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9768. this._data = data;
  9769. }
  9770. };
  9771. VertexBuffer.prototype.update = function (data) {
  9772. this.create(data);
  9773. };
  9774. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9775. if (!this._buffer) {
  9776. return;
  9777. }
  9778. if (this._updatable) {
  9779. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9780. this._data = null;
  9781. }
  9782. };
  9783. VertexBuffer.prototype.dispose = function () {
  9784. if (!this._buffer) {
  9785. return;
  9786. }
  9787. if (this._engine._releaseBuffer(this._buffer)) {
  9788. this._buffer = null;
  9789. }
  9790. };
  9791. Object.defineProperty(VertexBuffer, "PositionKind", {
  9792. get: function () {
  9793. return VertexBuffer._PositionKind;
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. Object.defineProperty(VertexBuffer, "NormalKind", {
  9799. get: function () {
  9800. return VertexBuffer._NormalKind;
  9801. },
  9802. enumerable: true,
  9803. configurable: true
  9804. });
  9805. Object.defineProperty(VertexBuffer, "UVKind", {
  9806. get: function () {
  9807. return VertexBuffer._UVKind;
  9808. },
  9809. enumerable: true,
  9810. configurable: true
  9811. });
  9812. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9813. get: function () {
  9814. return VertexBuffer._UV2Kind;
  9815. },
  9816. enumerable: true,
  9817. configurable: true
  9818. });
  9819. Object.defineProperty(VertexBuffer, "ColorKind", {
  9820. get: function () {
  9821. return VertexBuffer._ColorKind;
  9822. },
  9823. enumerable: true,
  9824. configurable: true
  9825. });
  9826. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9827. get: function () {
  9828. return VertexBuffer._MatricesIndicesKind;
  9829. },
  9830. enumerable: true,
  9831. configurable: true
  9832. });
  9833. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9834. get: function () {
  9835. return VertexBuffer._MatricesWeightsKind;
  9836. },
  9837. enumerable: true,
  9838. configurable: true
  9839. });
  9840. // Enums
  9841. VertexBuffer._PositionKind = "position";
  9842. VertexBuffer._NormalKind = "normal";
  9843. VertexBuffer._UVKind = "uv";
  9844. VertexBuffer._UV2Kind = "uv2";
  9845. VertexBuffer._ColorKind = "color";
  9846. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9847. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9848. return VertexBuffer;
  9849. })();
  9850. BABYLON.VertexBuffer = VertexBuffer;
  9851. })(BABYLON || (BABYLON = {}));
  9852. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9853. var BABYLON;
  9854. (function (BABYLON) {
  9855. var AbstractMesh = (function (_super) {
  9856. __extends(AbstractMesh, _super);
  9857. function AbstractMesh(name, scene) {
  9858. _super.call(this, name, scene);
  9859. // Properties
  9860. this.definedFacingForward = true; // orientation for POV movement & rotation
  9861. this.position = new BABYLON.Vector3(0, 0, 0);
  9862. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9863. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9864. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9865. this.visibility = 1.0;
  9866. this.alphaIndex = Number.MAX_VALUE;
  9867. this.infiniteDistance = false;
  9868. this.isVisible = true;
  9869. this.isPickable = true;
  9870. this.showBoundingBox = false;
  9871. this.showSubMeshesBoundingBox = false;
  9872. this.onDispose = null;
  9873. this.checkCollisions = false;
  9874. this.isBlocker = false;
  9875. this.renderingGroupId = 0;
  9876. this.receiveShadows = false;
  9877. this.renderOutline = false;
  9878. this.outlineColor = BABYLON.Color3.Red();
  9879. this.outlineWidth = 0.02;
  9880. this.renderOverlay = false;
  9881. this.overlayColor = BABYLON.Color3.Red();
  9882. this.overlayAlpha = 0.5;
  9883. this.hasVertexAlpha = false;
  9884. this.useVertexColors = true;
  9885. this.applyFog = true;
  9886. this.useOctreeForRenderingSelection = true;
  9887. this.useOctreeForPicking = true;
  9888. this.useOctreeForCollisions = true;
  9889. this.layerMask = 0xFFFFFFFF;
  9890. // Physics
  9891. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9892. // Collisions
  9893. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9894. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9895. this._collider = new BABYLON.Collider();
  9896. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9897. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9898. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9899. // Cache
  9900. this._localScaling = BABYLON.Matrix.Zero();
  9901. this._localRotation = BABYLON.Matrix.Zero();
  9902. this._localTranslation = BABYLON.Matrix.Zero();
  9903. this._localBillboard = BABYLON.Matrix.Zero();
  9904. this._localPivotScaling = BABYLON.Matrix.Zero();
  9905. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9906. this._localWorld = BABYLON.Matrix.Zero();
  9907. this._worldMatrix = BABYLON.Matrix.Zero();
  9908. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9909. this._absolutePosition = BABYLON.Vector3.Zero();
  9910. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9911. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9912. this._isDirty = false;
  9913. this._pivotMatrix = BABYLON.Matrix.Identity();
  9914. this._isDisposed = false;
  9915. this._renderId = 0;
  9916. this._intersectionsInProgress = new Array();
  9917. this._onAfterWorldMatrixUpdate = new Array();
  9918. scene.addMesh(this);
  9919. }
  9920. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9921. get: function () {
  9922. return AbstractMesh._BILLBOARDMODE_NONE;
  9923. },
  9924. enumerable: true,
  9925. configurable: true
  9926. });
  9927. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9928. get: function () {
  9929. return AbstractMesh._BILLBOARDMODE_X;
  9930. },
  9931. enumerable: true,
  9932. configurable: true
  9933. });
  9934. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9935. get: function () {
  9936. return AbstractMesh._BILLBOARDMODE_Y;
  9937. },
  9938. enumerable: true,
  9939. configurable: true
  9940. });
  9941. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9942. get: function () {
  9943. return AbstractMesh._BILLBOARDMODE_Z;
  9944. },
  9945. enumerable: true,
  9946. configurable: true
  9947. });
  9948. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9949. get: function () {
  9950. return AbstractMesh._BILLBOARDMODE_ALL;
  9951. },
  9952. enumerable: true,
  9953. configurable: true
  9954. });
  9955. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9956. // Methods
  9957. get: function () {
  9958. return false;
  9959. },
  9960. enumerable: true,
  9961. configurable: true
  9962. });
  9963. AbstractMesh.prototype.getLOD = function (camera) {
  9964. return this;
  9965. };
  9966. AbstractMesh.prototype.getTotalVertices = function () {
  9967. return 0;
  9968. };
  9969. AbstractMesh.prototype.getIndices = function () {
  9970. return null;
  9971. };
  9972. AbstractMesh.prototype.getVerticesData = function (kind) {
  9973. return null;
  9974. };
  9975. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9976. return false;
  9977. };
  9978. AbstractMesh.prototype.getBoundingInfo = function () {
  9979. if (this._masterMesh) {
  9980. return this._masterMesh.getBoundingInfo();
  9981. }
  9982. if (!this._boundingInfo) {
  9983. this._updateBoundingInfo();
  9984. }
  9985. return this._boundingInfo;
  9986. };
  9987. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9988. get: function () {
  9989. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9990. },
  9991. enumerable: true,
  9992. configurable: true
  9993. });
  9994. AbstractMesh.prototype._preActivate = function () {
  9995. };
  9996. AbstractMesh.prototype._activate = function (renderId) {
  9997. this._renderId = renderId;
  9998. };
  9999. AbstractMesh.prototype.getWorldMatrix = function () {
  10000. if (this._masterMesh) {
  10001. return this._masterMesh.getWorldMatrix();
  10002. }
  10003. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10004. this.computeWorldMatrix();
  10005. }
  10006. return this._worldMatrix;
  10007. };
  10008. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10009. get: function () {
  10010. return this._worldMatrix;
  10011. },
  10012. enumerable: true,
  10013. configurable: true
  10014. });
  10015. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10016. get: function () {
  10017. return this._absolutePosition;
  10018. },
  10019. enumerable: true,
  10020. configurable: true
  10021. });
  10022. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10023. if (!this.rotationQuaternion) {
  10024. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10025. this.rotation = BABYLON.Vector3.Zero();
  10026. }
  10027. if (!space || space === 0 /* LOCAL */) {
  10028. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10029. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  10030. }
  10031. else {
  10032. if (this.parent) {
  10033. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10034. invertParentWorldMatrix.invert();
  10035. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10036. }
  10037. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  10038. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  10039. }
  10040. };
  10041. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10042. var displacementVector = axis.scale(distance);
  10043. if (!space || space === 0 /* LOCAL */) {
  10044. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10045. this.setPositionWithLocalVector(tempV3);
  10046. }
  10047. else {
  10048. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10049. }
  10050. };
  10051. AbstractMesh.prototype.getAbsolutePosition = function () {
  10052. this.computeWorldMatrix();
  10053. return this._absolutePosition;
  10054. };
  10055. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10056. if (!absolutePosition) {
  10057. return;
  10058. }
  10059. var absolutePositionX;
  10060. var absolutePositionY;
  10061. var absolutePositionZ;
  10062. if (absolutePosition.x === undefined) {
  10063. if (arguments.length < 3) {
  10064. return;
  10065. }
  10066. absolutePositionX = arguments[0];
  10067. absolutePositionY = arguments[1];
  10068. absolutePositionZ = arguments[2];
  10069. }
  10070. else {
  10071. absolutePositionX = absolutePosition.x;
  10072. absolutePositionY = absolutePosition.y;
  10073. absolutePositionZ = absolutePosition.z;
  10074. }
  10075. if (this.parent) {
  10076. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10077. invertParentWorldMatrix.invert();
  10078. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10079. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10080. }
  10081. else {
  10082. this.position.x = absolutePositionX;
  10083. this.position.y = absolutePositionY;
  10084. this.position.z = absolutePositionZ;
  10085. }
  10086. };
  10087. // ================================== Point of View Movement =================================
  10088. /**
  10089. * Perform relative position change from the point of view of behind the front of the mesh.
  10090. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10091. * Supports definition of mesh facing forward or backward.
  10092. * @param {number} amountRight
  10093. * @param {number} amountUp
  10094. * @param {number} amountForward
  10095. */
  10096. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10097. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10098. };
  10099. /**
  10100. * Calculate relative position change from the point of view of behind the front of the mesh.
  10101. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10102. * Supports definition of mesh facing forward or backward.
  10103. * @param {number} amountRight
  10104. * @param {number} amountUp
  10105. * @param {number} amountForward
  10106. */
  10107. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10108. var rotMatrix = new BABYLON.Matrix();
  10109. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10110. rotQuaternion.toRotationMatrix(rotMatrix);
  10111. var translationDelta = BABYLON.Vector3.Zero();
  10112. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10113. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10114. return translationDelta;
  10115. };
  10116. // ================================== Point of View Rotation =================================
  10117. /**
  10118. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10119. * Supports definition of mesh facing forward or backward.
  10120. * @param {number} flipBack
  10121. * @param {number} twirlClockwise
  10122. * @param {number} tiltRight
  10123. */
  10124. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10125. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10126. };
  10127. /**
  10128. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10129. * Supports definition of mesh facing forward or backward.
  10130. * @param {number} flipBack
  10131. * @param {number} twirlClockwise
  10132. * @param {number} tiltRight
  10133. */
  10134. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10135. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10136. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10137. };
  10138. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10139. this._pivotMatrix = matrix;
  10140. this._cache.pivotMatrixUpdated = true;
  10141. };
  10142. AbstractMesh.prototype.getPivotMatrix = function () {
  10143. return this._pivotMatrix;
  10144. };
  10145. AbstractMesh.prototype._isSynchronized = function () {
  10146. if (this._isDirty) {
  10147. return false;
  10148. }
  10149. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10150. return false;
  10151. if (this._cache.pivotMatrixUpdated) {
  10152. return false;
  10153. }
  10154. if (this.infiniteDistance) {
  10155. return false;
  10156. }
  10157. if (!this._cache.position.equals(this.position))
  10158. return false;
  10159. if (this.rotationQuaternion) {
  10160. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10161. return false;
  10162. }
  10163. else {
  10164. if (!this._cache.rotation.equals(this.rotation))
  10165. return false;
  10166. }
  10167. if (!this._cache.scaling.equals(this.scaling))
  10168. return false;
  10169. return true;
  10170. };
  10171. AbstractMesh.prototype._initCache = function () {
  10172. _super.prototype._initCache.call(this);
  10173. this._cache.localMatrixUpdated = false;
  10174. this._cache.position = BABYLON.Vector3.Zero();
  10175. this._cache.scaling = BABYLON.Vector3.Zero();
  10176. this._cache.rotation = BABYLON.Vector3.Zero();
  10177. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10178. };
  10179. AbstractMesh.prototype.markAsDirty = function (property) {
  10180. if (property === "rotation") {
  10181. this.rotationQuaternion = null;
  10182. }
  10183. this._currentRenderId = Number.MAX_VALUE;
  10184. this._isDirty = true;
  10185. };
  10186. AbstractMesh.prototype._updateBoundingInfo = function () {
  10187. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10188. this._boundingInfo._update(this.worldMatrixFromCache);
  10189. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10190. };
  10191. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10192. if (!this.subMeshes) {
  10193. return;
  10194. }
  10195. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10196. var subMesh = this.subMeshes[subIndex];
  10197. subMesh.updateBoundingInfo(matrix);
  10198. }
  10199. };
  10200. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10201. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10202. return this._worldMatrix;
  10203. }
  10204. this._cache.position.copyFrom(this.position);
  10205. this._cache.scaling.copyFrom(this.scaling);
  10206. this._cache.pivotMatrixUpdated = false;
  10207. this._currentRenderId = this.getScene().getRenderId();
  10208. this._isDirty = false;
  10209. // Scaling
  10210. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  10211. // Rotation
  10212. if (this.rotationQuaternion) {
  10213. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  10214. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10215. }
  10216. else {
  10217. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  10218. this._cache.rotation.copyFrom(this.rotation);
  10219. }
  10220. // Translation
  10221. if (this.infiniteDistance && !this.parent) {
  10222. var camera = this.getScene().activeCamera;
  10223. var cameraWorldMatrix = camera.getWorldMatrix();
  10224. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10225. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  10226. }
  10227. else {
  10228. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  10229. }
  10230. // Composing transformations
  10231. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  10232. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  10233. // Billboarding
  10234. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10235. var localPosition = this.position.clone();
  10236. var zero = this.getScene().activeCamera.position.clone();
  10237. if (this.parent && this.parent.position) {
  10238. localPosition.addInPlace(this.parent.position);
  10239. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  10240. }
  10241. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  10242. zero = this.getScene().activeCamera.position;
  10243. }
  10244. else {
  10245. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10246. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  10247. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10248. zero.y = localPosition.y + 0.001;
  10249. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10250. zero.z = localPosition.z + 0.001;
  10251. }
  10252. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  10253. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  10254. this._localBillboard.invert();
  10255. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  10256. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  10257. }
  10258. // Local world
  10259. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  10260. // Parent
  10261. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10262. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10263. }
  10264. else {
  10265. this._worldMatrix.copyFrom(this._localWorld);
  10266. }
  10267. // Bounding info
  10268. this._updateBoundingInfo();
  10269. // Absolute position
  10270. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10271. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10272. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10273. }
  10274. return this._worldMatrix;
  10275. };
  10276. /**
  10277. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10278. * @param func: callback function to add
  10279. */
  10280. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10281. this._onAfterWorldMatrixUpdate.push(func);
  10282. };
  10283. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10284. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10285. if (index > -1) {
  10286. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10287. }
  10288. };
  10289. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10290. this.computeWorldMatrix();
  10291. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10292. };
  10293. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10294. this.computeWorldMatrix();
  10295. var invLocalWorldMatrix = this._localWorld.clone();
  10296. invLocalWorldMatrix.invert();
  10297. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10298. };
  10299. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10300. this.computeWorldMatrix();
  10301. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10302. };
  10303. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10304. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10305. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10306. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10307. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10308. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10309. /// <returns>Mesh oriented towards targetMesh</returns>
  10310. yawCor = yawCor || 0; // default to zero if undefined
  10311. pitchCor = pitchCor || 0;
  10312. rollCor = rollCor || 0;
  10313. var dv = targetPoint.subtract(this.position);
  10314. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10315. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10316. var pitch = Math.atan2(dv.y, len);
  10317. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10318. };
  10319. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10320. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10321. return false;
  10322. }
  10323. return true;
  10324. };
  10325. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10326. if (!camera) {
  10327. camera = this.getScene().activeCamera;
  10328. }
  10329. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10330. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10331. return false;
  10332. }
  10333. return true;
  10334. };
  10335. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10336. if (!this._boundingInfo || !mesh._boundingInfo) {
  10337. return false;
  10338. }
  10339. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10340. };
  10341. AbstractMesh.prototype.intersectsPoint = function (point) {
  10342. if (!this._boundingInfo) {
  10343. return false;
  10344. }
  10345. return this._boundingInfo.intersectsPoint(point);
  10346. };
  10347. // Physics
  10348. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10349. var physicsEngine = this.getScene().getPhysicsEngine();
  10350. if (!physicsEngine) {
  10351. return;
  10352. }
  10353. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10354. if (impostor.impostor) {
  10355. // Old API
  10356. options = impostor;
  10357. impostor = impostor.impostor;
  10358. }
  10359. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10360. physicsEngine._unregisterMesh(this);
  10361. return;
  10362. }
  10363. if (!options) {
  10364. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10365. }
  10366. else {
  10367. if (!options.mass && options.mass !== 0)
  10368. options.mass = 0;
  10369. if (!options.friction && options.friction !== 0)
  10370. options.friction = 0.2;
  10371. if (!options.restitution && options.restitution !== 0)
  10372. options.restitution = 0.2;
  10373. }
  10374. this._physicImpostor = impostor;
  10375. this._physicsMass = options.mass;
  10376. this._physicsFriction = options.friction;
  10377. this._physicRestitution = options.restitution;
  10378. return physicsEngine._registerMesh(this, impostor, options);
  10379. };
  10380. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10381. if (!this._physicImpostor) {
  10382. return BABYLON.PhysicsEngine.NoImpostor;
  10383. }
  10384. return this._physicImpostor;
  10385. };
  10386. AbstractMesh.prototype.getPhysicsMass = function () {
  10387. if (!this._physicsMass) {
  10388. return 0;
  10389. }
  10390. return this._physicsMass;
  10391. };
  10392. AbstractMesh.prototype.getPhysicsFriction = function () {
  10393. if (!this._physicsFriction) {
  10394. return 0;
  10395. }
  10396. return this._physicsFriction;
  10397. };
  10398. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10399. if (!this._physicRestitution) {
  10400. return 0;
  10401. }
  10402. return this._physicRestitution;
  10403. };
  10404. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10405. if (!camera) {
  10406. camera = this.getScene().activeCamera;
  10407. }
  10408. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10409. };
  10410. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10411. if (!camera) {
  10412. camera = this.getScene().activeCamera;
  10413. }
  10414. return this.absolutePosition.subtract(camera.position).length();
  10415. };
  10416. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10417. if (!this._physicImpostor) {
  10418. return;
  10419. }
  10420. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10421. };
  10422. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10423. if (!this._physicImpostor) {
  10424. return;
  10425. }
  10426. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10427. };
  10428. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10429. if (!this._physicImpostor) {
  10430. return;
  10431. }
  10432. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10433. };
  10434. // Collisions
  10435. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10436. var globalPosition = this.getAbsolutePosition();
  10437. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10438. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10439. this._collider.radius = this.ellipsoid;
  10440. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10441. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10442. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10443. this.position.addInPlace(this._diffPositionForCollisions);
  10444. }
  10445. };
  10446. // Submeshes octree
  10447. /**
  10448. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10449. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10450. */
  10451. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10452. if (maxCapacity === void 0) { maxCapacity = 64; }
  10453. if (maxDepth === void 0) { maxDepth = 2; }
  10454. if (!this._submeshesOctree) {
  10455. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10456. }
  10457. this.computeWorldMatrix(true);
  10458. // Update octree
  10459. var bbox = this.getBoundingInfo().boundingBox;
  10460. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10461. return this._submeshesOctree;
  10462. };
  10463. // Collisions
  10464. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10465. this._generatePointsArray();
  10466. // Transformation
  10467. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10468. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10469. subMesh._lastColliderWorldVertices = [];
  10470. subMesh._trianglePlanes = [];
  10471. var start = subMesh.verticesStart;
  10472. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10473. for (var i = start; i < end; i++) {
  10474. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10475. }
  10476. }
  10477. // Collide
  10478. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10479. };
  10480. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10481. var subMeshes;
  10482. var len;
  10483. // Octrees
  10484. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10485. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10486. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10487. len = intersections.length;
  10488. subMeshes = intersections.data;
  10489. }
  10490. else {
  10491. subMeshes = this.subMeshes;
  10492. len = subMeshes.length;
  10493. }
  10494. for (var index = 0; index < len; index++) {
  10495. var subMesh = subMeshes[index];
  10496. // Bounding test
  10497. if (len > 1 && !subMesh._checkCollision(collider))
  10498. continue;
  10499. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10500. }
  10501. };
  10502. AbstractMesh.prototype._checkCollision = function (collider) {
  10503. // Bounding box test
  10504. if (!this._boundingInfo._checkCollision(collider))
  10505. return;
  10506. // Transformation matrix
  10507. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10508. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10509. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10510. };
  10511. // Picking
  10512. AbstractMesh.prototype._generatePointsArray = function () {
  10513. return false;
  10514. };
  10515. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10516. var pickingInfo = new BABYLON.PickingInfo();
  10517. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10518. return pickingInfo;
  10519. }
  10520. if (!this._generatePointsArray()) {
  10521. return pickingInfo;
  10522. }
  10523. var intersectInfo = null;
  10524. // Octrees
  10525. var subMeshes;
  10526. var len;
  10527. if (this._submeshesOctree && this.useOctreeForPicking) {
  10528. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10529. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10530. len = intersections.length;
  10531. subMeshes = intersections.data;
  10532. }
  10533. else {
  10534. subMeshes = this.subMeshes;
  10535. len = subMeshes.length;
  10536. }
  10537. for (var index = 0; index < len; index++) {
  10538. var subMesh = subMeshes[index];
  10539. // Bounding test
  10540. if (len > 1 && !subMesh.canIntersects(ray))
  10541. continue;
  10542. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10543. if (currentIntersectInfo) {
  10544. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10545. intersectInfo = currentIntersectInfo;
  10546. intersectInfo.subMeshId = index;
  10547. if (fastCheck) {
  10548. break;
  10549. }
  10550. }
  10551. }
  10552. }
  10553. if (intersectInfo) {
  10554. // Get picked point
  10555. var world = this.getWorldMatrix();
  10556. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10557. var direction = ray.direction.clone();
  10558. direction = direction.scale(intersectInfo.distance);
  10559. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10560. var pickedPoint = worldOrigin.add(worldDirection);
  10561. // Return result
  10562. pickingInfo.hit = true;
  10563. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10564. pickingInfo.pickedPoint = pickedPoint;
  10565. pickingInfo.pickedMesh = this;
  10566. pickingInfo.bu = intersectInfo.bu;
  10567. pickingInfo.bv = intersectInfo.bv;
  10568. pickingInfo.faceId = intersectInfo.faceId;
  10569. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10570. return pickingInfo;
  10571. }
  10572. return pickingInfo;
  10573. };
  10574. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10575. return null;
  10576. };
  10577. AbstractMesh.prototype.releaseSubMeshes = function () {
  10578. if (this.subMeshes) {
  10579. while (this.subMeshes.length) {
  10580. this.subMeshes[0].dispose();
  10581. }
  10582. }
  10583. else {
  10584. this.subMeshes = new Array();
  10585. }
  10586. };
  10587. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10588. var index;
  10589. // Physics
  10590. if (this.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  10591. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10592. }
  10593. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10594. var other = this._intersectionsInProgress[index];
  10595. var pos = other._intersectionsInProgress.indexOf(this);
  10596. other._intersectionsInProgress.splice(pos, 1);
  10597. }
  10598. this._intersectionsInProgress = [];
  10599. // SubMeshes
  10600. this.releaseSubMeshes();
  10601. // Remove from scene
  10602. this.getScene().removeMesh(this);
  10603. if (!doNotRecurse) {
  10604. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10605. if (this.getScene().particleSystems[index].emitter === this) {
  10606. this.getScene().particleSystems[index].dispose();
  10607. index--;
  10608. }
  10609. }
  10610. // Children
  10611. var objects = this.getScene().meshes.slice(0);
  10612. for (index = 0; index < objects.length; index++) {
  10613. if (objects[index].parent === this) {
  10614. objects[index].dispose();
  10615. }
  10616. }
  10617. }
  10618. else {
  10619. for (index = 0; index < this.getScene().meshes.length; index++) {
  10620. var obj = this.getScene().meshes[index];
  10621. if (obj.parent === this) {
  10622. obj.parent = null;
  10623. obj.computeWorldMatrix(true);
  10624. }
  10625. }
  10626. }
  10627. this._onAfterWorldMatrixUpdate = [];
  10628. this._isDisposed = true;
  10629. // Callback
  10630. if (this.onDispose) {
  10631. this.onDispose();
  10632. }
  10633. };
  10634. // Statics
  10635. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10636. AbstractMesh._BILLBOARDMODE_X = 1;
  10637. AbstractMesh._BILLBOARDMODE_Y = 2;
  10638. AbstractMesh._BILLBOARDMODE_Z = 4;
  10639. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10640. return AbstractMesh;
  10641. })(BABYLON.Node);
  10642. BABYLON.AbstractMesh = AbstractMesh;
  10643. })(BABYLON || (BABYLON = {}));
  10644. //# sourceMappingURL=babylon.abstractMesh.js.map
  10645. var BABYLON;
  10646. (function (BABYLON) {
  10647. var _InstancesBatch = (function () {
  10648. function _InstancesBatch() {
  10649. this.mustReturn = false;
  10650. this.visibleInstances = new Array();
  10651. this.renderSelf = new Array();
  10652. }
  10653. return _InstancesBatch;
  10654. })();
  10655. BABYLON._InstancesBatch = _InstancesBatch;
  10656. var Mesh = (function (_super) {
  10657. __extends(Mesh, _super);
  10658. /**
  10659. * @constructor
  10660. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10661. * @param {Scene} scene - The scene to add this mesh to.
  10662. * @param {Node} parent - The parent of this mesh, if it has one
  10663. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10664. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10665. * When false, achieved by calling a clone(), also passing False.
  10666. * This will make creation of children, recursive.
  10667. */
  10668. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10669. if (parent === void 0) { parent = null; }
  10670. _super.call(this, name, scene);
  10671. // Members
  10672. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10673. this.instances = new Array();
  10674. this._LODLevels = new Array();
  10675. this._onBeforeRenderCallbacks = new Array();
  10676. this._onAfterRenderCallbacks = new Array();
  10677. this._visibleInstances = {};
  10678. this._renderIdForInstances = new Array();
  10679. this._batchCache = new _InstancesBatch();
  10680. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10681. if (source) {
  10682. // Geometry
  10683. if (source._geometry) {
  10684. source._geometry.applyToMesh(this);
  10685. }
  10686. // Deep copy
  10687. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10688. // Material
  10689. this.material = source.material;
  10690. if (!doNotCloneChildren) {
  10691. for (var index = 0; index < scene.meshes.length; index++) {
  10692. var mesh = scene.meshes[index];
  10693. if (mesh.parent === source) {
  10694. // doNotCloneChildren is always going to be False
  10695. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10696. }
  10697. }
  10698. }
  10699. for (index = 0; index < scene.particleSystems.length; index++) {
  10700. var system = scene.particleSystems[index];
  10701. if (system.emitter === source) {
  10702. system.clone(system.name, this);
  10703. }
  10704. }
  10705. this.computeWorldMatrix(true);
  10706. }
  10707. // Parent
  10708. if (parent !== null) {
  10709. this.parent = parent;
  10710. }
  10711. }
  10712. Object.defineProperty(Mesh, "FRONTSIDE", {
  10713. get: function () {
  10714. return Mesh._FRONTSIDE;
  10715. },
  10716. enumerable: true,
  10717. configurable: true
  10718. });
  10719. Object.defineProperty(Mesh, "BACKSIDE", {
  10720. get: function () {
  10721. return Mesh._BACKSIDE;
  10722. },
  10723. enumerable: true,
  10724. configurable: true
  10725. });
  10726. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10727. get: function () {
  10728. return Mesh._DOUBLESIDE;
  10729. },
  10730. enumerable: true,
  10731. configurable: true
  10732. });
  10733. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10734. get: function () {
  10735. return Mesh._DEFAULTSIDE;
  10736. },
  10737. enumerable: true,
  10738. configurable: true
  10739. });
  10740. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10741. // Methods
  10742. get: function () {
  10743. return this._LODLevels.length > 0;
  10744. },
  10745. enumerable: true,
  10746. configurable: true
  10747. });
  10748. Mesh.prototype._sortLODLevels = function () {
  10749. this._LODLevels.sort(function (a, b) {
  10750. if (a.distance < b.distance) {
  10751. return 1;
  10752. }
  10753. if (a.distance > b.distance) {
  10754. return -1;
  10755. }
  10756. return 0;
  10757. });
  10758. };
  10759. /**
  10760. * Add a mesh as LOD level triggered at the given distance.
  10761. * @param {number} distance - the distance from the center of the object to show this level
  10762. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10763. * @return {BABYLON.Mesh} this mesh (for chaining)
  10764. */
  10765. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10766. if (mesh && mesh._masterMesh) {
  10767. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10768. return this;
  10769. }
  10770. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10771. this._LODLevels.push(level);
  10772. if (mesh) {
  10773. mesh._masterMesh = this;
  10774. }
  10775. this._sortLODLevels();
  10776. return this;
  10777. };
  10778. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10779. for (var index = 0; index < this._LODLevels.length; index++) {
  10780. var level = this._LODLevels[index];
  10781. if (level.distance === distance) {
  10782. return level.mesh;
  10783. }
  10784. }
  10785. return null;
  10786. };
  10787. /**
  10788. * Remove a mesh from the LOD array
  10789. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10790. * @return {BABYLON.Mesh} this mesh (for chaining)
  10791. */
  10792. Mesh.prototype.removeLODLevel = function (mesh) {
  10793. for (var index = 0; index < this._LODLevels.length; index++) {
  10794. if (this._LODLevels[index].mesh === mesh) {
  10795. this._LODLevels.splice(index, 1);
  10796. if (mesh) {
  10797. mesh._masterMesh = null;
  10798. }
  10799. }
  10800. }
  10801. this._sortLODLevels();
  10802. return this;
  10803. };
  10804. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10805. if (!this._LODLevels || this._LODLevels.length === 0) {
  10806. return this;
  10807. }
  10808. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10809. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10810. return this;
  10811. }
  10812. for (var index = 0; index < this._LODLevels.length; index++) {
  10813. var level = this._LODLevels[index];
  10814. if (level.distance < distanceToCamera) {
  10815. if (level.mesh) {
  10816. level.mesh._preActivate();
  10817. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10818. }
  10819. return level.mesh;
  10820. }
  10821. }
  10822. return this;
  10823. };
  10824. Object.defineProperty(Mesh.prototype, "geometry", {
  10825. get: function () {
  10826. return this._geometry;
  10827. },
  10828. enumerable: true,
  10829. configurable: true
  10830. });
  10831. Mesh.prototype.getTotalVertices = function () {
  10832. if (!this._geometry) {
  10833. return 0;
  10834. }
  10835. return this._geometry.getTotalVertices();
  10836. };
  10837. Mesh.prototype.getVerticesData = function (kind) {
  10838. if (!this._geometry) {
  10839. return null;
  10840. }
  10841. return this._geometry.getVerticesData(kind);
  10842. };
  10843. Mesh.prototype.getVertexBuffer = function (kind) {
  10844. if (!this._geometry) {
  10845. return undefined;
  10846. }
  10847. return this._geometry.getVertexBuffer(kind);
  10848. };
  10849. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10850. if (!this._geometry) {
  10851. if (this._delayInfo) {
  10852. return this._delayInfo.indexOf(kind) !== -1;
  10853. }
  10854. return false;
  10855. }
  10856. return this._geometry.isVerticesDataPresent(kind);
  10857. };
  10858. Mesh.prototype.getVerticesDataKinds = function () {
  10859. if (!this._geometry) {
  10860. var result = [];
  10861. if (this._delayInfo) {
  10862. for (var kind in this._delayInfo) {
  10863. result.push(kind);
  10864. }
  10865. }
  10866. return result;
  10867. }
  10868. return this._geometry.getVerticesDataKinds();
  10869. };
  10870. Mesh.prototype.getTotalIndices = function () {
  10871. if (!this._geometry) {
  10872. return 0;
  10873. }
  10874. return this._geometry.getTotalIndices();
  10875. };
  10876. Mesh.prototype.getIndices = function () {
  10877. if (!this._geometry) {
  10878. return [];
  10879. }
  10880. return this._geometry.getIndices();
  10881. };
  10882. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10883. get: function () {
  10884. return this._masterMesh !== null && this._masterMesh !== undefined;
  10885. },
  10886. enumerable: true,
  10887. configurable: true
  10888. });
  10889. Mesh.prototype.isReady = function () {
  10890. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10891. return false;
  10892. }
  10893. return _super.prototype.isReady.call(this);
  10894. };
  10895. Mesh.prototype.isDisposed = function () {
  10896. return this._isDisposed;
  10897. };
  10898. // Methods
  10899. Mesh.prototype._preActivate = function () {
  10900. var sceneRenderId = this.getScene().getRenderId();
  10901. if (this._preActivateId === sceneRenderId) {
  10902. return;
  10903. }
  10904. this._preActivateId = sceneRenderId;
  10905. this._visibleInstances = null;
  10906. };
  10907. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10908. if (!this._visibleInstances) {
  10909. this._visibleInstances = {};
  10910. this._visibleInstances.defaultRenderId = renderId;
  10911. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10912. }
  10913. if (!this._visibleInstances[renderId]) {
  10914. this._visibleInstances[renderId] = new Array();
  10915. }
  10916. this._visibleInstances[renderId].push(instance);
  10917. };
  10918. Mesh.prototype.refreshBoundingInfo = function () {
  10919. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10920. if (data) {
  10921. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10922. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10923. }
  10924. if (this.subMeshes) {
  10925. for (var index = 0; index < this.subMeshes.length; index++) {
  10926. this.subMeshes[index].refreshBoundingInfo();
  10927. }
  10928. }
  10929. this._updateBoundingInfo();
  10930. };
  10931. Mesh.prototype._createGlobalSubMesh = function () {
  10932. var totalVertices = this.getTotalVertices();
  10933. if (!totalVertices || !this.getIndices()) {
  10934. return null;
  10935. }
  10936. this.releaseSubMeshes();
  10937. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10938. };
  10939. Mesh.prototype.subdivide = function (count) {
  10940. if (count < 1) {
  10941. return;
  10942. }
  10943. var totalIndices = this.getTotalIndices();
  10944. var subdivisionSize = (totalIndices / count) | 0;
  10945. var offset = 0;
  10946. while (subdivisionSize % 3 !== 0) {
  10947. subdivisionSize++;
  10948. }
  10949. this.releaseSubMeshes();
  10950. for (var index = 0; index < count; index++) {
  10951. if (offset >= totalIndices) {
  10952. break;
  10953. }
  10954. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10955. offset += subdivisionSize;
  10956. }
  10957. this.synchronizeInstances();
  10958. };
  10959. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10960. if (kind instanceof Array) {
  10961. var temp = data;
  10962. data = kind;
  10963. kind = temp;
  10964. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10965. }
  10966. if (!this._geometry) {
  10967. var vertexData = new BABYLON.VertexData();
  10968. vertexData.set(data, kind);
  10969. var scene = this.getScene();
  10970. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10971. }
  10972. else {
  10973. this._geometry.setVerticesData(kind, data, updatable, stride);
  10974. }
  10975. };
  10976. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10977. if (!this._geometry) {
  10978. return;
  10979. }
  10980. if (!makeItUnique) {
  10981. this._geometry.updateVerticesData(kind, data, updateExtends);
  10982. }
  10983. else {
  10984. this.makeGeometryUnique();
  10985. this.updateVerticesData(kind, data, updateExtends, false);
  10986. }
  10987. };
  10988. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10989. if (!this._geometry) {
  10990. return;
  10991. }
  10992. if (!makeItUnique) {
  10993. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10994. }
  10995. else {
  10996. this.makeGeometryUnique();
  10997. this.updateVerticesDataDirectly(kind, data, offset, false);
  10998. }
  10999. };
  11000. Mesh.prototype.makeGeometryUnique = function () {
  11001. if (!this._geometry) {
  11002. return;
  11003. }
  11004. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  11005. geometry.applyToMesh(this);
  11006. };
  11007. Mesh.prototype.setIndices = function (indices, totalVertices) {
  11008. if (!this._geometry) {
  11009. var vertexData = new BABYLON.VertexData();
  11010. vertexData.indices = indices;
  11011. var scene = this.getScene();
  11012. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  11013. }
  11014. else {
  11015. this._geometry.setIndices(indices, totalVertices);
  11016. }
  11017. };
  11018. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  11019. var engine = this.getScene().getEngine();
  11020. // Wireframe
  11021. var indexToBind;
  11022. switch (fillMode) {
  11023. case BABYLON.Material.PointFillMode:
  11024. indexToBind = null;
  11025. break;
  11026. case BABYLON.Material.WireFrameFillMode:
  11027. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  11028. break;
  11029. default:
  11030. case BABYLON.Material.TriangleFillMode:
  11031. indexToBind = this._geometry.getIndexBuffer();
  11032. break;
  11033. }
  11034. // VBOs
  11035. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  11036. };
  11037. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  11038. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11039. return;
  11040. }
  11041. var engine = this.getScene().getEngine();
  11042. switch (fillMode) {
  11043. case BABYLON.Material.PointFillMode:
  11044. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  11045. break;
  11046. case BABYLON.Material.WireFrameFillMode:
  11047. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  11048. break;
  11049. default:
  11050. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  11051. }
  11052. };
  11053. Mesh.prototype.registerBeforeRender = function (func) {
  11054. this._onBeforeRenderCallbacks.push(func);
  11055. };
  11056. Mesh.prototype.unregisterBeforeRender = function (func) {
  11057. var index = this._onBeforeRenderCallbacks.indexOf(func);
  11058. if (index > -1) {
  11059. this._onBeforeRenderCallbacks.splice(index, 1);
  11060. }
  11061. };
  11062. Mesh.prototype.registerAfterRender = function (func) {
  11063. this._onAfterRenderCallbacks.push(func);
  11064. };
  11065. Mesh.prototype.unregisterAfterRender = function (func) {
  11066. var index = this._onAfterRenderCallbacks.indexOf(func);
  11067. if (index > -1) {
  11068. this._onAfterRenderCallbacks.splice(index, 1);
  11069. }
  11070. };
  11071. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  11072. var scene = this.getScene();
  11073. this._batchCache.mustReturn = false;
  11074. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  11075. this._batchCache.visibleInstances[subMeshId] = null;
  11076. if (this._visibleInstances) {
  11077. var currentRenderId = scene.getRenderId();
  11078. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  11079. var selfRenderId = this._renderId;
  11080. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  11081. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  11082. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  11083. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  11084. }
  11085. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  11086. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  11087. this._batchCache.mustReturn = true;
  11088. return this._batchCache;
  11089. }
  11090. if (currentRenderId !== selfRenderId) {
  11091. this._batchCache.renderSelf[subMeshId] = false;
  11092. }
  11093. }
  11094. this._renderIdForInstances[subMeshId] = currentRenderId;
  11095. }
  11096. return this._batchCache;
  11097. };
  11098. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  11099. var visibleInstances = batch.visibleInstances[subMesh._id];
  11100. var matricesCount = visibleInstances.length + 1;
  11101. var bufferSize = matricesCount * 16 * 4;
  11102. while (this._instancesBufferSize < bufferSize) {
  11103. this._instancesBufferSize *= 2;
  11104. }
  11105. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  11106. if (this._worldMatricesInstancesBuffer) {
  11107. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11108. }
  11109. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  11110. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  11111. }
  11112. var offset = 0;
  11113. var instancesCount = 0;
  11114. var world = this.getWorldMatrix();
  11115. if (batch.renderSelf[subMesh._id]) {
  11116. world.copyToArray(this._worldMatricesInstancesArray, offset);
  11117. offset += 16;
  11118. instancesCount++;
  11119. }
  11120. if (visibleInstances) {
  11121. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  11122. var instance = visibleInstances[instanceIndex];
  11123. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  11124. offset += 16;
  11125. instancesCount++;
  11126. }
  11127. }
  11128. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  11129. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  11130. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  11131. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  11132. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  11133. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  11134. this._draw(subMesh, fillMode, instancesCount);
  11135. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  11136. };
  11137. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  11138. var scene = this.getScene();
  11139. var engine = scene.getEngine();
  11140. if (hardwareInstancedRendering) {
  11141. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  11142. }
  11143. else {
  11144. if (batch.renderSelf[subMesh._id]) {
  11145. // Draw
  11146. if (onBeforeDraw) {
  11147. onBeforeDraw(false, this.getWorldMatrix());
  11148. }
  11149. this._draw(subMesh, fillMode);
  11150. }
  11151. if (batch.visibleInstances[subMesh._id]) {
  11152. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  11153. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  11154. // World
  11155. var world = instance.getWorldMatrix();
  11156. if (onBeforeDraw) {
  11157. onBeforeDraw(true, world);
  11158. }
  11159. // Draw
  11160. this._draw(subMesh, fillMode);
  11161. }
  11162. }
  11163. }
  11164. };
  11165. Mesh.prototype.render = function (subMesh) {
  11166. var scene = this.getScene();
  11167. // Managing instances
  11168. var batch = this._getInstancesRenderList(subMesh._id);
  11169. if (batch.mustReturn) {
  11170. return;
  11171. }
  11172. // Checking geometry state
  11173. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  11174. return;
  11175. }
  11176. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  11177. this._onBeforeRenderCallbacks[callbackIndex](this);
  11178. }
  11179. var engine = scene.getEngine();
  11180. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11181. // Material
  11182. var effectiveMaterial = subMesh.getMaterial();
  11183. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  11184. return;
  11185. }
  11186. // Outline - step 1
  11187. var savedDepthWrite = engine.getDepthWrite();
  11188. if (this.renderOutline) {
  11189. engine.setDepthWrite(false);
  11190. scene.getOutlineRenderer().render(subMesh, batch);
  11191. engine.setDepthWrite(savedDepthWrite);
  11192. }
  11193. effectiveMaterial._preBind();
  11194. var effect = effectiveMaterial.getEffect();
  11195. // Bind
  11196. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  11197. this._bind(subMesh, effect, fillMode);
  11198. var world = this.getWorldMatrix();
  11199. effectiveMaterial.bind(world, this);
  11200. // Draw
  11201. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  11202. if (isInstance) {
  11203. effectiveMaterial.bindOnlyWorldMatrix(world);
  11204. }
  11205. });
  11206. // Unbind
  11207. effectiveMaterial.unbind();
  11208. // Outline - step 2
  11209. if (this.renderOutline && savedDepthWrite) {
  11210. engine.setDepthWrite(true);
  11211. engine.setColorWrite(false);
  11212. scene.getOutlineRenderer().render(subMesh, batch);
  11213. engine.setColorWrite(true);
  11214. }
  11215. // Overlay
  11216. if (this.renderOverlay) {
  11217. var currentMode = engine.getAlphaMode();
  11218. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11219. scene.getOutlineRenderer().render(subMesh, batch, true);
  11220. engine.setAlphaMode(currentMode);
  11221. }
  11222. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  11223. this._onAfterRenderCallbacks[callbackIndex](this);
  11224. }
  11225. };
  11226. Mesh.prototype.getEmittedParticleSystems = function () {
  11227. var results = new Array();
  11228. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11229. var particleSystem = this.getScene().particleSystems[index];
  11230. if (particleSystem.emitter === this) {
  11231. results.push(particleSystem);
  11232. }
  11233. }
  11234. return results;
  11235. };
  11236. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  11237. var results = new Array();
  11238. var descendants = this.getDescendants();
  11239. descendants.push(this);
  11240. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  11241. var particleSystem = this.getScene().particleSystems[index];
  11242. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  11243. results.push(particleSystem);
  11244. }
  11245. }
  11246. return results;
  11247. };
  11248. Mesh.prototype.getChildren = function () {
  11249. var results = [];
  11250. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11251. var mesh = this.getScene().meshes[index];
  11252. if (mesh.parent === this) {
  11253. results.push(mesh);
  11254. }
  11255. }
  11256. return results;
  11257. };
  11258. Mesh.prototype._checkDelayState = function () {
  11259. var _this = this;
  11260. var that = this;
  11261. var scene = this.getScene();
  11262. if (this._geometry) {
  11263. this._geometry.load(scene);
  11264. }
  11265. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11266. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  11267. scene._addPendingData(that);
  11268. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11269. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11270. if (data instanceof ArrayBuffer) {
  11271. _this._delayLoadingFunction(data, _this);
  11272. }
  11273. else {
  11274. _this._delayLoadingFunction(JSON.parse(data), _this);
  11275. }
  11276. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11277. scene._removePendingData(_this);
  11278. }, function () {
  11279. }, scene.database, getBinaryData);
  11280. }
  11281. };
  11282. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11283. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11284. return false;
  11285. }
  11286. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11287. return false;
  11288. }
  11289. this._checkDelayState();
  11290. return true;
  11291. };
  11292. Mesh.prototype.setMaterialByID = function (id) {
  11293. var materials = this.getScene().materials;
  11294. for (var index = 0; index < materials.length; index++) {
  11295. if (materials[index].id === id) {
  11296. this.material = materials[index];
  11297. return;
  11298. }
  11299. }
  11300. // Multi
  11301. var multiMaterials = this.getScene().multiMaterials;
  11302. for (index = 0; index < multiMaterials.length; index++) {
  11303. if (multiMaterials[index].id === id) {
  11304. this.material = multiMaterials[index];
  11305. return;
  11306. }
  11307. }
  11308. };
  11309. Mesh.prototype.getAnimatables = function () {
  11310. var results = [];
  11311. if (this.material) {
  11312. results.push(this.material);
  11313. }
  11314. if (this.skeleton) {
  11315. results.push(this.skeleton);
  11316. }
  11317. return results;
  11318. };
  11319. // Geometry
  11320. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11321. // Position
  11322. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11323. return;
  11324. }
  11325. this._resetPointsArrayCache();
  11326. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11327. var temp = [];
  11328. for (var index = 0; index < data.length; index += 3) {
  11329. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11330. }
  11331. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11332. // Normals
  11333. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11334. return;
  11335. }
  11336. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11337. for (index = 0; index < data.length; index += 3) {
  11338. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11339. }
  11340. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11341. };
  11342. // Cache
  11343. Mesh.prototype._resetPointsArrayCache = function () {
  11344. this._positions = null;
  11345. };
  11346. Mesh.prototype._generatePointsArray = function () {
  11347. if (this._positions)
  11348. return true;
  11349. this._positions = [];
  11350. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11351. if (!data) {
  11352. return false;
  11353. }
  11354. for (var index = 0; index < data.length; index += 3) {
  11355. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11356. }
  11357. return true;
  11358. };
  11359. // Clone
  11360. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11361. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11362. };
  11363. // Dispose
  11364. Mesh.prototype.dispose = function (doNotRecurse) {
  11365. if (this._geometry) {
  11366. this._geometry.releaseForMesh(this, true);
  11367. }
  11368. // Instances
  11369. if (this._worldMatricesInstancesBuffer) {
  11370. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11371. this._worldMatricesInstancesBuffer = null;
  11372. }
  11373. while (this.instances.length) {
  11374. this.instances[0].dispose();
  11375. }
  11376. _super.prototype.dispose.call(this, doNotRecurse);
  11377. };
  11378. // Geometric tools
  11379. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11380. var _this = this;
  11381. var scene = this.getScene();
  11382. var onload = function (img) {
  11383. // Getting height map data
  11384. var canvas = document.createElement("canvas");
  11385. var context = canvas.getContext("2d");
  11386. var heightMapWidth = img.width;
  11387. var heightMapHeight = img.height;
  11388. canvas.width = heightMapWidth;
  11389. canvas.height = heightMapHeight;
  11390. context.drawImage(img, 0, 0);
  11391. // Create VertexData from map data
  11392. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11393. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11394. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11395. //execute success callback, if set
  11396. if (onSuccess) {
  11397. onSuccess(_this);
  11398. }
  11399. };
  11400. BABYLON.Tools.LoadImage(url, onload, function () {
  11401. }, scene.database);
  11402. };
  11403. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11404. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11405. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11406. return;
  11407. }
  11408. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11409. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11410. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11411. var position = BABYLON.Vector3.Zero();
  11412. var normal = BABYLON.Vector3.Zero();
  11413. var uv = BABYLON.Vector2.Zero();
  11414. for (var index = 0; index < positions.length; index += 3) {
  11415. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11416. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11417. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11418. // Compute height
  11419. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11420. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11421. var pos = (u + v * heightMapWidth) * 4;
  11422. var r = buffer[pos] / 255.0;
  11423. var g = buffer[pos + 1] / 255.0;
  11424. var b = buffer[pos + 2] / 255.0;
  11425. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11426. normal.normalize();
  11427. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11428. position = position.add(normal);
  11429. position.toArray(positions, index);
  11430. }
  11431. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11432. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11433. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11434. };
  11435. Mesh.prototype.convertToFlatShadedMesh = function () {
  11436. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11437. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11438. var kinds = this.getVerticesDataKinds();
  11439. var vbs = [];
  11440. var data = [];
  11441. var newdata = [];
  11442. var updatableNormals = false;
  11443. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11444. var kind = kinds[kindIndex];
  11445. var vertexBuffer = this.getVertexBuffer(kind);
  11446. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11447. updatableNormals = vertexBuffer.isUpdatable();
  11448. kinds.splice(kindIndex, 1);
  11449. kindIndex--;
  11450. continue;
  11451. }
  11452. vbs[kind] = vertexBuffer;
  11453. data[kind] = vbs[kind].getData();
  11454. newdata[kind] = [];
  11455. }
  11456. // Save previous submeshes
  11457. var previousSubmeshes = this.subMeshes.slice(0);
  11458. var indices = this.getIndices();
  11459. var totalIndices = this.getTotalIndices();
  11460. for (var index = 0; index < totalIndices; index++) {
  11461. var vertexIndex = indices[index];
  11462. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11463. kind = kinds[kindIndex];
  11464. var stride = vbs[kind].getStrideSize();
  11465. for (var offset = 0; offset < stride; offset++) {
  11466. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11467. }
  11468. }
  11469. }
  11470. // Updating faces & normal
  11471. var normals = [];
  11472. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11473. for (index = 0; index < totalIndices; index += 3) {
  11474. indices[index] = index;
  11475. indices[index + 1] = index + 1;
  11476. indices[index + 2] = index + 2;
  11477. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11478. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11479. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11480. var p1p2 = p1.subtract(p2);
  11481. var p3p2 = p3.subtract(p2);
  11482. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11483. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11484. normals.push(normal.x);
  11485. normals.push(normal.y);
  11486. normals.push(normal.z);
  11487. }
  11488. }
  11489. this.setIndices(indices);
  11490. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11491. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11492. kind = kinds[kindIndex];
  11493. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11494. }
  11495. // Updating submeshes
  11496. this.releaseSubMeshes();
  11497. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11498. var previousOne = previousSubmeshes[submeshIndex];
  11499. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11500. }
  11501. this.synchronizeInstances();
  11502. };
  11503. // Instances
  11504. Mesh.prototype.createInstance = function (name) {
  11505. return new BABYLON.InstancedMesh(name, this);
  11506. };
  11507. Mesh.prototype.synchronizeInstances = function () {
  11508. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11509. var instance = this.instances[instanceIndex];
  11510. instance._syncSubMeshes();
  11511. }
  11512. };
  11513. /**
  11514. * Simplify the mesh according to the given array of settings.
  11515. * Function will return immediately and will simplify async.
  11516. * @param settings a collection of simplification settings.
  11517. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11518. * @param type the type of simplification to run.
  11519. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  11520. */
  11521. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11522. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11523. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11524. this.getScene().simplificationQueue.addTask({
  11525. settings: settings,
  11526. parallelProcessing: parallelProcessing,
  11527. mesh: this,
  11528. simplificationType: simplificationType,
  11529. successCallback: successCallback
  11530. });
  11531. };
  11532. /**
  11533. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  11534. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  11535. * This should be used together with the simplification to avoid disappearing triangles.
  11536. * @param successCallback an optional success callback to be called after the optimization finished.
  11537. */
  11538. Mesh.prototype.optimizeIndices = function (successCallback) {
  11539. var _this = this;
  11540. var indices = this.getIndices();
  11541. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11542. var vectorPositions = [];
  11543. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  11544. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  11545. }
  11546. var dupes = [];
  11547. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  11548. var realPos = vectorPositions.length - 1 - iteration;
  11549. var testedPosition = vectorPositions[realPos];
  11550. for (var j = 0; j < realPos; ++j) {
  11551. var againstPosition = vectorPositions[j];
  11552. if (testedPosition.equals(againstPosition)) {
  11553. dupes[realPos] = j;
  11554. break;
  11555. }
  11556. }
  11557. }, function () {
  11558. for (var i = 0; i < indices.length; ++i) {
  11559. indices[i] = dupes[indices[i]] || indices[i];
  11560. }
  11561. //indices are now reordered
  11562. var originalSubMeshes = _this.subMeshes.slice(0);
  11563. _this.setIndices(indices);
  11564. _this.subMeshes = originalSubMeshes;
  11565. if (successCallback) {
  11566. successCallback(_this);
  11567. }
  11568. });
  11569. };
  11570. // Statics
  11571. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11572. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11573. var ribbon = new Mesh(name, scene);
  11574. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11575. vertexData.applyToMesh(ribbon, updatable);
  11576. return ribbon;
  11577. };
  11578. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11579. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11580. var box = new Mesh(name, scene);
  11581. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11582. vertexData.applyToMesh(box, updatable);
  11583. return box;
  11584. };
  11585. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11586. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11587. var sphere = new Mesh(name, scene);
  11588. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11589. vertexData.applyToMesh(sphere, updatable);
  11590. return sphere;
  11591. };
  11592. // Cylinder and cone (Code inspired by SharpDX.org)
  11593. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11594. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11595. // subdivisions is a new parameter, we need to support old signature
  11596. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11597. if (scene !== undefined) {
  11598. updatable = scene;
  11599. }
  11600. scene = subdivisions;
  11601. subdivisions = 1;
  11602. }
  11603. var cylinder = new Mesh(name, scene);
  11604. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11605. vertexData.applyToMesh(cylinder, updatable);
  11606. return cylinder;
  11607. };
  11608. // Torus (Code from SharpDX.org)
  11609. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11610. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11611. var torus = new Mesh(name, scene);
  11612. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11613. vertexData.applyToMesh(torus, updatable);
  11614. return torus;
  11615. };
  11616. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11617. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11618. var torusKnot = new Mesh(name, scene);
  11619. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11620. vertexData.applyToMesh(torusKnot, updatable);
  11621. return torusKnot;
  11622. };
  11623. // Lines
  11624. Mesh.CreateLines = function (name, points, scene, updatable) {
  11625. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11626. var vertexData = BABYLON.VertexData.CreateLines(points);
  11627. vertexData.applyToMesh(lines, updatable);
  11628. return lines;
  11629. };
  11630. // Extrusion
  11631. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11632. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11633. scale = scale || 1;
  11634. rotation = rotation || 0;
  11635. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11636. return extruded;
  11637. };
  11638. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11639. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11640. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11641. return extrudedCustom;
  11642. };
  11643. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11644. var path3D = new BABYLON.Path3D(curve);
  11645. var tangents = path3D.getTangents();
  11646. var normals = path3D.getNormals();
  11647. var binormals = path3D.getBinormals();
  11648. var distances = path3D.getDistances();
  11649. var shapePaths = new Array();
  11650. var angle = 0;
  11651. var returnScale = function (i, distance) {
  11652. return scale;
  11653. };
  11654. var returnRotation = function (i, distance) {
  11655. return rotation;
  11656. };
  11657. var rotate = custom ? rotateFunction : returnRotation;
  11658. var scl = custom ? scaleFunction : returnScale;
  11659. for (var i = 0; i < curve.length; i++) {
  11660. var shapePath = new Array();
  11661. var angleStep = rotate(i, distances[i]);
  11662. var scaleRatio = scl(i, distances[i]);
  11663. for (var p = 0; p < shape.length; p++) {
  11664. var rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], angle);
  11665. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  11666. var rotated = BABYLON.Vector3.TransformCoordinates(planed, rotationMatrix).scaleInPlace(scaleRatio).add(curve[i]);
  11667. shapePath.push(rotated);
  11668. }
  11669. shapePaths.push(shapePath);
  11670. angle += angleStep;
  11671. }
  11672. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11673. return extrudedGeneric;
  11674. };
  11675. // Plane & ground
  11676. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11677. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11678. var plane = new Mesh(name, scene);
  11679. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11680. vertexData.applyToMesh(plane, updatable);
  11681. return plane;
  11682. };
  11683. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11684. var ground = new BABYLON.GroundMesh(name, scene);
  11685. ground._setReady(false);
  11686. ground._subdivisions = subdivisions;
  11687. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11688. vertexData.applyToMesh(ground, updatable);
  11689. ground._setReady(true);
  11690. return ground;
  11691. };
  11692. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11693. var tiledGround = new Mesh(name, scene);
  11694. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11695. vertexData.applyToMesh(tiledGround, updatable);
  11696. return tiledGround;
  11697. };
  11698. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11699. var ground = new BABYLON.GroundMesh(name, scene);
  11700. ground._subdivisions = subdivisions;
  11701. ground._setReady(false);
  11702. var onload = function (img) {
  11703. // Getting height map data
  11704. var canvas = document.createElement("canvas");
  11705. var context = canvas.getContext("2d");
  11706. var heightMapWidth = img.width;
  11707. var heightMapHeight = img.height;
  11708. canvas.width = heightMapWidth;
  11709. canvas.height = heightMapHeight;
  11710. context.drawImage(img, 0, 0);
  11711. // Create VertexData from map data
  11712. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11713. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11714. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11715. vertexData.applyToMesh(ground, updatable);
  11716. ground._setReady(true);
  11717. //execute ready callback, if set
  11718. if (onReady) {
  11719. onReady(ground);
  11720. }
  11721. };
  11722. BABYLON.Tools.LoadImage(url, onload, function () {
  11723. }, scene.database);
  11724. return ground;
  11725. };
  11726. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11727. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11728. var path3D = new BABYLON.Path3D(path);
  11729. var tangents = path3D.getTangents();
  11730. var normals = path3D.getNormals();
  11731. var distances = path3D.getDistances();
  11732. var pi2 = Math.PI * 2;
  11733. var step = pi2 / tesselation;
  11734. var returnRadius = function (i, distance) { return radius; };
  11735. var radiusFunctionFinal = radiusFunction || returnRadius;
  11736. var circlePaths = new Array();
  11737. var circlePath;
  11738. var rad;
  11739. var normal;
  11740. var rotated;
  11741. var rotationMatrix;
  11742. for (var i = 0; i < path.length; i++) {
  11743. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11744. circlePath = Array(); // current circle array
  11745. normal = normals[i]; // current normal
  11746. for (var ang = 0; ang < pi2; ang += step) {
  11747. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11748. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11749. circlePath.push(rotated);
  11750. }
  11751. circlePaths.push(circlePath);
  11752. }
  11753. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11754. return tube;
  11755. };
  11756. // Tools
  11757. Mesh.MinMax = function (meshes) {
  11758. var minVector = null;
  11759. var maxVector = null;
  11760. for (var i in meshes) {
  11761. var mesh = meshes[i];
  11762. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11763. if (!minVector) {
  11764. minVector = boundingBox.minimumWorld;
  11765. maxVector = boundingBox.maximumWorld;
  11766. continue;
  11767. }
  11768. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11769. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11770. }
  11771. return {
  11772. min: minVector,
  11773. max: maxVector
  11774. };
  11775. };
  11776. Mesh.Center = function (meshesOrMinMaxVector) {
  11777. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11778. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11779. };
  11780. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11781. if (disposeSource === void 0) { disposeSource = true; }
  11782. var source = meshes[0];
  11783. var material = source.material;
  11784. var scene = source.getScene();
  11785. if (!allow32BitsIndices) {
  11786. var totalVertices = 0;
  11787. for (var index = 0; index < meshes.length; index++) {
  11788. totalVertices += meshes[index].getTotalVertices();
  11789. if (totalVertices > 65536) {
  11790. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11791. return null;
  11792. }
  11793. }
  11794. }
  11795. // Merge
  11796. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11797. vertexData.transform(source.getWorldMatrix());
  11798. for (index = 1; index < meshes.length; index++) {
  11799. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11800. otherVertexData.transform(meshes[index].getWorldMatrix());
  11801. vertexData.merge(otherVertexData);
  11802. }
  11803. var newMesh = new Mesh(source.name + "_merged", scene);
  11804. vertexData.applyToMesh(newMesh);
  11805. // Setting properties
  11806. newMesh.material = material;
  11807. newMesh.checkCollisions = source.checkCollisions;
  11808. // Cleaning
  11809. if (disposeSource) {
  11810. for (index = 0; index < meshes.length; index++) {
  11811. meshes[index].dispose();
  11812. }
  11813. }
  11814. return newMesh;
  11815. };
  11816. // Consts
  11817. Mesh._FRONTSIDE = 0;
  11818. Mesh._BACKSIDE = 1;
  11819. Mesh._DOUBLESIDE = 2;
  11820. Mesh._DEFAULTSIDE = 0;
  11821. return Mesh;
  11822. })(BABYLON.AbstractMesh);
  11823. BABYLON.Mesh = Mesh;
  11824. })(BABYLON || (BABYLON = {}));
  11825. //# sourceMappingURL=babylon.mesh.js.map
  11826. var BABYLON;
  11827. (function (BABYLON) {
  11828. var GroundMesh = (function (_super) {
  11829. __extends(GroundMesh, _super);
  11830. function GroundMesh(name, scene) {
  11831. _super.call(this, name, scene);
  11832. this.generateOctree = false;
  11833. this._worldInverse = new BABYLON.Matrix();
  11834. }
  11835. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11836. get: function () {
  11837. return this._subdivisions;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. GroundMesh.prototype.optimize = function (chunksCount) {
  11843. this.subdivide(this._subdivisions);
  11844. this.createOrUpdateSubmeshesOctree(32);
  11845. };
  11846. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11847. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11848. this.getWorldMatrix().invertToRef(this._worldInverse);
  11849. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11850. var pickInfo = this.intersects(ray);
  11851. if (pickInfo.hit) {
  11852. return pickInfo.pickedPoint.y;
  11853. }
  11854. return 0;
  11855. };
  11856. return GroundMesh;
  11857. })(BABYLON.Mesh);
  11858. BABYLON.GroundMesh = GroundMesh;
  11859. })(BABYLON || (BABYLON = {}));
  11860. //# sourceMappingURL=babylon.groundMesh.js.map
  11861. var BABYLON;
  11862. (function (BABYLON) {
  11863. /**
  11864. * Creates an instance based on a source mesh.
  11865. */
  11866. var InstancedMesh = (function (_super) {
  11867. __extends(InstancedMesh, _super);
  11868. function InstancedMesh(name, source) {
  11869. _super.call(this, name, source.getScene());
  11870. source.instances.push(this);
  11871. this._sourceMesh = source;
  11872. this.position.copyFrom(source.position);
  11873. this.rotation.copyFrom(source.rotation);
  11874. this.scaling.copyFrom(source.scaling);
  11875. if (source.rotationQuaternion) {
  11876. this.rotationQuaternion = source.rotationQuaternion.clone();
  11877. }
  11878. this.infiniteDistance = source.infiniteDistance;
  11879. this.setPivotMatrix(source.getPivotMatrix());
  11880. this.refreshBoundingInfo();
  11881. this._syncSubMeshes();
  11882. }
  11883. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11884. // Methods
  11885. get: function () {
  11886. return this._sourceMesh.receiveShadows;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(InstancedMesh.prototype, "material", {
  11892. get: function () {
  11893. return this._sourceMesh.material;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11899. get: function () {
  11900. return this._sourceMesh.visibility;
  11901. },
  11902. enumerable: true,
  11903. configurable: true
  11904. });
  11905. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11906. get: function () {
  11907. return this._sourceMesh.skeleton;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. InstancedMesh.prototype.getTotalVertices = function () {
  11913. return this._sourceMesh.getTotalVertices();
  11914. };
  11915. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11916. get: function () {
  11917. return this._sourceMesh;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. InstancedMesh.prototype.getVerticesData = function (kind) {
  11923. return this._sourceMesh.getVerticesData(kind);
  11924. };
  11925. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11926. return this._sourceMesh.isVerticesDataPresent(kind);
  11927. };
  11928. InstancedMesh.prototype.getIndices = function () {
  11929. return this._sourceMesh.getIndices();
  11930. };
  11931. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11932. get: function () {
  11933. return this._sourceMesh._positions;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11939. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11940. if (data) {
  11941. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11942. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11943. }
  11944. this._updateBoundingInfo();
  11945. };
  11946. InstancedMesh.prototype._preActivate = function () {
  11947. if (this._currentLOD) {
  11948. this._currentLOD._preActivate();
  11949. }
  11950. };
  11951. InstancedMesh.prototype._activate = function (renderId) {
  11952. if (this._currentLOD) {
  11953. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11954. }
  11955. };
  11956. InstancedMesh.prototype.getLOD = function (camera) {
  11957. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11958. if (this._currentLOD === this.sourceMesh) {
  11959. return this;
  11960. }
  11961. return this._currentLOD;
  11962. };
  11963. InstancedMesh.prototype._syncSubMeshes = function () {
  11964. this.releaseSubMeshes();
  11965. if (this._sourceMesh.subMeshes) {
  11966. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11967. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11968. }
  11969. }
  11970. };
  11971. InstancedMesh.prototype._generatePointsArray = function () {
  11972. return this._sourceMesh._generatePointsArray();
  11973. };
  11974. // Clone
  11975. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11976. var result = this._sourceMesh.createInstance(name);
  11977. // Deep copy
  11978. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11979. // Bounding info
  11980. this.refreshBoundingInfo();
  11981. // Parent
  11982. if (newParent) {
  11983. result.parent = newParent;
  11984. }
  11985. if (!doNotCloneChildren) {
  11986. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11987. var mesh = this.getScene().meshes[index];
  11988. if (mesh.parent === this) {
  11989. mesh.clone(mesh.name, result);
  11990. }
  11991. }
  11992. }
  11993. result.computeWorldMatrix(true);
  11994. return result;
  11995. };
  11996. // Dispoe
  11997. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11998. // Remove from mesh
  11999. var index = this._sourceMesh.instances.indexOf(this);
  12000. this._sourceMesh.instances.splice(index, 1);
  12001. _super.prototype.dispose.call(this, doNotRecurse);
  12002. };
  12003. return InstancedMesh;
  12004. })(BABYLON.AbstractMesh);
  12005. BABYLON.InstancedMesh = InstancedMesh;
  12006. })(BABYLON || (BABYLON = {}));
  12007. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  12008. (function (BABYLON) {
  12009. var SubMesh = (function () {
  12010. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  12011. if (createBoundingBox === void 0) { createBoundingBox = true; }
  12012. this.materialIndex = materialIndex;
  12013. this.verticesStart = verticesStart;
  12014. this.verticesCount = verticesCount;
  12015. this.indexStart = indexStart;
  12016. this.indexCount = indexCount;
  12017. this._renderId = 0;
  12018. this._mesh = mesh;
  12019. this._renderingMesh = renderingMesh || mesh;
  12020. mesh.subMeshes.push(this);
  12021. this._id = mesh.subMeshes.length - 1;
  12022. if (createBoundingBox) {
  12023. this.refreshBoundingInfo();
  12024. mesh.computeWorldMatrix(true);
  12025. }
  12026. }
  12027. SubMesh.prototype.getBoundingInfo = function () {
  12028. return this._boundingInfo;
  12029. };
  12030. SubMesh.prototype.getMesh = function () {
  12031. return this._mesh;
  12032. };
  12033. SubMesh.prototype.getRenderingMesh = function () {
  12034. return this._renderingMesh;
  12035. };
  12036. SubMesh.prototype.getMaterial = function () {
  12037. var rootMaterial = this._renderingMesh.material;
  12038. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  12039. var multiMaterial = rootMaterial;
  12040. return multiMaterial.getSubMaterial(this.materialIndex);
  12041. }
  12042. if (!rootMaterial) {
  12043. return this._mesh.getScene().defaultMaterial;
  12044. }
  12045. return rootMaterial;
  12046. };
  12047. // Methods
  12048. SubMesh.prototype.refreshBoundingInfo = function () {
  12049. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12050. if (!data) {
  12051. this._boundingInfo = this._mesh._boundingInfo;
  12052. return;
  12053. }
  12054. var indices = this._renderingMesh.getIndices();
  12055. var extend;
  12056. if (this.indexStart === 0 && this.indexCount === indices.length) {
  12057. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  12058. }
  12059. else {
  12060. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  12061. }
  12062. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  12063. };
  12064. SubMesh.prototype._checkCollision = function (collider) {
  12065. return this._boundingInfo._checkCollision(collider);
  12066. };
  12067. SubMesh.prototype.updateBoundingInfo = function (world) {
  12068. if (!this._boundingInfo) {
  12069. this.refreshBoundingInfo();
  12070. }
  12071. this._boundingInfo._update(world);
  12072. };
  12073. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  12074. return this._boundingInfo.isInFrustum(frustumPlanes);
  12075. };
  12076. SubMesh.prototype.render = function () {
  12077. this._renderingMesh.render(this);
  12078. };
  12079. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  12080. if (!this._linesIndexBuffer) {
  12081. var linesIndices = [];
  12082. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12083. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  12084. }
  12085. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  12086. this.linesIndexCount = linesIndices.length;
  12087. }
  12088. return this._linesIndexBuffer;
  12089. };
  12090. SubMesh.prototype.canIntersects = function (ray) {
  12091. return ray.intersectsBox(this._boundingInfo.boundingBox);
  12092. };
  12093. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  12094. var intersectInfo = null;
  12095. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  12096. var p0 = positions[indices[index]];
  12097. var p1 = positions[indices[index + 1]];
  12098. var p2 = positions[indices[index + 2]];
  12099. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  12100. if (currentIntersectInfo) {
  12101. if (currentIntersectInfo.distance < 0) {
  12102. continue;
  12103. }
  12104. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  12105. intersectInfo = currentIntersectInfo;
  12106. intersectInfo.faceId = index / 3;
  12107. if (fastCheck) {
  12108. break;
  12109. }
  12110. }
  12111. }
  12112. }
  12113. return intersectInfo;
  12114. };
  12115. // Clone
  12116. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  12117. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  12118. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  12119. return result;
  12120. };
  12121. // Dispose
  12122. SubMesh.prototype.dispose = function () {
  12123. if (this._linesIndexBuffer) {
  12124. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  12125. this._linesIndexBuffer = null;
  12126. }
  12127. // Remove from mesh
  12128. var index = this._mesh.subMeshes.indexOf(this);
  12129. this._mesh.subMeshes.splice(index, 1);
  12130. };
  12131. // Statics
  12132. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  12133. var minVertexIndex = Number.MAX_VALUE;
  12134. var maxVertexIndex = -Number.MAX_VALUE;
  12135. renderingMesh = renderingMesh || mesh;
  12136. var indices = renderingMesh.getIndices();
  12137. for (var index = startIndex; index < startIndex + indexCount; index++) {
  12138. var vertexIndex = indices[index];
  12139. if (vertexIndex < minVertexIndex)
  12140. minVertexIndex = vertexIndex;
  12141. if (vertexIndex > maxVertexIndex)
  12142. maxVertexIndex = vertexIndex;
  12143. }
  12144. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  12145. };
  12146. return SubMesh;
  12147. })();
  12148. BABYLON.SubMesh = SubMesh;
  12149. })(BABYLON || (BABYLON = {}));
  12150. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  12151. (function (BABYLON) {
  12152. var BaseTexture = (function () {
  12153. function BaseTexture(scene) {
  12154. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  12155. this.hasAlpha = false;
  12156. this.getAlphaFromRGB = false;
  12157. this.level = 1;
  12158. this.isCube = false;
  12159. this.isRenderTarget = false;
  12160. this.animations = new Array();
  12161. this.coordinatesIndex = 0;
  12162. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  12163. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  12164. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  12165. this.anisotropicFilteringLevel = 4;
  12166. this._scene = scene;
  12167. this._scene.textures.push(this);
  12168. }
  12169. BaseTexture.prototype.getScene = function () {
  12170. return this._scene;
  12171. };
  12172. BaseTexture.prototype.getTextureMatrix = function () {
  12173. return null;
  12174. };
  12175. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  12176. return null;
  12177. };
  12178. BaseTexture.prototype.getInternalTexture = function () {
  12179. return this._texture;
  12180. };
  12181. BaseTexture.prototype.isReady = function () {
  12182. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12183. return true;
  12184. }
  12185. if (this._texture) {
  12186. return this._texture.isReady;
  12187. }
  12188. return false;
  12189. };
  12190. BaseTexture.prototype.getSize = function () {
  12191. if (this._texture._width) {
  12192. return { width: this._texture._width, height: this._texture._height };
  12193. }
  12194. if (this._texture._size) {
  12195. return { width: this._texture._size, height: this._texture._size };
  12196. }
  12197. return { width: 0, height: 0 };
  12198. };
  12199. BaseTexture.prototype.getBaseSize = function () {
  12200. if (!this.isReady())
  12201. return { width: 0, height: 0 };
  12202. if (this._texture._size) {
  12203. return { width: this._texture._size, height: this._texture._size };
  12204. }
  12205. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  12206. };
  12207. BaseTexture.prototype.scale = function (ratio) {
  12208. };
  12209. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  12210. get: function () {
  12211. return false;
  12212. },
  12213. enumerable: true,
  12214. configurable: true
  12215. });
  12216. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  12217. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12218. for (var index = 0; index < texturesCache.length; index++) {
  12219. var texturesCacheEntry = texturesCache[index];
  12220. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12221. texturesCache.splice(index, 1);
  12222. return;
  12223. }
  12224. }
  12225. };
  12226. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  12227. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12228. for (var index = 0; index < texturesCache.length; index++) {
  12229. var texturesCacheEntry = texturesCache[index];
  12230. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  12231. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  12232. texturesCacheEntry.references++;
  12233. return texturesCacheEntry;
  12234. }
  12235. }
  12236. }
  12237. return null;
  12238. };
  12239. BaseTexture.prototype.delayLoad = function () {
  12240. };
  12241. BaseTexture.prototype.releaseInternalTexture = function () {
  12242. if (!this._texture) {
  12243. return;
  12244. }
  12245. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  12246. this._texture.references--;
  12247. // Final reference ?
  12248. if (this._texture.references === 0) {
  12249. var index = texturesCache.indexOf(this._texture);
  12250. texturesCache.splice(index, 1);
  12251. this._scene.getEngine()._releaseTexture(this._texture);
  12252. delete this._texture;
  12253. }
  12254. };
  12255. BaseTexture.prototype.clone = function () {
  12256. return null;
  12257. };
  12258. BaseTexture.prototype.dispose = function () {
  12259. // Remove from scene
  12260. var index = this._scene.textures.indexOf(this);
  12261. if (index >= 0) {
  12262. this._scene.textures.splice(index, 1);
  12263. }
  12264. if (this._texture === undefined) {
  12265. return;
  12266. }
  12267. this.releaseInternalTexture();
  12268. // Callback
  12269. if (this.onDispose) {
  12270. this.onDispose();
  12271. }
  12272. };
  12273. return BaseTexture;
  12274. })();
  12275. BABYLON.BaseTexture = BaseTexture;
  12276. })(BABYLON || (BABYLON = {}));
  12277. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  12278. (function (BABYLON) {
  12279. var RenderingGroup = (function () {
  12280. function RenderingGroup(index, scene) {
  12281. this.index = index;
  12282. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  12283. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  12284. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  12285. this._scene = scene;
  12286. }
  12287. RenderingGroup.prototype.render = function (customRenderFunction) {
  12288. if (customRenderFunction) {
  12289. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  12290. return true;
  12291. }
  12292. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  12293. return false;
  12294. }
  12295. var engine = this._scene.getEngine();
  12296. // Opaque
  12297. var subIndex;
  12298. var submesh;
  12299. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  12300. submesh = this._opaqueSubMeshes.data[subIndex];
  12301. submesh.render();
  12302. }
  12303. // Alpha test
  12304. engine.setAlphaTesting(true);
  12305. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  12306. submesh = this._alphaTestSubMeshes.data[subIndex];
  12307. submesh.render();
  12308. }
  12309. engine.setAlphaTesting(false);
  12310. // Transparent
  12311. if (this._transparentSubMeshes.length) {
  12312. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  12313. submesh = this._transparentSubMeshes.data[subIndex];
  12314. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  12315. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  12316. }
  12317. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  12318. sortedArray.sort(function (a, b) {
  12319. // Alpha index first
  12320. if (a._alphaIndex > b._alphaIndex) {
  12321. return 1;
  12322. }
  12323. if (a._alphaIndex < b._alphaIndex) {
  12324. return -1;
  12325. }
  12326. // Then distance to camera
  12327. if (a._distanceToCamera < b._distanceToCamera) {
  12328. return 1;
  12329. }
  12330. if (a._distanceToCamera > b._distanceToCamera) {
  12331. return -1;
  12332. }
  12333. return 0;
  12334. });
  12335. // Rendering
  12336. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12337. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12338. submesh = sortedArray[subIndex];
  12339. submesh.render();
  12340. }
  12341. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12342. }
  12343. return true;
  12344. };
  12345. RenderingGroup.prototype.prepare = function () {
  12346. this._opaqueSubMeshes.reset();
  12347. this._transparentSubMeshes.reset();
  12348. this._alphaTestSubMeshes.reset();
  12349. };
  12350. RenderingGroup.prototype.dispatch = function (subMesh) {
  12351. var material = subMesh.getMaterial();
  12352. var mesh = subMesh.getMesh();
  12353. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12354. this._transparentSubMeshes.push(subMesh);
  12355. }
  12356. else if (material.needAlphaTesting()) {
  12357. this._alphaTestSubMeshes.push(subMesh);
  12358. }
  12359. else {
  12360. this._opaqueSubMeshes.push(subMesh); // Opaque
  12361. }
  12362. };
  12363. return RenderingGroup;
  12364. })();
  12365. BABYLON.RenderingGroup = RenderingGroup;
  12366. })(BABYLON || (BABYLON = {}));
  12367. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12368. (function (BABYLON) {
  12369. var RenderingManager = (function () {
  12370. function RenderingManager(scene) {
  12371. this._renderingGroups = new Array();
  12372. this._scene = scene;
  12373. }
  12374. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12375. if (this._scene._activeParticleSystems.length === 0) {
  12376. return;
  12377. }
  12378. // Particles
  12379. var beforeParticlesDate = BABYLON.Tools.Now;
  12380. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12381. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12382. if (particleSystem.renderingGroupId !== index) {
  12383. continue;
  12384. }
  12385. this._clearDepthBuffer();
  12386. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12387. this._scene._activeParticles += particleSystem.render();
  12388. }
  12389. }
  12390. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12391. };
  12392. RenderingManager.prototype._renderSprites = function (index) {
  12393. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12394. return;
  12395. }
  12396. // Sprites
  12397. var beforeSpritessDate = BABYLON.Tools.Now;
  12398. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12399. var spriteManager = this._scene.spriteManagers[id];
  12400. if (spriteManager.renderingGroupId === index) {
  12401. this._clearDepthBuffer();
  12402. spriteManager.render();
  12403. }
  12404. }
  12405. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12406. };
  12407. RenderingManager.prototype._clearDepthBuffer = function () {
  12408. if (this._depthBufferAlreadyCleaned) {
  12409. return;
  12410. }
  12411. this._scene.getEngine().clear(0, false, true);
  12412. this._depthBufferAlreadyCleaned = true;
  12413. };
  12414. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12415. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12416. this._depthBufferAlreadyCleaned = false;
  12417. var renderingGroup = this._renderingGroups[index];
  12418. var needToStepBack = false;
  12419. if (renderingGroup) {
  12420. this._clearDepthBuffer();
  12421. if (!renderingGroup.render(customRenderFunction)) {
  12422. this._renderingGroups.splice(index, 1);
  12423. needToStepBack = true;
  12424. }
  12425. }
  12426. if (renderSprites) {
  12427. this._renderSprites(index);
  12428. }
  12429. if (renderParticles) {
  12430. this._renderParticles(index, activeMeshes);
  12431. }
  12432. if (needToStepBack) {
  12433. index--;
  12434. }
  12435. }
  12436. };
  12437. RenderingManager.prototype.reset = function () {
  12438. for (var index in this._renderingGroups) {
  12439. var renderingGroup = this._renderingGroups[index];
  12440. renderingGroup.prepare();
  12441. }
  12442. };
  12443. RenderingManager.prototype.dispatch = function (subMesh) {
  12444. var mesh = subMesh.getMesh();
  12445. var renderingGroupId = mesh.renderingGroupId || 0;
  12446. if (!this._renderingGroups[renderingGroupId]) {
  12447. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12448. }
  12449. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12450. };
  12451. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12452. return RenderingManager;
  12453. })();
  12454. BABYLON.RenderingManager = RenderingManager;
  12455. })(BABYLON || (BABYLON = {}));
  12456. //# sourceMappingURL=babylon.renderingManager.js.map
  12457. var BABYLON;
  12458. (function (BABYLON) {
  12459. var Texture = (function (_super) {
  12460. __extends(Texture, _super);
  12461. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12462. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12463. if (onLoad === void 0) { onLoad = null; }
  12464. if (onError === void 0) { onError = null; }
  12465. if (buffer === void 0) { buffer = null; }
  12466. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12467. _super.call(this, scene);
  12468. this.uOffset = 0;
  12469. this.vOffset = 0;
  12470. this.uScale = 1.0;
  12471. this.vScale = 1.0;
  12472. this.uAng = 0;
  12473. this.vAng = 0;
  12474. this.wAng = 0;
  12475. this.name = url;
  12476. this.url = url;
  12477. this._noMipmap = noMipmap;
  12478. this._invertY = invertY;
  12479. this._samplingMode = samplingMode;
  12480. this._buffer = buffer;
  12481. this._deleteBuffer = deleteBuffer;
  12482. if (!url) {
  12483. return;
  12484. }
  12485. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12486. if (!this._texture) {
  12487. if (!scene.useDelayedTextureLoading) {
  12488. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12489. if (deleteBuffer) {
  12490. delete this._buffer;
  12491. }
  12492. }
  12493. else {
  12494. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12495. }
  12496. }
  12497. }
  12498. Texture.prototype.delayLoad = function () {
  12499. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12500. return;
  12501. }
  12502. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12503. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12504. if (!this._texture) {
  12505. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12506. if (this._deleteBuffer) {
  12507. delete this._buffer;
  12508. }
  12509. }
  12510. };
  12511. Texture.prototype.updateSamplingMode = function (samplingMode) {
  12512. if (!this._texture) {
  12513. return;
  12514. }
  12515. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  12516. };
  12517. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12518. x -= this.uOffset + 0.5;
  12519. y -= this.vOffset + 0.5;
  12520. z -= 0.5;
  12521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12522. t.x *= this.uScale;
  12523. t.y *= this.vScale;
  12524. t.x += 0.5;
  12525. t.y += 0.5;
  12526. t.z += 0.5;
  12527. };
  12528. Texture.prototype.getTextureMatrix = function () {
  12529. 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) {
  12530. return this._cachedTextureMatrix;
  12531. }
  12532. this._cachedUOffset = this.uOffset;
  12533. this._cachedVOffset = this.vOffset;
  12534. this._cachedUScale = this.uScale;
  12535. this._cachedVScale = this.vScale;
  12536. this._cachedUAng = this.uAng;
  12537. this._cachedVAng = this.vAng;
  12538. this._cachedWAng = this.wAng;
  12539. if (!this._cachedTextureMatrix) {
  12540. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12541. this._rowGenerationMatrix = new BABYLON.Matrix();
  12542. this._t0 = BABYLON.Vector3.Zero();
  12543. this._t1 = BABYLON.Vector3.Zero();
  12544. this._t2 = BABYLON.Vector3.Zero();
  12545. }
  12546. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12547. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12548. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12549. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12550. this._t1.subtractInPlace(this._t0);
  12551. this._t2.subtractInPlace(this._t0);
  12552. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12553. this._cachedTextureMatrix.m[0] = this._t1.x;
  12554. this._cachedTextureMatrix.m[1] = this._t1.y;
  12555. this._cachedTextureMatrix.m[2] = this._t1.z;
  12556. this._cachedTextureMatrix.m[4] = this._t2.x;
  12557. this._cachedTextureMatrix.m[5] = this._t2.y;
  12558. this._cachedTextureMatrix.m[6] = this._t2.z;
  12559. this._cachedTextureMatrix.m[8] = this._t0.x;
  12560. this._cachedTextureMatrix.m[9] = this._t0.y;
  12561. this._cachedTextureMatrix.m[10] = this._t0.z;
  12562. return this._cachedTextureMatrix;
  12563. };
  12564. Texture.prototype.getReflectionTextureMatrix = function () {
  12565. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12566. return this._cachedTextureMatrix;
  12567. }
  12568. if (!this._cachedTextureMatrix) {
  12569. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12570. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12571. }
  12572. this._cachedCoordinatesMode = this.coordinatesMode;
  12573. switch (this.coordinatesMode) {
  12574. case Texture.SPHERICAL_MODE:
  12575. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12576. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12577. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12578. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12579. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12580. break;
  12581. case Texture.PLANAR_MODE:
  12582. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12583. this._cachedTextureMatrix[0] = this.uScale;
  12584. this._cachedTextureMatrix[5] = this.vScale;
  12585. this._cachedTextureMatrix[12] = this.uOffset;
  12586. this._cachedTextureMatrix[13] = this.vOffset;
  12587. break;
  12588. case Texture.PROJECTION_MODE:
  12589. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12590. this._projectionModeMatrix.m[0] = 0.5;
  12591. this._projectionModeMatrix.m[5] = -0.5;
  12592. this._projectionModeMatrix.m[10] = 0.0;
  12593. this._projectionModeMatrix.m[12] = 0.5;
  12594. this._projectionModeMatrix.m[13] = 0.5;
  12595. this._projectionModeMatrix.m[14] = 1.0;
  12596. this._projectionModeMatrix.m[15] = 1.0;
  12597. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12598. break;
  12599. default:
  12600. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12601. break;
  12602. }
  12603. return this._cachedTextureMatrix;
  12604. };
  12605. Texture.prototype.clone = function () {
  12606. var newTexture = new Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12607. // Base texture
  12608. newTexture.hasAlpha = this.hasAlpha;
  12609. newTexture.level = this.level;
  12610. newTexture.wrapU = this.wrapU;
  12611. newTexture.wrapV = this.wrapV;
  12612. newTexture.coordinatesIndex = this.coordinatesIndex;
  12613. newTexture.coordinatesMode = this.coordinatesMode;
  12614. // Texture
  12615. newTexture.uOffset = this.uOffset;
  12616. newTexture.vOffset = this.vOffset;
  12617. newTexture.uScale = this.uScale;
  12618. newTexture.vScale = this.vScale;
  12619. newTexture.uAng = this.uAng;
  12620. newTexture.vAng = this.vAng;
  12621. newTexture.wAng = this.wAng;
  12622. return newTexture;
  12623. };
  12624. // Statics
  12625. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12626. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12627. if (onLoad === void 0) { onLoad = null; }
  12628. if (onError === void 0) { onError = null; }
  12629. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12630. };
  12631. // Constants
  12632. Texture.NEAREST_SAMPLINGMODE = 1;
  12633. Texture.BILINEAR_SAMPLINGMODE = 2;
  12634. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12635. Texture.EXPLICIT_MODE = 0;
  12636. Texture.SPHERICAL_MODE = 1;
  12637. Texture.PLANAR_MODE = 2;
  12638. Texture.CUBIC_MODE = 3;
  12639. Texture.PROJECTION_MODE = 4;
  12640. Texture.SKYBOX_MODE = 5;
  12641. Texture.CLAMP_ADDRESSMODE = 0;
  12642. Texture.WRAP_ADDRESSMODE = 1;
  12643. Texture.MIRROR_ADDRESSMODE = 2;
  12644. return Texture;
  12645. })(BABYLON.BaseTexture);
  12646. BABYLON.Texture = Texture;
  12647. })(BABYLON || (BABYLON = {}));
  12648. //# sourceMappingURL=babylon.texture.js.map
  12649. var BABYLON;
  12650. (function (BABYLON) {
  12651. var CubeTexture = (function (_super) {
  12652. __extends(CubeTexture, _super);
  12653. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12654. _super.call(this, scene);
  12655. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12656. this.name = rootUrl;
  12657. this.url = rootUrl;
  12658. this._noMipmap = noMipmap;
  12659. this.hasAlpha = false;
  12660. this._texture = this._getFromCache(rootUrl, noMipmap);
  12661. if (!extensions) {
  12662. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12663. }
  12664. this._extensions = extensions;
  12665. if (!this._texture) {
  12666. if (!scene.useDelayedTextureLoading) {
  12667. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12668. }
  12669. else {
  12670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12671. }
  12672. }
  12673. this.isCube = true;
  12674. this._textureMatrix = BABYLON.Matrix.Identity();
  12675. }
  12676. CubeTexture.prototype.clone = function () {
  12677. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12678. // Base texture
  12679. newTexture.level = this.level;
  12680. newTexture.wrapU = this.wrapU;
  12681. newTexture.wrapV = this.wrapV;
  12682. newTexture.coordinatesIndex = this.coordinatesIndex;
  12683. newTexture.coordinatesMode = this.coordinatesMode;
  12684. return newTexture;
  12685. };
  12686. // Methods
  12687. CubeTexture.prototype.delayLoad = function () {
  12688. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12689. return;
  12690. }
  12691. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12692. this._texture = this._getFromCache(this.url, this._noMipmap);
  12693. if (!this._texture) {
  12694. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12695. }
  12696. };
  12697. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12698. return this._textureMatrix;
  12699. };
  12700. return CubeTexture;
  12701. })(BABYLON.BaseTexture);
  12702. BABYLON.CubeTexture = CubeTexture;
  12703. })(BABYLON || (BABYLON = {}));
  12704. //# sourceMappingURL=babylon.cubeTexture.js.map
  12705. var BABYLON;
  12706. (function (BABYLON) {
  12707. var RenderTargetTexture = (function (_super) {
  12708. __extends(RenderTargetTexture, _super);
  12709. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12710. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12711. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12712. _super.call(this, null, scene, !generateMipMaps);
  12713. this.renderList = new Array();
  12714. this.renderParticles = true;
  12715. this.renderSprites = false;
  12716. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12717. this._currentRefreshId = -1;
  12718. this._refreshRate = 1;
  12719. this.name = name;
  12720. this.isRenderTarget = true;
  12721. this._size = size;
  12722. this._generateMipMaps = generateMipMaps;
  12723. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12724. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12725. // Rendering groups
  12726. this._renderingManager = new BABYLON.RenderingManager(scene);
  12727. }
  12728. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12729. this._currentRefreshId = -1;
  12730. };
  12731. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12732. get: function () {
  12733. return this._refreshRate;
  12734. },
  12735. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12736. set: function (value) {
  12737. this._refreshRate = value;
  12738. this.resetRefreshCounter();
  12739. },
  12740. enumerable: true,
  12741. configurable: true
  12742. });
  12743. RenderTargetTexture.prototype._shouldRender = function () {
  12744. if (this._currentRefreshId === -1) {
  12745. this._currentRefreshId = 1;
  12746. return true;
  12747. }
  12748. if (this.refreshRate === this._currentRefreshId) {
  12749. this._currentRefreshId = 1;
  12750. return true;
  12751. }
  12752. this._currentRefreshId++;
  12753. return false;
  12754. };
  12755. RenderTargetTexture.prototype.isReady = function () {
  12756. if (!this.getScene().renderTargetsEnabled) {
  12757. return false;
  12758. }
  12759. return _super.prototype.isReady.call(this);
  12760. };
  12761. RenderTargetTexture.prototype.getRenderSize = function () {
  12762. return this._size;
  12763. };
  12764. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12765. get: function () {
  12766. return true;
  12767. },
  12768. enumerable: true,
  12769. configurable: true
  12770. });
  12771. RenderTargetTexture.prototype.scale = function (ratio) {
  12772. var newSize = this._size * ratio;
  12773. this.resize(newSize, this._generateMipMaps);
  12774. };
  12775. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12776. this.releaseInternalTexture();
  12777. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12778. };
  12779. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12780. var scene = this.getScene();
  12781. var engine = scene.getEngine();
  12782. if (this._waitingRenderList) {
  12783. this.renderList = [];
  12784. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12785. var id = this._waitingRenderList[index];
  12786. this.renderList.push(scene.getMeshByID(id));
  12787. }
  12788. delete this._waitingRenderList;
  12789. }
  12790. if (this.renderList && this.renderList.length === 0) {
  12791. return;
  12792. }
  12793. // Bind
  12794. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12795. engine.bindFramebuffer(this._texture);
  12796. }
  12797. this._renderingManager.reset();
  12798. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12799. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12800. var mesh = currentRenderList[meshIndex];
  12801. if (mesh) {
  12802. if (!mesh.isReady()) {
  12803. // Reset _currentRefreshId
  12804. this.resetRefreshCounter();
  12805. continue;
  12806. }
  12807. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12808. mesh._activate(scene.getRenderId());
  12809. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12810. var subMesh = mesh.subMeshes[subIndex];
  12811. scene._activeVertices += subMesh.indexCount;
  12812. this._renderingManager.dispatch(subMesh);
  12813. }
  12814. }
  12815. }
  12816. }
  12817. if (this.onBeforeRender) {
  12818. this.onBeforeRender();
  12819. }
  12820. // Clear
  12821. if (this.onClear) {
  12822. this.onClear(engine);
  12823. }
  12824. else {
  12825. engine.clear(scene.clearColor, true, true);
  12826. }
  12827. if (!this._doNotChangeAspectRatio) {
  12828. scene.updateTransformMatrix(true);
  12829. }
  12830. // Render
  12831. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12832. if (useCameraPostProcess) {
  12833. scene.postProcessManager._finalizeFrame(false, this._texture);
  12834. }
  12835. if (!this._doNotChangeAspectRatio) {
  12836. scene.updateTransformMatrix(true);
  12837. }
  12838. if (this.onAfterRender) {
  12839. this.onAfterRender();
  12840. }
  12841. // Dump ?
  12842. if (dumpForDebug) {
  12843. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12844. }
  12845. // Unbind
  12846. engine.unBindFramebuffer(this._texture);
  12847. if (this.onAfterUnbind) {
  12848. this.onAfterUnbind();
  12849. }
  12850. };
  12851. RenderTargetTexture.prototype.clone = function () {
  12852. var textureSize = this.getSize();
  12853. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12854. // Base texture
  12855. newTexture.hasAlpha = this.hasAlpha;
  12856. newTexture.level = this.level;
  12857. // RenderTarget Texture
  12858. newTexture.coordinatesMode = this.coordinatesMode;
  12859. newTexture.renderList = this.renderList.slice(0);
  12860. return newTexture;
  12861. };
  12862. return RenderTargetTexture;
  12863. })(BABYLON.Texture);
  12864. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12865. })(BABYLON || (BABYLON = {}));
  12866. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12867. var BABYLON;
  12868. (function (BABYLON) {
  12869. var ProceduralTexture = (function (_super) {
  12870. __extends(ProceduralTexture, _super);
  12871. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12872. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12873. _super.call(this, null, scene, !generateMipMaps);
  12874. this._currentRefreshId = -1;
  12875. this._refreshRate = 1;
  12876. this._vertexDeclaration = [2];
  12877. this._vertexStrideSize = 2 * 4;
  12878. this._uniforms = new Array();
  12879. this._samplers = new Array();
  12880. this._textures = new Array();
  12881. this._floats = new Array();
  12882. this._floatsArrays = {};
  12883. this._colors3 = new Array();
  12884. this._colors4 = new Array();
  12885. this._vectors2 = new Array();
  12886. this._vectors3 = new Array();
  12887. this._matrices = new Array();
  12888. this._fallbackTextureUsed = false;
  12889. scene._proceduralTextures.push(this);
  12890. this.name = name;
  12891. this.isRenderTarget = true;
  12892. this._size = size;
  12893. this._generateMipMaps = generateMipMaps;
  12894. this.setFragment(fragment);
  12895. this._fallbackTexture = fallbackTexture;
  12896. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12897. // VBO
  12898. var vertices = [];
  12899. vertices.push(1, 1);
  12900. vertices.push(-1, 1);
  12901. vertices.push(-1, -1);
  12902. vertices.push(1, -1);
  12903. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12904. // Indices
  12905. var indices = [];
  12906. indices.push(0);
  12907. indices.push(1);
  12908. indices.push(2);
  12909. indices.push(0);
  12910. indices.push(2);
  12911. indices.push(3);
  12912. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12913. }
  12914. ProceduralTexture.prototype.reset = function () {
  12915. if (this._effect === undefined) {
  12916. return;
  12917. }
  12918. var engine = this.getScene().getEngine();
  12919. engine._releaseEffect(this._effect);
  12920. };
  12921. ProceduralTexture.prototype.isReady = function () {
  12922. var _this = this;
  12923. var engine = this.getScene().getEngine();
  12924. var shaders;
  12925. if (!this._fragment) {
  12926. return false;
  12927. }
  12928. if (this._fallbackTextureUsed) {
  12929. return true;
  12930. }
  12931. if (this._fragment.fragmentElement !== undefined) {
  12932. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12933. }
  12934. else {
  12935. shaders = { vertex: "procedural", fragment: this._fragment };
  12936. }
  12937. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12938. _this.releaseInternalTexture();
  12939. if (_this._fallbackTexture) {
  12940. _this._texture = _this._fallbackTexture._texture;
  12941. _this._texture.references++;
  12942. }
  12943. _this._fallbackTextureUsed = true;
  12944. });
  12945. return this._effect.isReady();
  12946. };
  12947. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12948. this._currentRefreshId = -1;
  12949. };
  12950. ProceduralTexture.prototype.setFragment = function (fragment) {
  12951. this._fragment = fragment;
  12952. };
  12953. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12954. get: function () {
  12955. return this._refreshRate;
  12956. },
  12957. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12958. set: function (value) {
  12959. this._refreshRate = value;
  12960. this.resetRefreshCounter();
  12961. },
  12962. enumerable: true,
  12963. configurable: true
  12964. });
  12965. ProceduralTexture.prototype._shouldRender = function () {
  12966. if (!this.isReady() || !this._texture) {
  12967. return false;
  12968. }
  12969. if (this._fallbackTextureUsed) {
  12970. return false;
  12971. }
  12972. if (this._currentRefreshId === -1) {
  12973. this._currentRefreshId = 1;
  12974. return true;
  12975. }
  12976. if (this.refreshRate === this._currentRefreshId) {
  12977. this._currentRefreshId = 1;
  12978. return true;
  12979. }
  12980. this._currentRefreshId++;
  12981. return false;
  12982. };
  12983. ProceduralTexture.prototype.getRenderSize = function () {
  12984. return this._size;
  12985. };
  12986. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12987. if (this._fallbackTextureUsed) {
  12988. return;
  12989. }
  12990. this.releaseInternalTexture();
  12991. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12992. };
  12993. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12994. if (this._uniforms.indexOf(uniformName) === -1) {
  12995. this._uniforms.push(uniformName);
  12996. }
  12997. };
  12998. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12999. if (this._samplers.indexOf(name) === -1) {
  13000. this._samplers.push(name);
  13001. }
  13002. this._textures[name] = texture;
  13003. return this;
  13004. };
  13005. ProceduralTexture.prototype.setFloat = function (name, value) {
  13006. this._checkUniform(name);
  13007. this._floats[name] = value;
  13008. return this;
  13009. };
  13010. ProceduralTexture.prototype.setFloats = function (name, value) {
  13011. this._checkUniform(name);
  13012. this._floatsArrays[name] = value;
  13013. return this;
  13014. };
  13015. ProceduralTexture.prototype.setColor3 = function (name, value) {
  13016. this._checkUniform(name);
  13017. this._colors3[name] = value;
  13018. return this;
  13019. };
  13020. ProceduralTexture.prototype.setColor4 = function (name, value) {
  13021. this._checkUniform(name);
  13022. this._colors4[name] = value;
  13023. return this;
  13024. };
  13025. ProceduralTexture.prototype.setVector2 = function (name, value) {
  13026. this._checkUniform(name);
  13027. this._vectors2[name] = value;
  13028. return this;
  13029. };
  13030. ProceduralTexture.prototype.setVector3 = function (name, value) {
  13031. this._checkUniform(name);
  13032. this._vectors3[name] = value;
  13033. return this;
  13034. };
  13035. ProceduralTexture.prototype.setMatrix = function (name, value) {
  13036. this._checkUniform(name);
  13037. this._matrices[name] = value;
  13038. return this;
  13039. };
  13040. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13041. var scene = this.getScene();
  13042. var engine = scene.getEngine();
  13043. engine.bindFramebuffer(this._texture);
  13044. // Clear
  13045. engine.clear(scene.clearColor, true, true);
  13046. // Render
  13047. engine.enableEffect(this._effect);
  13048. engine.setState(false);
  13049. for (var name in this._textures) {
  13050. this._effect.setTexture(name, this._textures[name]);
  13051. }
  13052. for (name in this._floats) {
  13053. this._effect.setFloat(name, this._floats[name]);
  13054. }
  13055. for (name in this._floatsArrays) {
  13056. this._effect.setArray(name, this._floatsArrays[name]);
  13057. }
  13058. for (name in this._colors3) {
  13059. this._effect.setColor3(name, this._colors3[name]);
  13060. }
  13061. for (name in this._colors4) {
  13062. var color = this._colors4[name];
  13063. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  13064. }
  13065. for (name in this._vectors2) {
  13066. this._effect.setVector2(name, this._vectors2[name]);
  13067. }
  13068. for (name in this._vectors3) {
  13069. this._effect.setVector3(name, this._vectors3[name]);
  13070. }
  13071. for (name in this._matrices) {
  13072. this._effect.setMatrix(name, this._matrices[name]);
  13073. }
  13074. // VBOs
  13075. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  13076. // Draw order
  13077. engine.draw(true, 0, 6);
  13078. // Unbind
  13079. engine.unBindFramebuffer(this._texture);
  13080. };
  13081. ProceduralTexture.prototype.clone = function () {
  13082. var textureSize = this.getSize();
  13083. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  13084. // Base texture
  13085. newTexture.hasAlpha = this.hasAlpha;
  13086. newTexture.level = this.level;
  13087. // RenderTarget Texture
  13088. newTexture.coordinatesMode = this.coordinatesMode;
  13089. return newTexture;
  13090. };
  13091. ProceduralTexture.prototype.dispose = function () {
  13092. var index = this.getScene()._proceduralTextures.indexOf(this);
  13093. if (index >= 0) {
  13094. this.getScene()._proceduralTextures.splice(index, 1);
  13095. }
  13096. _super.prototype.dispose.call(this);
  13097. };
  13098. return ProceduralTexture;
  13099. })(BABYLON.Texture);
  13100. BABYLON.ProceduralTexture = ProceduralTexture;
  13101. })(BABYLON || (BABYLON = {}));
  13102. //# sourceMappingURL=babylon.proceduralTexture.js.map
  13103. var BABYLON;
  13104. (function (BABYLON) {
  13105. var WoodProceduralTexture = (function (_super) {
  13106. __extends(WoodProceduralTexture, _super);
  13107. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13108. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  13109. this._ampScale = 100.0;
  13110. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  13111. this.updateShaderUniforms();
  13112. this.refreshRate = 0;
  13113. }
  13114. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  13115. this.setFloat("ampScale", this._ampScale);
  13116. this.setColor3("woodColor", this._woodColor);
  13117. };
  13118. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  13119. get: function () {
  13120. return this._ampScale;
  13121. },
  13122. set: function (value) {
  13123. this._ampScale = value;
  13124. this.updateShaderUniforms();
  13125. },
  13126. enumerable: true,
  13127. configurable: true
  13128. });
  13129. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  13130. get: function () {
  13131. return this._woodColor;
  13132. },
  13133. set: function (value) {
  13134. this._woodColor = value;
  13135. this.updateShaderUniforms();
  13136. },
  13137. enumerable: true,
  13138. configurable: true
  13139. });
  13140. return WoodProceduralTexture;
  13141. })(BABYLON.ProceduralTexture);
  13142. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  13143. var FireProceduralTexture = (function (_super) {
  13144. __extends(FireProceduralTexture, _super);
  13145. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13146. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  13147. this._time = 0.0;
  13148. this._speed = new BABYLON.Vector2(0.5, 0.3);
  13149. this._shift = 1.6;
  13150. this._autoGenerateTime = true;
  13151. this._alphaThreshold = 0.5;
  13152. this._fireColors = FireProceduralTexture.RedFireColors;
  13153. this.updateShaderUniforms();
  13154. this.refreshRate = 1;
  13155. }
  13156. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  13157. this.setFloat("time", this._time);
  13158. this.setVector2("speed", this._speed);
  13159. this.setFloat("shift", this._shift);
  13160. this.setColor3("c1", this._fireColors[0]);
  13161. this.setColor3("c2", this._fireColors[1]);
  13162. this.setColor3("c3", this._fireColors[2]);
  13163. this.setColor3("c4", this._fireColors[3]);
  13164. this.setColor3("c5", this._fireColors[4]);
  13165. this.setColor3("c6", this._fireColors[5]);
  13166. this.setFloat("alphaThreshold", this._alphaThreshold);
  13167. };
  13168. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13169. if (this._autoGenerateTime) {
  13170. this._time += this.getScene().getAnimationRatio() * 0.03;
  13171. this.updateShaderUniforms();
  13172. }
  13173. _super.prototype.render.call(this, useCameraPostProcess);
  13174. };
  13175. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  13176. get: function () {
  13177. return [
  13178. new BABYLON.Color3(0.5, 0.0, 1.0),
  13179. new BABYLON.Color3(0.9, 0.0, 1.0),
  13180. new BABYLON.Color3(0.2, 0.0, 1.0),
  13181. new BABYLON.Color3(1.0, 0.9, 1.0),
  13182. new BABYLON.Color3(0.1, 0.1, 1.0),
  13183. new BABYLON.Color3(0.9, 0.9, 1.0)
  13184. ];
  13185. },
  13186. enumerable: true,
  13187. configurable: true
  13188. });
  13189. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  13190. get: function () {
  13191. return [
  13192. new BABYLON.Color3(0.5, 1.0, 0.0),
  13193. new BABYLON.Color3(0.5, 1.0, 0.0),
  13194. new BABYLON.Color3(0.3, 0.4, 0.0),
  13195. new BABYLON.Color3(0.5, 1.0, 0.0),
  13196. new BABYLON.Color3(0.2, 0.0, 0.0),
  13197. new BABYLON.Color3(0.5, 1.0, 0.0)
  13198. ];
  13199. },
  13200. enumerable: true,
  13201. configurable: true
  13202. });
  13203. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  13204. get: function () {
  13205. return [
  13206. new BABYLON.Color3(0.5, 0.0, 0.1),
  13207. new BABYLON.Color3(0.9, 0.0, 0.0),
  13208. new BABYLON.Color3(0.2, 0.0, 0.0),
  13209. new BABYLON.Color3(1.0, 0.9, 0.0),
  13210. new BABYLON.Color3(0.1, 0.1, 0.1),
  13211. new BABYLON.Color3(0.9, 0.9, 0.9)
  13212. ];
  13213. },
  13214. enumerable: true,
  13215. configurable: true
  13216. });
  13217. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  13218. get: function () {
  13219. return [
  13220. new BABYLON.Color3(0.1, 0.0, 0.5),
  13221. new BABYLON.Color3(0.0, 0.0, 0.5),
  13222. new BABYLON.Color3(0.1, 0.0, 0.2),
  13223. new BABYLON.Color3(0.0, 0.0, 1.0),
  13224. new BABYLON.Color3(0.1, 0.2, 0.3),
  13225. new BABYLON.Color3(0.0, 0.2, 0.9)
  13226. ];
  13227. },
  13228. enumerable: true,
  13229. configurable: true
  13230. });
  13231. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  13232. get: function () {
  13233. return this._fireColors;
  13234. },
  13235. set: function (value) {
  13236. this._fireColors = value;
  13237. this.updateShaderUniforms();
  13238. },
  13239. enumerable: true,
  13240. configurable: true
  13241. });
  13242. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  13243. get: function () {
  13244. return this._time;
  13245. },
  13246. set: function (value) {
  13247. this._time = value;
  13248. this.updateShaderUniforms();
  13249. },
  13250. enumerable: true,
  13251. configurable: true
  13252. });
  13253. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  13254. get: function () {
  13255. return this._speed;
  13256. },
  13257. set: function (value) {
  13258. this._speed = value;
  13259. this.updateShaderUniforms();
  13260. },
  13261. enumerable: true,
  13262. configurable: true
  13263. });
  13264. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  13265. get: function () {
  13266. return this._shift;
  13267. },
  13268. set: function (value) {
  13269. this._shift = value;
  13270. this.updateShaderUniforms();
  13271. },
  13272. enumerable: true,
  13273. configurable: true
  13274. });
  13275. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  13276. get: function () {
  13277. return this._alphaThreshold;
  13278. },
  13279. set: function (value) {
  13280. this._alphaThreshold = value;
  13281. this.updateShaderUniforms();
  13282. },
  13283. enumerable: true,
  13284. configurable: true
  13285. });
  13286. return FireProceduralTexture;
  13287. })(BABYLON.ProceduralTexture);
  13288. BABYLON.FireProceduralTexture = FireProceduralTexture;
  13289. var CloudProceduralTexture = (function (_super) {
  13290. __extends(CloudProceduralTexture, _super);
  13291. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13292. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  13293. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  13294. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  13295. this.updateShaderUniforms();
  13296. this.refreshRate = 0;
  13297. }
  13298. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  13299. this.setColor3("skyColor", this._skyColor);
  13300. this.setColor3("cloudColor", this._cloudColor);
  13301. };
  13302. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  13303. get: function () {
  13304. return this._skyColor;
  13305. },
  13306. set: function (value) {
  13307. this._skyColor = value;
  13308. this.updateShaderUniforms();
  13309. },
  13310. enumerable: true,
  13311. configurable: true
  13312. });
  13313. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  13314. get: function () {
  13315. return this._cloudColor;
  13316. },
  13317. set: function (value) {
  13318. this._cloudColor = value;
  13319. this.updateShaderUniforms();
  13320. },
  13321. enumerable: true,
  13322. configurable: true
  13323. });
  13324. return CloudProceduralTexture;
  13325. })(BABYLON.ProceduralTexture);
  13326. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  13327. var GrassProceduralTexture = (function (_super) {
  13328. __extends(GrassProceduralTexture, _super);
  13329. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13330. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  13331. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  13332. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  13333. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  13334. this._groundColor = new BABYLON.Color3(1, 1, 1);
  13335. this._grassColors = [
  13336. new BABYLON.Color3(0.29, 0.38, 0.02),
  13337. new BABYLON.Color3(0.36, 0.49, 0.09),
  13338. new BABYLON.Color3(0.51, 0.6, 0.28)
  13339. ];
  13340. this.updateShaderUniforms();
  13341. this.refreshRate = 0;
  13342. }
  13343. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13344. this.setColor3("herb1Color", this._grassColors[0]);
  13345. this.setColor3("herb2Color", this._grassColors[1]);
  13346. this.setColor3("herb3Color", this._grassColors[2]);
  13347. this.setColor3("groundColor", this._groundColor);
  13348. };
  13349. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13350. get: function () {
  13351. return this._grassColors;
  13352. },
  13353. set: function (value) {
  13354. this._grassColors = value;
  13355. this.updateShaderUniforms();
  13356. },
  13357. enumerable: true,
  13358. configurable: true
  13359. });
  13360. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13361. get: function () {
  13362. return this._groundColor;
  13363. },
  13364. set: function (value) {
  13365. this.groundColor = value;
  13366. this.updateShaderUniforms();
  13367. },
  13368. enumerable: true,
  13369. configurable: true
  13370. });
  13371. return GrassProceduralTexture;
  13372. })(BABYLON.ProceduralTexture);
  13373. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13374. var RoadProceduralTexture = (function (_super) {
  13375. __extends(RoadProceduralTexture, _super);
  13376. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13377. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13378. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13379. this.updateShaderUniforms();
  13380. this.refreshRate = 0;
  13381. }
  13382. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13383. this.setColor3("roadColor", this._roadColor);
  13384. };
  13385. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13386. get: function () {
  13387. return this._roadColor;
  13388. },
  13389. set: function (value) {
  13390. this._roadColor = value;
  13391. this.updateShaderUniforms();
  13392. },
  13393. enumerable: true,
  13394. configurable: true
  13395. });
  13396. return RoadProceduralTexture;
  13397. })(BABYLON.ProceduralTexture);
  13398. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13399. var BrickProceduralTexture = (function (_super) {
  13400. __extends(BrickProceduralTexture, _super);
  13401. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13402. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13403. this._numberOfBricksHeight = 15;
  13404. this._numberOfBricksWidth = 5;
  13405. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13406. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13407. this.updateShaderUniforms();
  13408. this.refreshRate = 0;
  13409. }
  13410. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13411. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13412. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13413. this.setColor3("brickColor", this._brickColor);
  13414. this.setColor3("jointColor", this._jointColor);
  13415. };
  13416. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13417. get: function () {
  13418. return this._numberOfBricksHeight;
  13419. },
  13420. enumerable: true,
  13421. configurable: true
  13422. });
  13423. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13424. set: function (value) {
  13425. this._numberOfBricksHeight = value;
  13426. this.updateShaderUniforms();
  13427. },
  13428. enumerable: true,
  13429. configurable: true
  13430. });
  13431. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13432. get: function () {
  13433. return this._numberOfBricksWidth;
  13434. },
  13435. set: function (value) {
  13436. this._numberOfBricksHeight = value;
  13437. this.updateShaderUniforms();
  13438. },
  13439. enumerable: true,
  13440. configurable: true
  13441. });
  13442. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13443. get: function () {
  13444. return this._jointColor;
  13445. },
  13446. set: function (value) {
  13447. this._jointColor = value;
  13448. this.updateShaderUniforms();
  13449. },
  13450. enumerable: true,
  13451. configurable: true
  13452. });
  13453. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13454. get: function () {
  13455. return this._brickColor;
  13456. },
  13457. set: function (value) {
  13458. this._brickColor = value;
  13459. this.updateShaderUniforms();
  13460. },
  13461. enumerable: true,
  13462. configurable: true
  13463. });
  13464. return BrickProceduralTexture;
  13465. })(BABYLON.ProceduralTexture);
  13466. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13467. var MarbleProceduralTexture = (function (_super) {
  13468. __extends(MarbleProceduralTexture, _super);
  13469. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13470. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13471. this._numberOfTilesHeight = 3;
  13472. this._numberOfTilesWidth = 3;
  13473. this._amplitude = 9.0;
  13474. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13475. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13476. this.updateShaderUniforms();
  13477. this.refreshRate = 0;
  13478. }
  13479. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13480. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13481. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13482. this.setFloat("amplitude", this._amplitude);
  13483. this.setColor3("marbleColor", this._marbleColor);
  13484. this.setColor3("jointColor", this._jointColor);
  13485. };
  13486. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13487. get: function () {
  13488. return this._numberOfTilesHeight;
  13489. },
  13490. set: function (value) {
  13491. this._numberOfTilesHeight = value;
  13492. this.updateShaderUniforms();
  13493. },
  13494. enumerable: true,
  13495. configurable: true
  13496. });
  13497. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13498. get: function () {
  13499. return this._numberOfTilesWidth;
  13500. },
  13501. set: function (value) {
  13502. this._numberOfTilesWidth = value;
  13503. this.updateShaderUniforms();
  13504. },
  13505. enumerable: true,
  13506. configurable: true
  13507. });
  13508. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13509. get: function () {
  13510. return this._jointColor;
  13511. },
  13512. set: function (value) {
  13513. this._jointColor = value;
  13514. this.updateShaderUniforms();
  13515. },
  13516. enumerable: true,
  13517. configurable: true
  13518. });
  13519. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13520. get: function () {
  13521. return this._marbleColor;
  13522. },
  13523. set: function (value) {
  13524. this._marbleColor = value;
  13525. this.updateShaderUniforms();
  13526. },
  13527. enumerable: true,
  13528. configurable: true
  13529. });
  13530. return MarbleProceduralTexture;
  13531. })(BABYLON.ProceduralTexture);
  13532. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13533. })(BABYLON || (BABYLON = {}));
  13534. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13535. var BABYLON;
  13536. (function (BABYLON) {
  13537. var CustomProceduralTexture = (function (_super) {
  13538. __extends(CustomProceduralTexture, _super);
  13539. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13540. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13541. this._animate = true;
  13542. this._time = 0;
  13543. this._texturePath = texturePath;
  13544. //Try to load json
  13545. this.loadJson(texturePath);
  13546. this.refreshRate = 1;
  13547. }
  13548. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13549. var _this = this;
  13550. var that = this;
  13551. function noConfigFile() {
  13552. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13553. try {
  13554. that.setFragment(that._texturePath);
  13555. }
  13556. catch (ex) {
  13557. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13558. }
  13559. }
  13560. var configFileUrl = jsonUrl + "/config.json";
  13561. var xhr = new XMLHttpRequest();
  13562. xhr.open("GET", configFileUrl, true);
  13563. xhr.addEventListener("load", function () {
  13564. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13565. try {
  13566. _this._config = JSON.parse(xhr.response);
  13567. _this.updateShaderUniforms();
  13568. _this.updateTextures();
  13569. _this.setFragment(_this._texturePath + "/custom");
  13570. _this._animate = _this._config.animate;
  13571. _this.refreshRate = _this._config.refreshrate;
  13572. }
  13573. catch (ex) {
  13574. noConfigFile();
  13575. }
  13576. }
  13577. else {
  13578. noConfigFile();
  13579. }
  13580. }, false);
  13581. xhr.addEventListener("error", function () {
  13582. noConfigFile();
  13583. }, false);
  13584. try {
  13585. xhr.send();
  13586. }
  13587. catch (ex) {
  13588. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13589. }
  13590. };
  13591. CustomProceduralTexture.prototype.isReady = function () {
  13592. if (!_super.prototype.isReady.call(this)) {
  13593. return false;
  13594. }
  13595. for (var name in this._textures) {
  13596. var texture = this._textures[name];
  13597. if (!texture.isReady()) {
  13598. return false;
  13599. }
  13600. }
  13601. return true;
  13602. };
  13603. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13604. if (this._animate) {
  13605. this._time += this.getScene().getAnimationRatio() * 0.03;
  13606. this.updateShaderUniforms();
  13607. }
  13608. _super.prototype.render.call(this, useCameraPostProcess);
  13609. };
  13610. CustomProceduralTexture.prototype.updateTextures = function () {
  13611. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13612. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13613. }
  13614. };
  13615. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13616. if (this._config) {
  13617. for (var j = 0; j < this._config.uniforms.length; j++) {
  13618. var uniform = this._config.uniforms[j];
  13619. switch (uniform.type) {
  13620. case "float":
  13621. this.setFloat(uniform.name, uniform.value);
  13622. break;
  13623. case "color3":
  13624. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13625. break;
  13626. case "color4":
  13627. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13628. break;
  13629. case "vector2":
  13630. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13631. break;
  13632. case "vector3":
  13633. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13634. break;
  13635. }
  13636. }
  13637. }
  13638. this.setFloat("time", this._time);
  13639. };
  13640. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13641. get: function () {
  13642. return this._animate;
  13643. },
  13644. set: function (value) {
  13645. this._animate = value;
  13646. },
  13647. enumerable: true,
  13648. configurable: true
  13649. });
  13650. return CustomProceduralTexture;
  13651. })(BABYLON.ProceduralTexture);
  13652. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13653. })(BABYLON || (BABYLON = {}));
  13654. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13655. var BABYLON;
  13656. (function (BABYLON) {
  13657. var MirrorTexture = (function (_super) {
  13658. __extends(MirrorTexture, _super);
  13659. function MirrorTexture(name, size, scene, generateMipMaps) {
  13660. var _this = this;
  13661. _super.call(this, name, size, scene, generateMipMaps, true);
  13662. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13663. this._transformMatrix = BABYLON.Matrix.Zero();
  13664. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13665. this.onBeforeRender = function () {
  13666. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13667. _this._savedViewMatrix = scene.getViewMatrix();
  13668. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13669. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13670. scene.clipPlane = _this.mirrorPlane;
  13671. scene.getEngine().cullBackFaces = false;
  13672. };
  13673. this.onAfterRender = function () {
  13674. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13675. scene.getEngine().cullBackFaces = true;
  13676. delete scene.clipPlane;
  13677. };
  13678. }
  13679. MirrorTexture.prototype.clone = function () {
  13680. var textureSize = this.getSize();
  13681. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13682. // Base texture
  13683. newTexture.hasAlpha = this.hasAlpha;
  13684. newTexture.level = this.level;
  13685. // Mirror Texture
  13686. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13687. newTexture.renderList = this.renderList.slice(0);
  13688. return newTexture;
  13689. };
  13690. return MirrorTexture;
  13691. })(BABYLON.RenderTargetTexture);
  13692. BABYLON.MirrorTexture = MirrorTexture;
  13693. })(BABYLON || (BABYLON = {}));
  13694. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13695. var BABYLON;
  13696. (function (BABYLON) {
  13697. var DynamicTexture = (function (_super) {
  13698. __extends(DynamicTexture, _super);
  13699. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13701. _super.call(this, null, scene, !generateMipMaps);
  13702. this.name = name;
  13703. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13704. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13705. this._generateMipMaps = generateMipMaps;
  13706. if (options.getContext) {
  13707. this._canvas = options;
  13708. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13709. }
  13710. else {
  13711. this._canvas = document.createElement("canvas");
  13712. if (options.width) {
  13713. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13714. }
  13715. else {
  13716. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13717. }
  13718. }
  13719. var textureSize = this.getSize();
  13720. this._canvas.width = textureSize.width;
  13721. this._canvas.height = textureSize.height;
  13722. this._context = this._canvas.getContext("2d");
  13723. }
  13724. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13725. get: function () {
  13726. return true;
  13727. },
  13728. enumerable: true,
  13729. configurable: true
  13730. });
  13731. DynamicTexture.prototype.scale = function (ratio) {
  13732. var textureSize = this.getSize();
  13733. textureSize.width *= ratio;
  13734. textureSize.height *= ratio;
  13735. this._canvas.width = textureSize.width;
  13736. this._canvas.height = textureSize.height;
  13737. this.releaseInternalTexture();
  13738. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13739. };
  13740. DynamicTexture.prototype.getContext = function () {
  13741. return this._context;
  13742. };
  13743. DynamicTexture.prototype.clear = function () {
  13744. var size = this.getSize();
  13745. this._context.fillRect(0, 0, size.width, size.height);
  13746. };
  13747. DynamicTexture.prototype.update = function (invertY) {
  13748. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13749. };
  13750. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13751. if (update === void 0) { update = true; }
  13752. var size = this.getSize();
  13753. if (clearColor) {
  13754. this._context.fillStyle = clearColor;
  13755. this._context.fillRect(0, 0, size.width, size.height);
  13756. }
  13757. this._context.font = font;
  13758. if (x === null) {
  13759. var textSize = this._context.measureText(text);
  13760. x = (size.width - textSize.width) / 2;
  13761. }
  13762. this._context.fillStyle = color;
  13763. this._context.fillText(text, x, y);
  13764. if (update) {
  13765. this.update(invertY);
  13766. }
  13767. };
  13768. DynamicTexture.prototype.clone = function () {
  13769. var textureSize = this.getSize();
  13770. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13771. // Base texture
  13772. newTexture.hasAlpha = this.hasAlpha;
  13773. newTexture.level = this.level;
  13774. // Dynamic Texture
  13775. newTexture.wrapU = this.wrapU;
  13776. newTexture.wrapV = this.wrapV;
  13777. return newTexture;
  13778. };
  13779. return DynamicTexture;
  13780. })(BABYLON.Texture);
  13781. BABYLON.DynamicTexture = DynamicTexture;
  13782. })(BABYLON || (BABYLON = {}));
  13783. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13784. var BABYLON;
  13785. (function (BABYLON) {
  13786. var VideoTexture = (function (_super) {
  13787. __extends(VideoTexture, _super);
  13788. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13789. var _this = this;
  13790. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13791. _super.call(this, null, scene, !generateMipMaps, invertY);
  13792. this._autoLaunch = true;
  13793. this.name = name;
  13794. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13795. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13796. var requiredWidth = size.width || size;
  13797. var requiredHeight = size.height || size;
  13798. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13799. var textureSize = this.getSize();
  13800. this.video = document.createElement("video");
  13801. this.video.width = textureSize.width;
  13802. this.video.height = textureSize.height;
  13803. this.video.autoplay = false;
  13804. this.video.loop = true;
  13805. this.video.addEventListener("canplaythrough", function () {
  13806. if (_this._texture) {
  13807. _this._texture.isReady = true;
  13808. }
  13809. });
  13810. urls.forEach(function (url) {
  13811. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13812. var source = document.createElement("source");
  13813. source.src = url;
  13814. _this.video.appendChild(source);
  13815. });
  13816. this._lastUpdate = BABYLON.Tools.Now;
  13817. }
  13818. VideoTexture.prototype.update = function () {
  13819. if (this._autoLaunch) {
  13820. this._autoLaunch = false;
  13821. this.video.play();
  13822. }
  13823. var now = BABYLON.Tools.Now;
  13824. if (now - this._lastUpdate < 15) {
  13825. return false;
  13826. }
  13827. this._lastUpdate = now;
  13828. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13829. return true;
  13830. };
  13831. return VideoTexture;
  13832. })(BABYLON.Texture);
  13833. BABYLON.VideoTexture = VideoTexture;
  13834. })(BABYLON || (BABYLON = {}));
  13835. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13836. (function (BABYLON) {
  13837. var EffectFallbacks = (function () {
  13838. function EffectFallbacks() {
  13839. this._defines = {};
  13840. this._currentRank = 32;
  13841. this._maxRank = -1;
  13842. }
  13843. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13844. if (!this._defines[rank]) {
  13845. if (rank < this._currentRank) {
  13846. this._currentRank = rank;
  13847. }
  13848. if (rank > this._maxRank) {
  13849. this._maxRank = rank;
  13850. }
  13851. this._defines[rank] = new Array();
  13852. }
  13853. this._defines[rank].push(define);
  13854. };
  13855. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13856. get: function () {
  13857. return this._currentRank <= this._maxRank;
  13858. },
  13859. enumerable: true,
  13860. configurable: true
  13861. });
  13862. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13863. var currentFallbacks = this._defines[this._currentRank];
  13864. for (var index = 0; index < currentFallbacks.length; index++) {
  13865. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13866. }
  13867. this._currentRank++;
  13868. return currentDefines;
  13869. };
  13870. return EffectFallbacks;
  13871. })();
  13872. BABYLON.EffectFallbacks = EffectFallbacks;
  13873. var Effect = (function () {
  13874. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13875. var _this = this;
  13876. this._isReady = false;
  13877. this._compilationError = "";
  13878. this._valueCache = [];
  13879. this._engine = engine;
  13880. this.name = baseName;
  13881. this.defines = defines;
  13882. this._uniformsNames = uniformsNames.concat(samplers);
  13883. this._samplers = samplers;
  13884. this._attributesNames = attributesNames;
  13885. this.onError = onError;
  13886. this.onCompiled = onCompiled;
  13887. var vertexSource;
  13888. var fragmentSource;
  13889. if (baseName.vertexElement) {
  13890. vertexSource = document.getElementById(baseName.vertexElement);
  13891. if (!vertexSource) {
  13892. vertexSource = baseName.vertexElement;
  13893. }
  13894. }
  13895. else {
  13896. vertexSource = baseName.vertex || baseName;
  13897. }
  13898. if (baseName.fragmentElement) {
  13899. fragmentSource = document.getElementById(baseName.fragmentElement);
  13900. if (!fragmentSource) {
  13901. fragmentSource = baseName.fragmentElement;
  13902. }
  13903. }
  13904. else {
  13905. fragmentSource = baseName.fragment || baseName;
  13906. }
  13907. this._loadVertexShader(vertexSource, function (vertexCode) {
  13908. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13909. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13910. });
  13911. });
  13912. }
  13913. // Properties
  13914. Effect.prototype.isReady = function () {
  13915. return this._isReady;
  13916. };
  13917. Effect.prototype.getProgram = function () {
  13918. return this._program;
  13919. };
  13920. Effect.prototype.getAttributesNames = function () {
  13921. return this._attributesNames;
  13922. };
  13923. Effect.prototype.getAttributeLocation = function (index) {
  13924. return this._attributes[index];
  13925. };
  13926. Effect.prototype.getAttributeLocationByName = function (name) {
  13927. var index = this._attributesNames.indexOf(name);
  13928. return this._attributes[index];
  13929. };
  13930. Effect.prototype.getAttributesCount = function () {
  13931. return this._attributes.length;
  13932. };
  13933. Effect.prototype.getUniformIndex = function (uniformName) {
  13934. return this._uniformsNames.indexOf(uniformName);
  13935. };
  13936. Effect.prototype.getUniform = function (uniformName) {
  13937. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13938. };
  13939. Effect.prototype.getSamplers = function () {
  13940. return this._samplers;
  13941. };
  13942. Effect.prototype.getCompilationError = function () {
  13943. return this._compilationError;
  13944. };
  13945. // Methods
  13946. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13947. // DOM element ?
  13948. if (vertex instanceof HTMLElement) {
  13949. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13950. callback(vertexCode);
  13951. return;
  13952. }
  13953. // Is in local store ?
  13954. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13955. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13956. return;
  13957. }
  13958. var vertexShaderUrl;
  13959. if (vertex[0] === ".") {
  13960. vertexShaderUrl = vertex;
  13961. }
  13962. else {
  13963. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13964. }
  13965. // Vertex shader
  13966. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13967. };
  13968. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13969. // DOM element ?
  13970. if (fragment instanceof HTMLElement) {
  13971. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13972. callback(fragmentCode);
  13973. return;
  13974. }
  13975. // Is in local store ?
  13976. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13977. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13978. return;
  13979. }
  13980. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13981. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13982. return;
  13983. }
  13984. var fragmentShaderUrl;
  13985. if (fragment[0] === ".") {
  13986. fragmentShaderUrl = fragment;
  13987. }
  13988. else {
  13989. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13990. }
  13991. // Fragment shader
  13992. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13993. };
  13994. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13995. try {
  13996. var engine = this._engine;
  13997. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13998. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13999. this._attributes = engine.getAttributes(this._program, attributesNames);
  14000. for (var index = 0; index < this._samplers.length; index++) {
  14001. var sampler = this.getUniform(this._samplers[index]);
  14002. if (sampler == null) {
  14003. this._samplers.splice(index, 1);
  14004. index--;
  14005. }
  14006. }
  14007. engine.bindSamplers(this);
  14008. this._isReady = true;
  14009. if (this.onCompiled) {
  14010. this.onCompiled(this);
  14011. }
  14012. }
  14013. catch (e) {
  14014. // Is it a problem with precision?
  14015. if (e.message.indexOf("highp") !== -1) {
  14016. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  14017. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  14018. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14019. return;
  14020. }
  14021. // Let's go through fallbacks then
  14022. if (fallbacks && fallbacks.isMoreFallbacks) {
  14023. defines = fallbacks.reduce(defines);
  14024. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  14025. }
  14026. else {
  14027. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  14028. BABYLON.Tools.Error("Defines: " + defines);
  14029. BABYLON.Tools.Error("Error: " + e.message);
  14030. this._compilationError = e.message;
  14031. if (this.onError) {
  14032. this.onError(this, this._compilationError);
  14033. }
  14034. }
  14035. }
  14036. };
  14037. Effect.prototype._bindTexture = function (channel, texture) {
  14038. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  14039. };
  14040. Effect.prototype.setTexture = function (channel, texture) {
  14041. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  14042. };
  14043. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14044. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  14045. };
  14046. //public _cacheMatrix(uniformName, matrix) {
  14047. // if (!this._valueCache[uniformName]) {
  14048. // this._valueCache[uniformName] = new BABYLON.Matrix();
  14049. // }
  14050. // for (var index = 0; index < 16; index++) {
  14051. // this._valueCache[uniformName].m[index] = matrix.m[index];
  14052. // }
  14053. //};
  14054. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  14055. if (!this._valueCache[uniformName]) {
  14056. this._valueCache[uniformName] = [x, y];
  14057. return;
  14058. }
  14059. this._valueCache[uniformName][0] = x;
  14060. this._valueCache[uniformName][1] = y;
  14061. };
  14062. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  14063. if (!this._valueCache[uniformName]) {
  14064. this._valueCache[uniformName] = [x, y, z];
  14065. return;
  14066. }
  14067. this._valueCache[uniformName][0] = x;
  14068. this._valueCache[uniformName][1] = y;
  14069. this._valueCache[uniformName][2] = z;
  14070. };
  14071. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  14072. if (!this._valueCache[uniformName]) {
  14073. this._valueCache[uniformName] = [x, y, z, w];
  14074. return;
  14075. }
  14076. this._valueCache[uniformName][0] = x;
  14077. this._valueCache[uniformName][1] = y;
  14078. this._valueCache[uniformName][2] = z;
  14079. this._valueCache[uniformName][3] = w;
  14080. };
  14081. Effect.prototype.setArray = function (uniformName, array) {
  14082. this._engine.setArray(this.getUniform(uniformName), array);
  14083. return this;
  14084. };
  14085. Effect.prototype.setArray2 = function (uniformName, array) {
  14086. this._engine.setArray2(this.getUniform(uniformName), array);
  14087. return this;
  14088. };
  14089. Effect.prototype.setArray3 = function (uniformName, array) {
  14090. this._engine.setArray3(this.getUniform(uniformName), array);
  14091. return this;
  14092. };
  14093. Effect.prototype.setArray4 = function (uniformName, array) {
  14094. this._engine.setArray4(this.getUniform(uniformName), array);
  14095. return this;
  14096. };
  14097. Effect.prototype.setMatrices = function (uniformName, matrices) {
  14098. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  14099. return this;
  14100. };
  14101. Effect.prototype.setMatrix = function (uniformName, matrix) {
  14102. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  14103. // return;
  14104. //this._cacheMatrix(uniformName, matrix);
  14105. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  14106. return this;
  14107. };
  14108. Effect.prototype.setFloat = function (uniformName, value) {
  14109. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  14110. return this;
  14111. this._valueCache[uniformName] = value;
  14112. this._engine.setFloat(this.getUniform(uniformName), value);
  14113. return this;
  14114. };
  14115. Effect.prototype.setBool = function (uniformName, bool) {
  14116. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  14117. return this;
  14118. this._valueCache[uniformName] = bool;
  14119. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  14120. return this;
  14121. };
  14122. Effect.prototype.setVector2 = function (uniformName, vector2) {
  14123. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  14124. return this;
  14125. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  14126. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  14127. return this;
  14128. };
  14129. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  14130. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  14131. return this;
  14132. this._cacheFloat2(uniformName, x, y);
  14133. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  14134. return this;
  14135. };
  14136. Effect.prototype.setVector3 = function (uniformName, vector3) {
  14137. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  14138. return this;
  14139. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  14140. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  14141. return this;
  14142. };
  14143. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  14144. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  14145. return this;
  14146. this._cacheFloat3(uniformName, x, y, z);
  14147. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  14148. return this;
  14149. };
  14150. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  14151. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  14152. return this;
  14153. this._cacheFloat4(uniformName, x, y, z, w);
  14154. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  14155. return this;
  14156. };
  14157. Effect.prototype.setColor3 = function (uniformName, color3) {
  14158. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  14159. return this;
  14160. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  14161. this._engine.setColor3(this.getUniform(uniformName), color3);
  14162. return this;
  14163. };
  14164. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  14165. 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)
  14166. return this;
  14167. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  14168. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  14169. return this;
  14170. };
  14171. // Statics
  14172. 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}",
  14173. 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}",
  14174. 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}",
  14175. 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}",
  14176. 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}",
  14177. 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}",
  14178. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  14179. 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}",
  14180. 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}",
  14181. 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}",
  14182. 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 if (t - bias <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, 0.002);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05, 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}",
  14183. 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}",
  14184. 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}",
  14185. 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#if defined(ALPHATEST) || defined(NEED_UV)\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#if defined(ALPHATEST) || defined(BASIC_RENDER)\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}",
  14186. 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}",
  14187. 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}",
  14188. 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}",
  14189. 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}",
  14190. 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}",
  14191. 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}",
  14192. 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}",
  14193. 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}",
  14194. 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}",
  14195. 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}",
  14196. 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}",
  14197. 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}",
  14198. 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}",
  14199. 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}",
  14200. 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}",
  14201. 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}",
  14202. 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}",
  14203. 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}",
  14204. 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}",
  14205. 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}",
  14206. 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}",
  14207. 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}",
  14208. 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}",
  14209. 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}",
  14210. 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}",
  14211. 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}",
  14212. 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}",
  14213. 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}",
  14214. 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}",
  14215. 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}",
  14216. 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}",
  14217. 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;\nuniform float opacityLevel;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || 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 OPACITY\n vec4 opacityColor = texture2D(opacitySampler, vUV);\n float alpha = 1.0;\n\n #ifdef OPACITYRGB\n opacityColor.rgb = opacityColor.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityColor.x + opacityColor.y + opacityColor.z) * opacityLevel;\n #else\n alpha *= opacityColor.a * opacityLevel;\n #endif\n\n #if defined(BASIC_RENDER)\n gl_FragColor = vec4(diffuseColor.rgb, alpha);\n #else\n gl_FragColor = vec4(0.0, 0.0, 0.0, alpha);\n #endif\n\n gl_FragColor.a = alpha;\n#else\n #ifndef BASIC_RENDER\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#endif\n\n}",
  14218. 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}",
  14219. };
  14220. return Effect;
  14221. })();
  14222. BABYLON.Effect = Effect;
  14223. })(BABYLON || (BABYLON = {}));
  14224. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  14225. (function (BABYLON) {
  14226. var Material = (function () {
  14227. function Material(name, scene, doNotAdd) {
  14228. this.name = name;
  14229. this.checkReadyOnEveryCall = true;
  14230. this.checkReadyOnlyOnce = false;
  14231. this.state = "";
  14232. this.alpha = 1.0;
  14233. this.backFaceCulling = true;
  14234. this._wasPreviouslyReady = false;
  14235. this._fillMode = Material.TriangleFillMode;
  14236. this.pointSize = 1.0;
  14237. this.id = name;
  14238. this._scene = scene;
  14239. if (!doNotAdd) {
  14240. scene.materials.push(this);
  14241. }
  14242. }
  14243. Object.defineProperty(Material, "TriangleFillMode", {
  14244. get: function () {
  14245. return Material._TriangleFillMode;
  14246. },
  14247. enumerable: true,
  14248. configurable: true
  14249. });
  14250. Object.defineProperty(Material, "WireFrameFillMode", {
  14251. get: function () {
  14252. return Material._WireFrameFillMode;
  14253. },
  14254. enumerable: true,
  14255. configurable: true
  14256. });
  14257. Object.defineProperty(Material, "PointFillMode", {
  14258. get: function () {
  14259. return Material._PointFillMode;
  14260. },
  14261. enumerable: true,
  14262. configurable: true
  14263. });
  14264. Object.defineProperty(Material.prototype, "wireframe", {
  14265. get: function () {
  14266. return this._fillMode === Material.WireFrameFillMode;
  14267. },
  14268. set: function (value) {
  14269. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  14270. },
  14271. enumerable: true,
  14272. configurable: true
  14273. });
  14274. Object.defineProperty(Material.prototype, "pointsCloud", {
  14275. get: function () {
  14276. return this._fillMode === Material.PointFillMode;
  14277. },
  14278. set: function (value) {
  14279. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  14280. },
  14281. enumerable: true,
  14282. configurable: true
  14283. });
  14284. Object.defineProperty(Material.prototype, "fillMode", {
  14285. get: function () {
  14286. return this._fillMode;
  14287. },
  14288. set: function (value) {
  14289. this._fillMode = value;
  14290. },
  14291. enumerable: true,
  14292. configurable: true
  14293. });
  14294. Material.prototype.isReady = function (mesh, useInstances) {
  14295. return true;
  14296. };
  14297. Material.prototype.getEffect = function () {
  14298. return this._effect;
  14299. };
  14300. Material.prototype.getScene = function () {
  14301. return this._scene;
  14302. };
  14303. Material.prototype.needAlphaBlending = function () {
  14304. return (this.alpha < 1.0);
  14305. };
  14306. Material.prototype.needAlphaTesting = function () {
  14307. return false;
  14308. };
  14309. Material.prototype.getAlphaTestTexture = function () {
  14310. return null;
  14311. };
  14312. Material.prototype.trackCreation = function (onCompiled, onError) {
  14313. };
  14314. Material.prototype._preBind = function () {
  14315. var engine = this._scene.getEngine();
  14316. engine.enableEffect(this._effect);
  14317. engine.setState(this.backFaceCulling);
  14318. };
  14319. Material.prototype.bind = function (world, mesh) {
  14320. this._scene._cachedMaterial = this;
  14321. if (this.onBind) {
  14322. this.onBind(this);
  14323. }
  14324. };
  14325. Material.prototype.bindOnlyWorldMatrix = function (world) {
  14326. };
  14327. Material.prototype.unbind = function () {
  14328. };
  14329. Material.prototype.dispose = function (forceDisposeEffect) {
  14330. // Remove from scene
  14331. var index = this._scene.materials.indexOf(this);
  14332. this._scene.materials.splice(index, 1);
  14333. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  14334. if (forceDisposeEffect && this._effect) {
  14335. this._scene.getEngine()._releaseEffect(this._effect);
  14336. this._effect = null;
  14337. }
  14338. // Callback
  14339. if (this.onDispose) {
  14340. this.onDispose();
  14341. }
  14342. };
  14343. Material._TriangleFillMode = 0;
  14344. Material._WireFrameFillMode = 1;
  14345. Material._PointFillMode = 2;
  14346. return Material;
  14347. })();
  14348. BABYLON.Material = Material;
  14349. })(BABYLON || (BABYLON = {}));
  14350. //# sourceMappingURL=babylon.material.js.map
  14351. var BABYLON;
  14352. (function (BABYLON) {
  14353. var maxSimultaneousLights = 4;
  14354. var FresnelParameters = (function () {
  14355. function FresnelParameters() {
  14356. this.isEnabled = true;
  14357. this.leftColor = BABYLON.Color3.White();
  14358. this.rightColor = BABYLON.Color3.Black();
  14359. this.bias = 0;
  14360. this.power = 1;
  14361. }
  14362. return FresnelParameters;
  14363. })();
  14364. BABYLON.FresnelParameters = FresnelParameters;
  14365. var StandardMaterial = (function (_super) {
  14366. __extends(StandardMaterial, _super);
  14367. function StandardMaterial(name, scene) {
  14368. var _this = this;
  14369. _super.call(this, name, scene);
  14370. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14371. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14372. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14373. this.specularPower = 64;
  14374. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14375. this.useAlphaFromDiffuseTexture = false;
  14376. this.useSpecularOverAlpha = true;
  14377. this.fogEnabled = true;
  14378. this._cachedDefines = null;
  14379. this._renderTargets = new BABYLON.SmartArray(16);
  14380. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14381. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14382. this._scaledDiffuse = new BABYLON.Color3();
  14383. this._scaledSpecular = new BABYLON.Color3();
  14384. this.getRenderTargetTextures = function () {
  14385. _this._renderTargets.reset();
  14386. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14387. _this._renderTargets.push(_this.reflectionTexture);
  14388. }
  14389. return _this._renderTargets;
  14390. };
  14391. }
  14392. StandardMaterial.prototype.needAlphaBlending = function () {
  14393. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14394. };
  14395. StandardMaterial.prototype.needAlphaTesting = function () {
  14396. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14397. };
  14398. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14399. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14400. };
  14401. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14402. return this.diffuseTexture;
  14403. };
  14404. // Methods
  14405. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14406. if (this.checkReadyOnlyOnce) {
  14407. if (this._wasPreviouslyReady) {
  14408. return true;
  14409. }
  14410. }
  14411. var scene = this.getScene();
  14412. if (!this.checkReadyOnEveryCall) {
  14413. if (this._renderId === scene.getRenderId()) {
  14414. return true;
  14415. }
  14416. }
  14417. var engine = scene.getEngine();
  14418. var defines = [];
  14419. var fallbacks = new BABYLON.EffectFallbacks();
  14420. var needNormals = false;
  14421. var needUVs = false;
  14422. // Textures
  14423. if (scene.texturesEnabled) {
  14424. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14425. if (!this.diffuseTexture.isReady()) {
  14426. return false;
  14427. }
  14428. else {
  14429. needUVs = true;
  14430. defines.push("#define DIFFUSE");
  14431. }
  14432. }
  14433. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14434. if (!this.ambientTexture.isReady()) {
  14435. return false;
  14436. }
  14437. else {
  14438. needUVs = true;
  14439. defines.push("#define AMBIENT");
  14440. }
  14441. }
  14442. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14443. if (!this.opacityTexture.isReady()) {
  14444. return false;
  14445. }
  14446. else {
  14447. needUVs = true;
  14448. defines.push("#define OPACITY");
  14449. if (this.opacityTexture.getAlphaFromRGB) {
  14450. defines.push("#define OPACITYRGB");
  14451. }
  14452. }
  14453. }
  14454. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14455. if (!this.reflectionTexture.isReady()) {
  14456. return false;
  14457. }
  14458. else {
  14459. needNormals = true;
  14460. needUVs = true;
  14461. defines.push("#define REFLECTION");
  14462. fallbacks.addFallback(0, "REFLECTION");
  14463. }
  14464. }
  14465. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14466. if (!this.emissiveTexture.isReady()) {
  14467. return false;
  14468. }
  14469. else {
  14470. needUVs = true;
  14471. defines.push("#define EMISSIVE");
  14472. }
  14473. }
  14474. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14475. if (!this.specularTexture.isReady()) {
  14476. return false;
  14477. }
  14478. else {
  14479. needUVs = true;
  14480. defines.push("#define SPECULAR");
  14481. fallbacks.addFallback(0, "SPECULAR");
  14482. }
  14483. }
  14484. }
  14485. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14486. if (!this.bumpTexture.isReady()) {
  14487. return false;
  14488. }
  14489. else {
  14490. needUVs = true;
  14491. defines.push("#define BUMP");
  14492. fallbacks.addFallback(0, "BUMP");
  14493. }
  14494. }
  14495. // Effect
  14496. if (this.useSpecularOverAlpha) {
  14497. defines.push("#define SPECULAROVERALPHA");
  14498. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14499. }
  14500. if (scene.clipPlane) {
  14501. defines.push("#define CLIPPLANE");
  14502. }
  14503. if (engine.getAlphaTesting()) {
  14504. defines.push("#define ALPHATEST");
  14505. }
  14506. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14507. defines.push("#define ALPHAFROMDIFFUSE");
  14508. }
  14509. // Point size
  14510. if (this.pointsCloud || scene.forcePointsCloud) {
  14511. defines.push("#define POINTSIZE");
  14512. }
  14513. // Fog
  14514. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14515. defines.push("#define FOG");
  14516. fallbacks.addFallback(1, "FOG");
  14517. }
  14518. var shadowsActivated = false;
  14519. var lightIndex = 0;
  14520. if (scene.lightsEnabled) {
  14521. for (var index = 0; index < scene.lights.length; index++) {
  14522. var light = scene.lights[index];
  14523. if (!light.isEnabled()) {
  14524. continue;
  14525. }
  14526. // Excluded check
  14527. if (light._excludedMeshesIds.length > 0) {
  14528. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14529. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14530. if (excludedMesh) {
  14531. light.excludedMeshes.push(excludedMesh);
  14532. }
  14533. }
  14534. light._excludedMeshesIds = [];
  14535. }
  14536. // Included check
  14537. if (light._includedOnlyMeshesIds.length > 0) {
  14538. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14539. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14540. if (includedOnlyMesh) {
  14541. light.includedOnlyMeshes.push(includedOnlyMesh);
  14542. }
  14543. }
  14544. light._includedOnlyMeshesIds = [];
  14545. }
  14546. if (!light.canAffectMesh(mesh)) {
  14547. continue;
  14548. }
  14549. needNormals = true;
  14550. defines.push("#define LIGHT" + lightIndex);
  14551. if (lightIndex > 0) {
  14552. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14553. }
  14554. var type;
  14555. if (light instanceof BABYLON.SpotLight) {
  14556. type = "#define SPOTLIGHT" + lightIndex;
  14557. }
  14558. else if (light instanceof BABYLON.HemisphericLight) {
  14559. type = "#define HEMILIGHT" + lightIndex;
  14560. }
  14561. else {
  14562. type = "#define POINTDIRLIGHT" + lightIndex;
  14563. }
  14564. defines.push(type);
  14565. if (lightIndex > 0) {
  14566. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14567. }
  14568. // Shadows
  14569. if (scene.shadowsEnabled) {
  14570. var shadowGenerator = light.getShadowGenerator();
  14571. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14572. defines.push("#define SHADOW" + lightIndex);
  14573. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14574. if (!shadowsActivated) {
  14575. defines.push("#define SHADOWS");
  14576. shadowsActivated = true;
  14577. }
  14578. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14579. defines.push("#define SHADOWVSM" + lightIndex);
  14580. if (lightIndex > 0) {
  14581. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14582. }
  14583. }
  14584. if (shadowGenerator.usePoissonSampling) {
  14585. defines.push("#define SHADOWPCF" + lightIndex);
  14586. if (lightIndex > 0) {
  14587. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14588. }
  14589. }
  14590. }
  14591. }
  14592. lightIndex++;
  14593. if (lightIndex === maxSimultaneousLights)
  14594. break;
  14595. }
  14596. }
  14597. if (StandardMaterial.FresnelEnabled) {
  14598. // Fresnel
  14599. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14600. var fresnelRank = 1;
  14601. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14602. defines.push("#define DIFFUSEFRESNEL");
  14603. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14604. fresnelRank++;
  14605. }
  14606. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14607. defines.push("#define OPACITYFRESNEL");
  14608. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14609. fresnelRank++;
  14610. }
  14611. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14612. defines.push("#define REFLECTIONFRESNEL");
  14613. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14614. fresnelRank++;
  14615. }
  14616. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14617. defines.push("#define EMISSIVEFRESNEL");
  14618. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14619. fresnelRank++;
  14620. }
  14621. needNormals = true;
  14622. defines.push("#define FRESNEL");
  14623. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14624. }
  14625. }
  14626. // Attribs
  14627. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14628. if (mesh) {
  14629. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14630. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14631. defines.push("#define NORMAL");
  14632. }
  14633. if (needUVs) {
  14634. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14635. attribs.push(BABYLON.VertexBuffer.UVKind);
  14636. defines.push("#define UV1");
  14637. }
  14638. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14639. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14640. defines.push("#define UV2");
  14641. }
  14642. }
  14643. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14644. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14645. defines.push("#define VERTEXCOLOR");
  14646. if (mesh.hasVertexAlpha) {
  14647. defines.push("#define VERTEXALPHA");
  14648. }
  14649. }
  14650. if (mesh.useBones) {
  14651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14653. defines.push("#define BONES");
  14654. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14655. defines.push("#define BONES4");
  14656. fallbacks.addFallback(0, "BONES4");
  14657. }
  14658. // Instances
  14659. if (useInstances) {
  14660. defines.push("#define INSTANCES");
  14661. attribs.push("world0");
  14662. attribs.push("world1");
  14663. attribs.push("world2");
  14664. attribs.push("world3");
  14665. }
  14666. }
  14667. // Get correct effect
  14668. var join = defines.join("\n");
  14669. if (this._cachedDefines !== join) {
  14670. this._cachedDefines = join;
  14671. scene.resetCachedMaterial();
  14672. // Legacy browser patch
  14673. var shaderName = "default";
  14674. if (!scene.getEngine().getCaps().standardDerivatives) {
  14675. shaderName = "legacydefault";
  14676. }
  14677. 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);
  14678. }
  14679. if (!this._effect.isReady()) {
  14680. return false;
  14681. }
  14682. this._renderId = scene.getRenderId();
  14683. this._wasPreviouslyReady = true;
  14684. return true;
  14685. };
  14686. StandardMaterial.prototype.unbind = function () {
  14687. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14688. this._effect.setTexture("reflection2DSampler", null);
  14689. }
  14690. };
  14691. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14692. this._effect.setMatrix("world", world);
  14693. };
  14694. StandardMaterial.prototype.bind = function (world, mesh) {
  14695. var scene = this.getScene();
  14696. // Matrices
  14697. this.bindOnlyWorldMatrix(world);
  14698. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14699. // Bones
  14700. if (mesh.useBones) {
  14701. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14702. }
  14703. if (scene.getCachedMaterial() !== this) {
  14704. if (StandardMaterial.FresnelEnabled) {
  14705. // Fresnel
  14706. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14707. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14708. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14709. }
  14710. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14711. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14712. }
  14713. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14714. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14715. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14716. }
  14717. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14718. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14719. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14720. }
  14721. }
  14722. // Textures
  14723. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14724. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14725. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14726. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14727. }
  14728. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14729. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14730. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14731. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14732. }
  14733. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14734. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14735. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14736. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14737. }
  14738. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14739. if (this.reflectionTexture.isCube) {
  14740. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14741. }
  14742. else {
  14743. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14744. }
  14745. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14746. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14747. }
  14748. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14749. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14750. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14751. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14752. }
  14753. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14754. this._effect.setTexture("specularSampler", this.specularTexture);
  14755. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14756. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14757. }
  14758. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14759. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14760. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14761. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14762. }
  14763. // Clip plane
  14764. if (scene.clipPlane) {
  14765. var clipPlane = scene.clipPlane;
  14766. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14767. }
  14768. // Point size
  14769. if (this.pointsCloud) {
  14770. this._effect.setFloat("pointSize", this.pointSize);
  14771. }
  14772. // Colors
  14773. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14774. // Scaling down color according to emissive
  14775. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14776. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14777. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14778. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14779. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14780. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14781. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14782. }
  14783. // Scaling down color according to emissive
  14784. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14785. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14786. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14787. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14788. if (scene.lightsEnabled) {
  14789. var lightIndex = 0;
  14790. for (var index = 0; index < scene.lights.length; index++) {
  14791. var light = scene.lights[index];
  14792. if (!light.isEnabled()) {
  14793. continue;
  14794. }
  14795. if (!light.canAffectMesh(mesh)) {
  14796. continue;
  14797. }
  14798. if (light instanceof BABYLON.PointLight) {
  14799. // Point Light
  14800. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14801. }
  14802. else if (light instanceof BABYLON.DirectionalLight) {
  14803. // Directional Light
  14804. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14805. }
  14806. else if (light instanceof BABYLON.SpotLight) {
  14807. // Spot Light
  14808. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14809. }
  14810. else if (light instanceof BABYLON.HemisphericLight) {
  14811. // Hemispheric Light
  14812. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14813. }
  14814. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14815. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14816. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14817. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14818. // Shadows
  14819. if (scene.shadowsEnabled) {
  14820. var shadowGenerator = light.getShadowGenerator();
  14821. if (mesh.receiveShadows && shadowGenerator) {
  14822. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14823. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14824. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14825. }
  14826. }
  14827. lightIndex++;
  14828. if (lightIndex === maxSimultaneousLights)
  14829. break;
  14830. }
  14831. }
  14832. // View
  14833. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14834. this._effect.setMatrix("view", scene.getViewMatrix());
  14835. }
  14836. // Fog
  14837. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14838. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14839. this._effect.setColor3("vFogColor", scene.fogColor);
  14840. }
  14841. _super.prototype.bind.call(this, world, mesh);
  14842. };
  14843. StandardMaterial.prototype.getAnimatables = function () {
  14844. var results = [];
  14845. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14846. results.push(this.diffuseTexture);
  14847. }
  14848. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14849. results.push(this.ambientTexture);
  14850. }
  14851. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14852. results.push(this.opacityTexture);
  14853. }
  14854. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14855. results.push(this.reflectionTexture);
  14856. }
  14857. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14858. results.push(this.emissiveTexture);
  14859. }
  14860. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14861. results.push(this.specularTexture);
  14862. }
  14863. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14864. results.push(this.bumpTexture);
  14865. }
  14866. return results;
  14867. };
  14868. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14869. if (this.diffuseTexture) {
  14870. this.diffuseTexture.dispose();
  14871. }
  14872. if (this.ambientTexture) {
  14873. this.ambientTexture.dispose();
  14874. }
  14875. if (this.opacityTexture) {
  14876. this.opacityTexture.dispose();
  14877. }
  14878. if (this.reflectionTexture) {
  14879. this.reflectionTexture.dispose();
  14880. }
  14881. if (this.emissiveTexture) {
  14882. this.emissiveTexture.dispose();
  14883. }
  14884. if (this.specularTexture) {
  14885. this.specularTexture.dispose();
  14886. }
  14887. if (this.bumpTexture) {
  14888. this.bumpTexture.dispose();
  14889. }
  14890. _super.prototype.dispose.call(this, forceDisposeEffect);
  14891. };
  14892. StandardMaterial.prototype.clone = function (name) {
  14893. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14894. // Base material
  14895. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14896. newStandardMaterial.alpha = this.alpha;
  14897. newStandardMaterial.fillMode = this.fillMode;
  14898. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14899. // Standard material
  14900. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14901. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14902. }
  14903. if (this.ambientTexture && this.ambientTexture.clone) {
  14904. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14905. }
  14906. if (this.opacityTexture && this.opacityTexture.clone) {
  14907. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14908. }
  14909. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14910. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14911. }
  14912. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14913. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14914. }
  14915. if (this.specularTexture && this.specularTexture.clone) {
  14916. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14917. }
  14918. if (this.bumpTexture && this.bumpTexture.clone) {
  14919. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14920. }
  14921. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14922. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14923. newStandardMaterial.specularColor = this.specularColor.clone();
  14924. newStandardMaterial.specularPower = this.specularPower;
  14925. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14926. return newStandardMaterial;
  14927. };
  14928. // Statics
  14929. // Flags used to enable or disable a type of texture for all Standard Materials
  14930. StandardMaterial.DiffuseTextureEnabled = true;
  14931. StandardMaterial.AmbientTextureEnabled = true;
  14932. StandardMaterial.OpacityTextureEnabled = true;
  14933. StandardMaterial.ReflectionTextureEnabled = true;
  14934. StandardMaterial.EmissiveTextureEnabled = true;
  14935. StandardMaterial.SpecularTextureEnabled = true;
  14936. StandardMaterial.BumpTextureEnabled = true;
  14937. StandardMaterial.FresnelEnabled = true;
  14938. return StandardMaterial;
  14939. })(BABYLON.Material);
  14940. BABYLON.StandardMaterial = StandardMaterial;
  14941. })(BABYLON || (BABYLON = {}));
  14942. //# sourceMappingURL=babylon.standardMaterial.js.map
  14943. var BABYLON;
  14944. (function (BABYLON) {
  14945. var MultiMaterial = (function (_super) {
  14946. __extends(MultiMaterial, _super);
  14947. function MultiMaterial(name, scene) {
  14948. _super.call(this, name, scene, true);
  14949. this.subMaterials = new Array();
  14950. scene.multiMaterials.push(this);
  14951. }
  14952. // Properties
  14953. MultiMaterial.prototype.getSubMaterial = function (index) {
  14954. if (index < 0 || index >= this.subMaterials.length) {
  14955. return this.getScene().defaultMaterial;
  14956. }
  14957. return this.subMaterials[index];
  14958. };
  14959. // Methods
  14960. MultiMaterial.prototype.isReady = function (mesh) {
  14961. for (var index = 0; index < this.subMaterials.length; index++) {
  14962. var subMaterial = this.subMaterials[index];
  14963. if (subMaterial) {
  14964. if (!this.subMaterials[index].isReady(mesh)) {
  14965. return false;
  14966. }
  14967. }
  14968. }
  14969. return true;
  14970. };
  14971. return MultiMaterial;
  14972. })(BABYLON.Material);
  14973. BABYLON.MultiMaterial = MultiMaterial;
  14974. })(BABYLON || (BABYLON = {}));
  14975. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14976. (function (BABYLON) {
  14977. var Database = (function () {
  14978. function Database(urlToScene, callbackManifestChecked) {
  14979. // Handling various flavors of prefixed version of IndexedDB
  14980. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14981. this.callbackManifestChecked = callbackManifestChecked;
  14982. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14983. this.db = null;
  14984. this.enableSceneOffline = false;
  14985. this.enableTexturesOffline = false;
  14986. this.manifestVersionFound = 0;
  14987. this.mustUpdateRessources = false;
  14988. this.hasReachedQuota = false;
  14989. this.checkManifestFile();
  14990. }
  14991. Database.prototype.checkManifestFile = function () {
  14992. var _this = this;
  14993. function noManifestFile() {
  14994. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14995. that.enableSceneOffline = false;
  14996. that.enableTexturesOffline = false;
  14997. that.callbackManifestChecked(false);
  14998. }
  14999. var that = this;
  15000. var manifestURL = this.currentSceneUrl + ".manifest";
  15001. var xhr = new XMLHttpRequest();
  15002. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  15003. xhr.open("GET", manifestURLTimeStamped, true);
  15004. xhr.addEventListener("load", function () {
  15005. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  15006. try {
  15007. var manifestFile = JSON.parse(xhr.response);
  15008. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  15009. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  15010. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  15011. _this.manifestVersionFound = manifestFile.version;
  15012. }
  15013. if (_this.callbackManifestChecked) {
  15014. _this.callbackManifestChecked(true);
  15015. }
  15016. }
  15017. catch (ex) {
  15018. noManifestFile();
  15019. }
  15020. }
  15021. else {
  15022. noManifestFile();
  15023. }
  15024. }, false);
  15025. xhr.addEventListener("error", function (event) {
  15026. noManifestFile();
  15027. }, false);
  15028. try {
  15029. xhr.send();
  15030. }
  15031. catch (ex) {
  15032. BABYLON.Tools.Error("Error on XHR send request.");
  15033. that.callbackManifestChecked(false);
  15034. }
  15035. };
  15036. Database.prototype.openAsync = function (successCallback, errorCallback) {
  15037. var _this = this;
  15038. function handleError() {
  15039. that.isSupported = false;
  15040. if (errorCallback)
  15041. errorCallback();
  15042. }
  15043. var that = this;
  15044. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  15045. // Your browser doesn't support IndexedDB
  15046. this.isSupported = false;
  15047. if (errorCallback)
  15048. errorCallback();
  15049. }
  15050. else {
  15051. // If the DB hasn't been opened or created yet
  15052. if (!this.db) {
  15053. this.hasReachedQuota = false;
  15054. this.isSupported = true;
  15055. var request = this.idbFactory.open("babylonjs", 1);
  15056. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  15057. request.onerror = function (event) {
  15058. handleError();
  15059. };
  15060. // executes when a version change transaction cannot complete due to other active transactions
  15061. request.onblocked = function (event) {
  15062. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  15063. handleError();
  15064. };
  15065. // DB has been opened successfully
  15066. request.onsuccess = function (event) {
  15067. _this.db = request.result;
  15068. successCallback();
  15069. };
  15070. // Initialization of the DB. Creating Scenes & Textures stores
  15071. request.onupgradeneeded = function (event) {
  15072. _this.db = (event.target).result;
  15073. try {
  15074. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  15075. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  15076. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  15077. }
  15078. catch (ex) {
  15079. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  15080. handleError();
  15081. }
  15082. };
  15083. }
  15084. else {
  15085. if (successCallback)
  15086. successCallback();
  15087. }
  15088. }
  15089. };
  15090. Database.prototype.loadImageFromDB = function (url, image) {
  15091. var _this = this;
  15092. var completeURL = Database.ReturnFullUrlLocation(url);
  15093. var saveAndLoadImage = function () {
  15094. if (!_this.hasReachedQuota && _this.db !== null) {
  15095. // the texture is not yet in the DB, let's try to save it
  15096. _this._saveImageIntoDBAsync(completeURL, image);
  15097. }
  15098. else {
  15099. image.src = url;
  15100. }
  15101. };
  15102. if (!this.mustUpdateRessources) {
  15103. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  15104. }
  15105. else {
  15106. saveAndLoadImage();
  15107. }
  15108. };
  15109. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  15110. if (this.isSupported && this.db !== null) {
  15111. var texture;
  15112. var transaction = this.db.transaction(["textures"]);
  15113. transaction.onabort = function (event) {
  15114. image.src = url;
  15115. };
  15116. transaction.oncomplete = function (event) {
  15117. var blobTextureURL;
  15118. if (texture) {
  15119. var URL = window.URL || window.webkitURL;
  15120. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  15121. image.onerror = function () {
  15122. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  15123. image.src = url;
  15124. };
  15125. image.src = blobTextureURL;
  15126. }
  15127. else {
  15128. notInDBCallback();
  15129. }
  15130. };
  15131. var getRequest = transaction.objectStore("textures").get(url);
  15132. getRequest.onsuccess = function (event) {
  15133. texture = (event.target).result;
  15134. };
  15135. getRequest.onerror = function (event) {
  15136. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  15137. image.src = url;
  15138. };
  15139. }
  15140. else {
  15141. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15142. image.src = url;
  15143. }
  15144. };
  15145. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  15146. var _this = this;
  15147. if (this.isSupported) {
  15148. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  15149. var generateBlobUrl = function () {
  15150. var blobTextureURL;
  15151. if (blob) {
  15152. var URL = window.URL || window.webkitURL;
  15153. try {
  15154. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  15155. }
  15156. catch (ex) {
  15157. blobTextureURL = URL.createObjectURL(blob);
  15158. }
  15159. }
  15160. image.src = blobTextureURL;
  15161. };
  15162. if (Database.isUASupportingBlobStorage) {
  15163. var xhr = new XMLHttpRequest(), blob;
  15164. xhr.open("GET", url, true);
  15165. xhr.responseType = "blob";
  15166. xhr.addEventListener("load", function () {
  15167. if (xhr.status === 200) {
  15168. // Blob as response (XHR2)
  15169. blob = xhr.response;
  15170. var transaction = _this.db.transaction(["textures"], "readwrite");
  15171. // the transaction could abort because of a QuotaExceededError error
  15172. transaction.onabort = function (event) {
  15173. try {
  15174. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15175. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15176. this.hasReachedQuota = true;
  15177. }
  15178. }
  15179. catch (ex) {
  15180. }
  15181. generateBlobUrl();
  15182. };
  15183. transaction.oncomplete = function (event) {
  15184. generateBlobUrl();
  15185. };
  15186. var newTexture = { textureUrl: url, data: blob };
  15187. try {
  15188. // Put the blob into the dabase
  15189. var addRequest = transaction.objectStore("textures").put(newTexture);
  15190. addRequest.onsuccess = function (event) {
  15191. };
  15192. addRequest.onerror = function (event) {
  15193. generateBlobUrl();
  15194. };
  15195. }
  15196. catch (ex) {
  15197. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  15198. if (ex.code === 25) {
  15199. Database.isUASupportingBlobStorage = false;
  15200. }
  15201. image.src = url;
  15202. }
  15203. }
  15204. else {
  15205. image.src = url;
  15206. }
  15207. }, false);
  15208. xhr.addEventListener("error", function (event) {
  15209. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  15210. image.src = url;
  15211. }, false);
  15212. xhr.send();
  15213. }
  15214. else {
  15215. image.src = url;
  15216. }
  15217. }
  15218. else {
  15219. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15220. image.src = url;
  15221. }
  15222. };
  15223. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  15224. var _this = this;
  15225. var updateVersion = function (event) {
  15226. // the version is not yet in the DB or we need to update it
  15227. _this._saveVersionIntoDBAsync(url, versionLoaded);
  15228. };
  15229. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  15230. };
  15231. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  15232. var _this = this;
  15233. if (this.isSupported) {
  15234. var version;
  15235. try {
  15236. var transaction = this.db.transaction(["versions"]);
  15237. transaction.oncomplete = function (event) {
  15238. if (version) {
  15239. // If the version in the JSON file is > than the version in DB
  15240. if (_this.manifestVersionFound > version.data) {
  15241. _this.mustUpdateRessources = true;
  15242. updateInDBCallback();
  15243. }
  15244. else {
  15245. callback(version.data);
  15246. }
  15247. }
  15248. else {
  15249. _this.mustUpdateRessources = true;
  15250. updateInDBCallback();
  15251. }
  15252. };
  15253. transaction.onabort = function (event) {
  15254. callback(-1);
  15255. };
  15256. var getRequest = transaction.objectStore("versions").get(url);
  15257. getRequest.onsuccess = function (event) {
  15258. version = (event.target).result;
  15259. };
  15260. getRequest.onerror = function (event) {
  15261. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  15262. callback(-1);
  15263. };
  15264. }
  15265. catch (ex) {
  15266. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  15267. callback(-1);
  15268. }
  15269. }
  15270. else {
  15271. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15272. callback(-1);
  15273. }
  15274. };
  15275. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  15276. var _this = this;
  15277. if (this.isSupported && !this.hasReachedQuota) {
  15278. try {
  15279. // Open a transaction to the database
  15280. var transaction = this.db.transaction(["versions"], "readwrite");
  15281. // the transaction could abort because of a QuotaExceededError error
  15282. transaction.onabort = function (event) {
  15283. try {
  15284. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15285. _this.hasReachedQuota = true;
  15286. }
  15287. }
  15288. catch (ex) {
  15289. }
  15290. callback(-1);
  15291. };
  15292. transaction.oncomplete = function (event) {
  15293. callback(_this.manifestVersionFound);
  15294. };
  15295. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  15296. // Put the scene into the database
  15297. var addRequest = transaction.objectStore("versions").put(newVersion);
  15298. addRequest.onsuccess = function (event) {
  15299. };
  15300. addRequest.onerror = function (event) {
  15301. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  15302. };
  15303. }
  15304. catch (ex) {
  15305. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  15306. callback(-1);
  15307. }
  15308. }
  15309. else {
  15310. callback(-1);
  15311. }
  15312. };
  15313. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  15314. var _this = this;
  15315. var completeUrl = Database.ReturnFullUrlLocation(url);
  15316. var saveAndLoadFile = function (event) {
  15317. // the scene is not yet in the DB, let's try to save it
  15318. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  15319. };
  15320. this._checkVersionFromDB(completeUrl, function (version) {
  15321. if (version !== -1) {
  15322. if (!_this.mustUpdateRessources) {
  15323. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  15324. }
  15325. else {
  15326. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  15327. }
  15328. }
  15329. else {
  15330. errorCallback();
  15331. }
  15332. });
  15333. };
  15334. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  15335. if (this.isSupported) {
  15336. var targetStore;
  15337. if (url.indexOf(".babylon") !== -1) {
  15338. targetStore = "scenes";
  15339. }
  15340. else {
  15341. targetStore = "textures";
  15342. }
  15343. var file;
  15344. var transaction = this.db.transaction([targetStore]);
  15345. transaction.oncomplete = function (event) {
  15346. if (file) {
  15347. callback(file.data);
  15348. }
  15349. else {
  15350. notInDBCallback();
  15351. }
  15352. };
  15353. transaction.onabort = function (event) {
  15354. notInDBCallback();
  15355. };
  15356. var getRequest = transaction.objectStore(targetStore).get(url);
  15357. getRequest.onsuccess = function (event) {
  15358. file = (event.target).result;
  15359. };
  15360. getRequest.onerror = function (event) {
  15361. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15362. notInDBCallback();
  15363. };
  15364. }
  15365. else {
  15366. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15367. callback();
  15368. }
  15369. };
  15370. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15371. var _this = this;
  15372. if (this.isSupported) {
  15373. var targetStore;
  15374. if (url.indexOf(".babylon") !== -1) {
  15375. targetStore = "scenes";
  15376. }
  15377. else {
  15378. targetStore = "textures";
  15379. }
  15380. // Create XHR
  15381. var xhr = new XMLHttpRequest(), fileData;
  15382. xhr.open("GET", url, true);
  15383. if (useArrayBuffer) {
  15384. xhr.responseType = "arraybuffer";
  15385. }
  15386. xhr.onprogress = progressCallback;
  15387. xhr.addEventListener("load", function () {
  15388. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15389. // Blob as response (XHR2)
  15390. //fileData = xhr.responseText;
  15391. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15392. if (!_this.hasReachedQuota) {
  15393. // Open a transaction to the database
  15394. var transaction = _this.db.transaction([targetStore], "readwrite");
  15395. // the transaction could abort because of a QuotaExceededError error
  15396. transaction.onabort = function (event) {
  15397. try {
  15398. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15399. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15400. this.hasReachedQuota = true;
  15401. }
  15402. }
  15403. catch (ex) {
  15404. }
  15405. callback(fileData);
  15406. };
  15407. transaction.oncomplete = function (event) {
  15408. callback(fileData);
  15409. };
  15410. var newFile;
  15411. if (targetStore === "scenes") {
  15412. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15413. }
  15414. else {
  15415. newFile = { textureUrl: url, data: fileData };
  15416. }
  15417. try {
  15418. // Put the scene into the database
  15419. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15420. addRequest.onsuccess = function (event) {
  15421. };
  15422. addRequest.onerror = function (event) {
  15423. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15424. };
  15425. }
  15426. catch (ex) {
  15427. callback(fileData);
  15428. }
  15429. }
  15430. else {
  15431. callback(fileData);
  15432. }
  15433. }
  15434. else {
  15435. callback();
  15436. }
  15437. }, false);
  15438. xhr.addEventListener("error", function (event) {
  15439. BABYLON.Tools.Error("error on XHR request.");
  15440. callback();
  15441. }, false);
  15442. xhr.send();
  15443. }
  15444. else {
  15445. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15446. callback();
  15447. }
  15448. };
  15449. Database.isUASupportingBlobStorage = true;
  15450. Database.parseURL = function (url) {
  15451. var a = document.createElement('a');
  15452. a.href = url;
  15453. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15454. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15455. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15456. return absLocation;
  15457. };
  15458. Database.ReturnFullUrlLocation = function (url) {
  15459. if (url.indexOf("http:/") === -1) {
  15460. return (BABYLON.Database.parseURL(window.location.href) + url);
  15461. }
  15462. else {
  15463. return url;
  15464. }
  15465. };
  15466. return Database;
  15467. })();
  15468. BABYLON.Database = Database;
  15469. })(BABYLON || (BABYLON = {}));
  15470. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15471. (function (BABYLON) {
  15472. var SpriteManager = (function () {
  15473. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15474. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15475. this.name = name;
  15476. this.cellSize = cellSize;
  15477. this.sprites = new Array();
  15478. this.renderingGroupId = 0;
  15479. this.fogEnabled = true;
  15480. this._vertexDeclaration = [3, 4, 4, 4];
  15481. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15482. this._capacity = capacity;
  15483. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15484. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15485. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15486. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15487. this._scene = scene;
  15488. this._scene.spriteManagers.push(this);
  15489. // VBO
  15490. this._vertexDeclaration = [3, 4, 4, 4];
  15491. this._vertexStrideSize = 15 * 4;
  15492. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15493. var indices = [];
  15494. var index = 0;
  15495. for (var count = 0; count < capacity; count++) {
  15496. indices.push(index);
  15497. indices.push(index + 1);
  15498. indices.push(index + 2);
  15499. indices.push(index);
  15500. indices.push(index + 2);
  15501. indices.push(index + 3);
  15502. index += 4;
  15503. }
  15504. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15505. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15506. // Effects
  15507. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15508. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15509. }
  15510. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15511. var arrayOffset = index * 15;
  15512. if (offsetX === 0)
  15513. offsetX = this._epsilon;
  15514. else if (offsetX === 1)
  15515. offsetX = 1 - this._epsilon;
  15516. if (offsetY === 0)
  15517. offsetY = this._epsilon;
  15518. else if (offsetY === 1)
  15519. offsetY = 1 - this._epsilon;
  15520. this._vertices[arrayOffset] = sprite.position.x;
  15521. this._vertices[arrayOffset + 1] = sprite.position.y;
  15522. this._vertices[arrayOffset + 2] = sprite.position.z;
  15523. this._vertices[arrayOffset + 3] = sprite.angle;
  15524. this._vertices[arrayOffset + 4] = sprite.size;
  15525. this._vertices[arrayOffset + 5] = offsetX;
  15526. this._vertices[arrayOffset + 6] = offsetY;
  15527. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15528. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15529. var offset = (sprite.cellIndex / rowSize) >> 0;
  15530. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15531. this._vertices[arrayOffset + 10] = offset;
  15532. // Color
  15533. this._vertices[arrayOffset + 11] = sprite.color.r;
  15534. this._vertices[arrayOffset + 12] = sprite.color.g;
  15535. this._vertices[arrayOffset + 13] = sprite.color.b;
  15536. this._vertices[arrayOffset + 14] = sprite.color.a;
  15537. };
  15538. SpriteManager.prototype.render = function () {
  15539. // Check
  15540. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15541. return;
  15542. var engine = this._scene.getEngine();
  15543. var baseSize = this._spriteTexture.getBaseSize();
  15544. // Sprites
  15545. var deltaTime = engine.getDeltaTime();
  15546. var max = Math.min(this._capacity, this.sprites.length);
  15547. var rowSize = baseSize.width / this.cellSize;
  15548. var offset = 0;
  15549. for (var index = 0; index < max; index++) {
  15550. var sprite = this.sprites[index];
  15551. if (!sprite) {
  15552. continue;
  15553. }
  15554. sprite._animate(deltaTime);
  15555. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15556. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15557. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15558. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15559. }
  15560. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15561. // Render
  15562. var effect = this._effectBase;
  15563. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15564. effect = this._effectFog;
  15565. }
  15566. engine.enableEffect(effect);
  15567. var viewMatrix = this._scene.getViewMatrix();
  15568. effect.setTexture("diffuseSampler", this._spriteTexture);
  15569. effect.setMatrix("view", viewMatrix);
  15570. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15571. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15572. // Fog
  15573. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15574. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15575. effect.setColor3("vFogColor", this._scene.fogColor);
  15576. }
  15577. // VBOs
  15578. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15579. // Draw order
  15580. effect.setBool("alphaTest", true);
  15581. engine.setColorWrite(false);
  15582. engine.draw(true, 0, max * 6);
  15583. engine.setColorWrite(true);
  15584. effect.setBool("alphaTest", false);
  15585. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15586. engine.draw(true, 0, max * 6);
  15587. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15588. };
  15589. SpriteManager.prototype.dispose = function () {
  15590. if (this._vertexBuffer) {
  15591. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15592. this._vertexBuffer = null;
  15593. }
  15594. if (this._indexBuffer) {
  15595. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15596. this._indexBuffer = null;
  15597. }
  15598. if (this._spriteTexture) {
  15599. this._spriteTexture.dispose();
  15600. this._spriteTexture = null;
  15601. }
  15602. // Remove from scene
  15603. var index = this._scene.spriteManagers.indexOf(this);
  15604. this._scene.spriteManagers.splice(index, 1);
  15605. // Callback
  15606. if (this.onDispose) {
  15607. this.onDispose();
  15608. }
  15609. };
  15610. return SpriteManager;
  15611. })();
  15612. BABYLON.SpriteManager = SpriteManager;
  15613. })(BABYLON || (BABYLON = {}));
  15614. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15615. (function (BABYLON) {
  15616. var Sprite = (function () {
  15617. function Sprite(name, manager) {
  15618. this.name = name;
  15619. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15620. this.size = 1.0;
  15621. this.angle = 0;
  15622. this.cellIndex = 0;
  15623. this.invertU = 0;
  15624. this.invertV = 0;
  15625. this.animations = new Array();
  15626. this._animationStarted = false;
  15627. this._loopAnimation = false;
  15628. this._fromIndex = 0;
  15629. this._toIndex = 0;
  15630. this._delay = 0;
  15631. this._direction = 1;
  15632. this._frameCount = 0;
  15633. this._time = 0;
  15634. this._manager = manager;
  15635. this._manager.sprites.push(this);
  15636. this.position = BABYLON.Vector3.Zero();
  15637. }
  15638. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15639. this._fromIndex = from;
  15640. this._toIndex = to;
  15641. this._loopAnimation = loop;
  15642. this._delay = delay;
  15643. this._animationStarted = true;
  15644. this._direction = from < to ? 1 : -1;
  15645. this.cellIndex = from;
  15646. this._time = 0;
  15647. };
  15648. Sprite.prototype.stopAnimation = function () {
  15649. this._animationStarted = false;
  15650. };
  15651. Sprite.prototype._animate = function (deltaTime) {
  15652. if (!this._animationStarted)
  15653. return;
  15654. this._time += deltaTime;
  15655. if (this._time > this._delay) {
  15656. this._time = this._time % this._delay;
  15657. this.cellIndex += this._direction;
  15658. if (this.cellIndex == this._toIndex) {
  15659. if (this._loopAnimation) {
  15660. this.cellIndex = this._fromIndex;
  15661. }
  15662. else {
  15663. this._animationStarted = false;
  15664. if (this.disposeWhenFinishedAnimating) {
  15665. this.dispose();
  15666. }
  15667. }
  15668. }
  15669. }
  15670. };
  15671. Sprite.prototype.dispose = function () {
  15672. for (var i = 0; i < this._manager.sprites.length; i++) {
  15673. if (this._manager.sprites[i] == this) {
  15674. this._manager.sprites.splice(i, 1);
  15675. }
  15676. }
  15677. };
  15678. return Sprite;
  15679. })();
  15680. BABYLON.Sprite = Sprite;
  15681. })(BABYLON || (BABYLON = {}));
  15682. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15683. (function (BABYLON) {
  15684. var Layer = (function () {
  15685. function Layer(name, imgUrl, scene, isBackground, color) {
  15686. this.name = name;
  15687. this._vertexDeclaration = [2];
  15688. this._vertexStrideSize = 2 * 4;
  15689. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15690. this.isBackground = isBackground === undefined ? true : isBackground;
  15691. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15692. this._scene = scene;
  15693. this._scene.layers.push(this);
  15694. // VBO
  15695. var vertices = [];
  15696. vertices.push(1, 1);
  15697. vertices.push(-1, 1);
  15698. vertices.push(-1, -1);
  15699. vertices.push(1, -1);
  15700. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15701. // Indices
  15702. var indices = [];
  15703. indices.push(0);
  15704. indices.push(1);
  15705. indices.push(2);
  15706. indices.push(0);
  15707. indices.push(2);
  15708. indices.push(3);
  15709. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15710. // Effects
  15711. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15712. }
  15713. Layer.prototype.render = function () {
  15714. // Check
  15715. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15716. return;
  15717. var engine = this._scene.getEngine();
  15718. // Render
  15719. engine.enableEffect(this._effect);
  15720. engine.setState(false);
  15721. // Texture
  15722. this._effect.setTexture("textureSampler", this.texture);
  15723. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15724. // Color
  15725. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15726. // VBOs
  15727. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15728. // Draw order
  15729. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15730. engine.draw(true, 0, 6);
  15731. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15732. };
  15733. Layer.prototype.dispose = function () {
  15734. if (this._vertexBuffer) {
  15735. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15736. this._vertexBuffer = null;
  15737. }
  15738. if (this._indexBuffer) {
  15739. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15740. this._indexBuffer = null;
  15741. }
  15742. if (this.texture) {
  15743. this.texture.dispose();
  15744. this.texture = null;
  15745. }
  15746. // Remove from scene
  15747. var index = this._scene.layers.indexOf(this);
  15748. this._scene.layers.splice(index, 1);
  15749. // Callback
  15750. if (this.onDispose) {
  15751. this.onDispose();
  15752. }
  15753. };
  15754. return Layer;
  15755. })();
  15756. BABYLON.Layer = Layer;
  15757. })(BABYLON || (BABYLON = {}));
  15758. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15759. (function (BABYLON) {
  15760. var Particle = (function () {
  15761. function Particle() {
  15762. this.position = BABYLON.Vector3.Zero();
  15763. this.direction = BABYLON.Vector3.Zero();
  15764. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15765. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15766. this.lifeTime = 1.0;
  15767. this.age = 0;
  15768. this.size = 0;
  15769. this.angle = 0;
  15770. this.angularSpeed = 0;
  15771. }
  15772. Particle.prototype.copyTo = function (other) {
  15773. other.position.copyFrom(this.position);
  15774. other.direction.copyFrom(this.direction);
  15775. other.color.copyFrom(this.color);
  15776. other.colorStep.copyFrom(this.colorStep);
  15777. other.lifeTime = this.lifeTime;
  15778. other.age = this.age;
  15779. other.size = this.size;
  15780. other.angle = this.angle;
  15781. other.angularSpeed = this.angularSpeed;
  15782. };
  15783. return Particle;
  15784. })();
  15785. BABYLON.Particle = Particle;
  15786. })(BABYLON || (BABYLON = {}));
  15787. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15788. (function (BABYLON) {
  15789. var randomNumber = function (min, max) {
  15790. if (min === max) {
  15791. return (min);
  15792. }
  15793. var random = Math.random();
  15794. return ((random * (max - min)) + min);
  15795. };
  15796. var ParticleSystem = (function () {
  15797. function ParticleSystem(name, capacity, scene, customEffect) {
  15798. var _this = this;
  15799. this.name = name;
  15800. this.renderingGroupId = 0;
  15801. this.emitter = null;
  15802. this.emitRate = 10;
  15803. this.manualEmitCount = -1;
  15804. this.updateSpeed = 0.01;
  15805. this.targetStopDuration = 0;
  15806. this.disposeOnStop = false;
  15807. this.minEmitPower = 1;
  15808. this.maxEmitPower = 1;
  15809. this.minLifeTime = 1;
  15810. this.maxLifeTime = 1;
  15811. this.minSize = 1;
  15812. this.maxSize = 1;
  15813. this.minAngularSpeed = 0;
  15814. this.maxAngularSpeed = 0;
  15815. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15816. this.forceDepthWrite = false;
  15817. this.gravity = BABYLON.Vector3.Zero();
  15818. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15819. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15820. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15821. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15822. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15823. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15824. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15825. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15826. this.particles = new Array();
  15827. this._vertexDeclaration = [3, 4, 4];
  15828. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15829. this._stockParticles = new Array();
  15830. this._newPartsExcess = 0;
  15831. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15832. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15833. this._scaledDirection = BABYLON.Vector3.Zero();
  15834. this._scaledGravity = BABYLON.Vector3.Zero();
  15835. this._currentRenderId = -1;
  15836. this._started = false;
  15837. this._stopped = false;
  15838. this._actualFrame = 0;
  15839. this.id = name;
  15840. this._capacity = capacity;
  15841. this._scene = scene;
  15842. this._customEffect = customEffect;
  15843. scene.particleSystems.push(this);
  15844. // VBO
  15845. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15846. var indices = [];
  15847. var index = 0;
  15848. for (var count = 0; count < capacity; count++) {
  15849. indices.push(index);
  15850. indices.push(index + 1);
  15851. indices.push(index + 2);
  15852. indices.push(index);
  15853. indices.push(index + 2);
  15854. indices.push(index + 3);
  15855. index += 4;
  15856. }
  15857. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15858. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15859. // Default behaviors
  15860. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15861. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15862. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15863. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15864. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15865. };
  15866. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15867. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15868. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15869. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15870. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15871. };
  15872. this.updateFunction = function (particles) {
  15873. for (var index = 0; index < particles.length; index++) {
  15874. var particle = particles[index];
  15875. particle.age += _this._scaledUpdateSpeed;
  15876. if (particle.age >= particle.lifeTime) {
  15877. _this.recycleParticle(particle);
  15878. index--;
  15879. continue;
  15880. }
  15881. else {
  15882. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15883. particle.color.addInPlace(_this._scaledColorStep);
  15884. if (particle.color.a < 0)
  15885. particle.color.a = 0;
  15886. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15887. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15888. particle.position.addInPlace(_this._scaledDirection);
  15889. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15890. particle.direction.addInPlace(_this._scaledGravity);
  15891. }
  15892. }
  15893. };
  15894. }
  15895. ParticleSystem.prototype.recycleParticle = function (particle) {
  15896. var lastParticle = this.particles.pop();
  15897. if (lastParticle !== particle) {
  15898. lastParticle.copyTo(particle);
  15899. this._stockParticles.push(lastParticle);
  15900. }
  15901. };
  15902. ParticleSystem.prototype.getCapacity = function () {
  15903. return this._capacity;
  15904. };
  15905. ParticleSystem.prototype.isAlive = function () {
  15906. return this._alive;
  15907. };
  15908. ParticleSystem.prototype.isStarted = function () {
  15909. return this._started;
  15910. };
  15911. ParticleSystem.prototype.start = function () {
  15912. this._started = true;
  15913. this._stopped = false;
  15914. this._actualFrame = 0;
  15915. };
  15916. ParticleSystem.prototype.stop = function () {
  15917. this._stopped = true;
  15918. };
  15919. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15920. var offset = index * 11;
  15921. this._vertices[offset] = particle.position.x;
  15922. this._vertices[offset + 1] = particle.position.y;
  15923. this._vertices[offset + 2] = particle.position.z;
  15924. this._vertices[offset + 3] = particle.color.r;
  15925. this._vertices[offset + 4] = particle.color.g;
  15926. this._vertices[offset + 5] = particle.color.b;
  15927. this._vertices[offset + 6] = particle.color.a;
  15928. this._vertices[offset + 7] = particle.angle;
  15929. this._vertices[offset + 8] = particle.size;
  15930. this._vertices[offset + 9] = offsetX;
  15931. this._vertices[offset + 10] = offsetY;
  15932. };
  15933. ParticleSystem.prototype._update = function (newParticles) {
  15934. // Update current
  15935. this._alive = this.particles.length > 0;
  15936. this.updateFunction(this.particles);
  15937. // Add new ones
  15938. var worldMatrix;
  15939. if (this.emitter.position) {
  15940. worldMatrix = this.emitter.getWorldMatrix();
  15941. }
  15942. else {
  15943. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15944. }
  15945. for (var index = 0; index < newParticles; index++) {
  15946. if (this.particles.length === this._capacity) {
  15947. break;
  15948. }
  15949. if (this._stockParticles.length !== 0) {
  15950. var particle = this._stockParticles.pop();
  15951. particle.age = 0;
  15952. }
  15953. else {
  15954. particle = new BABYLON.Particle();
  15955. }
  15956. this.particles.push(particle);
  15957. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15958. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15959. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15960. particle.size = randomNumber(this.minSize, this.maxSize);
  15961. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15962. this.startPositionFunction(worldMatrix, particle.position);
  15963. var step = randomNumber(0, 1.0);
  15964. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15965. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15966. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15967. }
  15968. };
  15969. ParticleSystem.prototype._getEffect = function () {
  15970. if (this._customEffect) {
  15971. return this._customEffect;
  15972. }
  15973. ;
  15974. var defines = [];
  15975. if (this._scene.clipPlane) {
  15976. defines.push("#define CLIPPLANE");
  15977. }
  15978. // Effect
  15979. var join = defines.join("\n");
  15980. if (this._cachedDefines !== join) {
  15981. this._cachedDefines = join;
  15982. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15983. }
  15984. return this._effect;
  15985. };
  15986. ParticleSystem.prototype.animate = function () {
  15987. if (!this._started)
  15988. return;
  15989. var effect = this._getEffect();
  15990. // Check
  15991. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15992. return;
  15993. if (this._currentRenderId === this._scene.getRenderId()) {
  15994. return;
  15995. }
  15996. this._currentRenderId = this._scene.getRenderId();
  15997. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15998. // determine the number of particles we need to create
  15999. var emitCout;
  16000. if (this.manualEmitCount > -1) {
  16001. emitCout = this.manualEmitCount;
  16002. this.manualEmitCount = 0;
  16003. }
  16004. else {
  16005. emitCout = this.emitRate;
  16006. }
  16007. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  16008. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  16009. if (this._newPartsExcess > 1.0) {
  16010. newParticles += this._newPartsExcess >> 0;
  16011. this._newPartsExcess -= this._newPartsExcess >> 0;
  16012. }
  16013. this._alive = false;
  16014. if (!this._stopped) {
  16015. this._actualFrame += this._scaledUpdateSpeed;
  16016. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  16017. this.stop();
  16018. }
  16019. else {
  16020. newParticles = 0;
  16021. }
  16022. this._update(newParticles);
  16023. // Stopped?
  16024. if (this._stopped) {
  16025. if (!this._alive) {
  16026. this._started = false;
  16027. if (this.disposeOnStop) {
  16028. this._scene._toBeDisposed.push(this);
  16029. }
  16030. }
  16031. }
  16032. // Update VBO
  16033. var offset = 0;
  16034. for (var index = 0; index < this.particles.length; index++) {
  16035. var particle = this.particles[index];
  16036. this._appendParticleVertex(offset++, particle, 0, 0);
  16037. this._appendParticleVertex(offset++, particle, 1, 0);
  16038. this._appendParticleVertex(offset++, particle, 1, 1);
  16039. this._appendParticleVertex(offset++, particle, 0, 1);
  16040. }
  16041. var engine = this._scene.getEngine();
  16042. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  16043. };
  16044. ParticleSystem.prototype.render = function () {
  16045. var effect = this._getEffect();
  16046. // Check
  16047. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  16048. return 0;
  16049. var engine = this._scene.getEngine();
  16050. // Render
  16051. engine.enableEffect(effect);
  16052. engine.setState(false);
  16053. var viewMatrix = this._scene.getViewMatrix();
  16054. effect.setTexture("diffuseSampler", this.particleTexture);
  16055. effect.setMatrix("view", viewMatrix);
  16056. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  16057. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  16058. if (this._scene.clipPlane) {
  16059. var clipPlane = this._scene.clipPlane;
  16060. var invView = viewMatrix.clone();
  16061. invView.invert();
  16062. effect.setMatrix("invView", invView);
  16063. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  16064. }
  16065. // VBOs
  16066. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16067. // Draw order
  16068. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  16069. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  16070. }
  16071. else {
  16072. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  16073. }
  16074. if (this.forceDepthWrite) {
  16075. engine.setDepthWrite(true);
  16076. }
  16077. engine.draw(true, 0, this.particles.length * 6);
  16078. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16079. return this.particles.length;
  16080. };
  16081. ParticleSystem.prototype.dispose = function () {
  16082. if (this._vertexBuffer) {
  16083. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16084. this._vertexBuffer = null;
  16085. }
  16086. if (this._indexBuffer) {
  16087. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16088. this._indexBuffer = null;
  16089. }
  16090. if (this.particleTexture) {
  16091. this.particleTexture.dispose();
  16092. this.particleTexture = null;
  16093. }
  16094. // Remove from scene
  16095. var index = this._scene.particleSystems.indexOf(this);
  16096. this._scene.particleSystems.splice(index, 1);
  16097. // Callback
  16098. if (this.onDispose) {
  16099. this.onDispose();
  16100. }
  16101. };
  16102. // Clone
  16103. ParticleSystem.prototype.clone = function (name, newEmitter) {
  16104. var result = new ParticleSystem(name, this._capacity, this._scene);
  16105. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  16106. if (newEmitter === undefined) {
  16107. newEmitter = this.emitter;
  16108. }
  16109. result.emitter = newEmitter;
  16110. if (this.particleTexture) {
  16111. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  16112. }
  16113. result.start();
  16114. return result;
  16115. };
  16116. // Statics
  16117. ParticleSystem.BLENDMODE_ONEONE = 0;
  16118. ParticleSystem.BLENDMODE_STANDARD = 1;
  16119. return ParticleSystem;
  16120. })();
  16121. BABYLON.ParticleSystem = ParticleSystem;
  16122. })(BABYLON || (BABYLON = {}));
  16123. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  16124. (function (BABYLON) {
  16125. var Animation = (function () {
  16126. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  16127. this.name = name;
  16128. this.targetProperty = targetProperty;
  16129. this.framePerSecond = framePerSecond;
  16130. this.dataType = dataType;
  16131. this.loopMode = loopMode;
  16132. this._offsetsCache = {};
  16133. this._highLimitsCache = {};
  16134. this._stopped = false;
  16135. this.targetPropertyPath = targetProperty.split(".");
  16136. this.dataType = dataType;
  16137. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  16138. }
  16139. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  16140. var dataType = undefined;
  16141. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  16142. dataType = Animation.ANIMATIONTYPE_FLOAT;
  16143. }
  16144. else if (from instanceof BABYLON.Quaternion) {
  16145. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  16146. }
  16147. else if (from instanceof BABYLON.Vector3) {
  16148. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  16149. }
  16150. else if (from instanceof BABYLON.Vector2) {
  16151. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  16152. }
  16153. else if (from instanceof BABYLON.Color3) {
  16154. dataType = Animation.ANIMATIONTYPE_COLOR3;
  16155. }
  16156. if (dataType == undefined) {
  16157. return null;
  16158. }
  16159. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  16160. var keys = [];
  16161. keys.push({ frame: 0, value: from });
  16162. keys.push({ frame: totalFrame, value: to });
  16163. animation.setKeys(keys);
  16164. mesh.animations.push(animation);
  16165. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  16166. };
  16167. // Methods
  16168. Animation.prototype.isStopped = function () {
  16169. return this._stopped;
  16170. };
  16171. Animation.prototype.getKeys = function () {
  16172. return this._keys;
  16173. };
  16174. Animation.prototype.getEasingFunction = function () {
  16175. return this._easingFunction;
  16176. };
  16177. Animation.prototype.setEasingFunction = function (easingFunction) {
  16178. this._easingFunction = easingFunction;
  16179. };
  16180. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  16181. return startValue + (endValue - startValue) * gradient;
  16182. };
  16183. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  16184. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  16185. };
  16186. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  16187. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  16188. };
  16189. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  16190. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  16191. };
  16192. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  16193. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  16194. };
  16195. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  16196. var startScale = new BABYLON.Vector3(0, 0, 0);
  16197. var startRotation = new BABYLON.Quaternion();
  16198. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  16199. startValue.decompose(startScale, startRotation, startTranslation);
  16200. var endScale = new BABYLON.Vector3(0, 0, 0);
  16201. var endRotation = new BABYLON.Quaternion();
  16202. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  16203. endValue.decompose(endScale, endRotation, endTranslation);
  16204. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  16205. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  16206. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  16207. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  16208. return result;
  16209. };
  16210. Animation.prototype.clone = function () {
  16211. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  16212. clone.setKeys(this._keys);
  16213. return clone;
  16214. };
  16215. Animation.prototype.setKeys = function (values) {
  16216. this._keys = values.slice(0);
  16217. this._offsetsCache = {};
  16218. this._highLimitsCache = {};
  16219. };
  16220. Animation.prototype._getKeyValue = function (value) {
  16221. if (typeof value === "function") {
  16222. return value();
  16223. }
  16224. return value;
  16225. };
  16226. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  16227. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  16228. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  16229. }
  16230. this.currentFrame = currentFrame;
  16231. // Try to get a hash to find the right key
  16232. var startKey = Math.max(0, Math.min(this._keys.length - 1, Math.floor(this._keys.length * (currentFrame - this._keys[0].frame) / (this._keys[this._keys.length - 1].frame - this._keys[0].frame)) - 1));
  16233. if (this._keys[startKey].frame >= currentFrame) {
  16234. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  16235. startKey--;
  16236. }
  16237. }
  16238. for (var key = startKey; key < this._keys.length; key++) {
  16239. if (this._keys[key + 1].frame >= currentFrame) {
  16240. var startValue = this._getKeyValue(this._keys[key].value);
  16241. var endValue = this._getKeyValue(this._keys[key + 1].value);
  16242. // gradient : percent of currentFrame between the frame inf and the frame sup
  16243. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  16244. // check for easingFunction and correction of gradient
  16245. if (this._easingFunction != null) {
  16246. gradient = this._easingFunction.ease(gradient);
  16247. }
  16248. switch (this.dataType) {
  16249. case Animation.ANIMATIONTYPE_FLOAT:
  16250. switch (loopMode) {
  16251. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16252. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16253. return this.floatInterpolateFunction(startValue, endValue, gradient);
  16254. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16255. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  16256. }
  16257. break;
  16258. case Animation.ANIMATIONTYPE_QUATERNION:
  16259. var quaternion = null;
  16260. switch (loopMode) {
  16261. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16262. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16263. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  16264. break;
  16265. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16266. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16267. break;
  16268. }
  16269. return quaternion;
  16270. case Animation.ANIMATIONTYPE_VECTOR3:
  16271. switch (loopMode) {
  16272. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16273. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16274. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  16275. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16276. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16277. }
  16278. case Animation.ANIMATIONTYPE_VECTOR2:
  16279. switch (loopMode) {
  16280. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16281. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16282. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  16283. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16284. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16285. }
  16286. case Animation.ANIMATIONTYPE_COLOR3:
  16287. switch (loopMode) {
  16288. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16289. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16290. return this.color3InterpolateFunction(startValue, endValue, gradient);
  16291. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16292. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  16293. }
  16294. case Animation.ANIMATIONTYPE_MATRIX:
  16295. switch (loopMode) {
  16296. case Animation.ANIMATIONLOOPMODE_CYCLE:
  16297. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  16298. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  16299. return startValue;
  16300. }
  16301. default:
  16302. break;
  16303. }
  16304. break;
  16305. }
  16306. }
  16307. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  16308. };
  16309. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  16310. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  16311. this._stopped = true;
  16312. return false;
  16313. }
  16314. var returnValue = true;
  16315. // Adding a start key at frame 0 if missing
  16316. if (this._keys[0].frame !== 0) {
  16317. var newKey = { frame: 0, value: this._keys[0].value };
  16318. this._keys.splice(0, 0, newKey);
  16319. }
  16320. // Check limits
  16321. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  16322. from = this._keys[0].frame;
  16323. }
  16324. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  16325. to = this._keys[this._keys.length - 1].frame;
  16326. }
  16327. // Compute ratio
  16328. var range = to - from;
  16329. var offsetValue;
  16330. // ratio represents the frame delta between from and to
  16331. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  16332. var highLimitValue = 0;
  16333. if (ratio > range && !loop) {
  16334. returnValue = false;
  16335. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  16336. }
  16337. else {
  16338. // Get max value if required
  16339. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  16340. var keyOffset = to.toString() + from.toString();
  16341. if (!this._offsetsCache[keyOffset]) {
  16342. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16343. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  16344. switch (this.dataType) {
  16345. case Animation.ANIMATIONTYPE_FLOAT:
  16346. this._offsetsCache[keyOffset] = toValue - fromValue;
  16347. break;
  16348. case Animation.ANIMATIONTYPE_QUATERNION:
  16349. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16350. break;
  16351. case Animation.ANIMATIONTYPE_VECTOR3:
  16352. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16353. case Animation.ANIMATIONTYPE_VECTOR2:
  16354. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16355. case Animation.ANIMATIONTYPE_COLOR3:
  16356. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16357. default:
  16358. break;
  16359. }
  16360. this._highLimitsCache[keyOffset] = toValue;
  16361. }
  16362. highLimitValue = this._highLimitsCache[keyOffset];
  16363. offsetValue = this._offsetsCache[keyOffset];
  16364. }
  16365. }
  16366. if (offsetValue === undefined) {
  16367. switch (this.dataType) {
  16368. case Animation.ANIMATIONTYPE_FLOAT:
  16369. offsetValue = 0;
  16370. break;
  16371. case Animation.ANIMATIONTYPE_QUATERNION:
  16372. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16373. break;
  16374. case Animation.ANIMATIONTYPE_VECTOR3:
  16375. offsetValue = BABYLON.Vector3.Zero();
  16376. break;
  16377. case Animation.ANIMATIONTYPE_VECTOR2:
  16378. offsetValue = BABYLON.Vector2.Zero();
  16379. break;
  16380. case Animation.ANIMATIONTYPE_COLOR3:
  16381. offsetValue = BABYLON.Color3.Black();
  16382. }
  16383. }
  16384. // Compute value
  16385. var repeatCount = (ratio / range) >> 0;
  16386. var currentFrame = returnValue ? from + ratio % range : to;
  16387. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16388. // Set value
  16389. if (this.targetPropertyPath.length > 1) {
  16390. var property = this._target[this.targetPropertyPath[0]];
  16391. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16392. property = property[this.targetPropertyPath[index]];
  16393. }
  16394. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16395. }
  16396. else {
  16397. this._target[this.targetPropertyPath[0]] = currentValue;
  16398. }
  16399. if (this._target.markAsDirty) {
  16400. this._target.markAsDirty(this.targetProperty);
  16401. }
  16402. if (!returnValue) {
  16403. this._stopped = true;
  16404. }
  16405. return returnValue;
  16406. };
  16407. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16408. get: function () {
  16409. return Animation._ANIMATIONTYPE_FLOAT;
  16410. },
  16411. enumerable: true,
  16412. configurable: true
  16413. });
  16414. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16415. get: function () {
  16416. return Animation._ANIMATIONTYPE_VECTOR3;
  16417. },
  16418. enumerable: true,
  16419. configurable: true
  16420. });
  16421. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16422. get: function () {
  16423. return Animation._ANIMATIONTYPE_VECTOR2;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16429. get: function () {
  16430. return Animation._ANIMATIONTYPE_QUATERNION;
  16431. },
  16432. enumerable: true,
  16433. configurable: true
  16434. });
  16435. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16436. get: function () {
  16437. return Animation._ANIMATIONTYPE_MATRIX;
  16438. },
  16439. enumerable: true,
  16440. configurable: true
  16441. });
  16442. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16443. get: function () {
  16444. return Animation._ANIMATIONTYPE_COLOR3;
  16445. },
  16446. enumerable: true,
  16447. configurable: true
  16448. });
  16449. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16450. get: function () {
  16451. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16452. },
  16453. enumerable: true,
  16454. configurable: true
  16455. });
  16456. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16457. get: function () {
  16458. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16459. },
  16460. enumerable: true,
  16461. configurable: true
  16462. });
  16463. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16464. get: function () {
  16465. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16466. },
  16467. enumerable: true,
  16468. configurable: true
  16469. });
  16470. // Statics
  16471. Animation._ANIMATIONTYPE_FLOAT = 0;
  16472. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16473. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16474. Animation._ANIMATIONTYPE_MATRIX = 3;
  16475. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16476. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16477. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16478. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16479. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16480. return Animation;
  16481. })();
  16482. BABYLON.Animation = Animation;
  16483. })(BABYLON || (BABYLON = {}));
  16484. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16485. (function (BABYLON) {
  16486. var Animatable = (function () {
  16487. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16488. if (fromFrame === void 0) { fromFrame = 0; }
  16489. if (toFrame === void 0) { toFrame = 100; }
  16490. if (loopAnimation === void 0) { loopAnimation = false; }
  16491. if (speedRatio === void 0) { speedRatio = 1.0; }
  16492. this.target = target;
  16493. this.fromFrame = fromFrame;
  16494. this.toFrame = toFrame;
  16495. this.loopAnimation = loopAnimation;
  16496. this.speedRatio = speedRatio;
  16497. this.onAnimationEnd = onAnimationEnd;
  16498. this._animations = new Array();
  16499. this._paused = false;
  16500. this.animationStarted = false;
  16501. if (animations) {
  16502. this.appendAnimations(target, animations);
  16503. }
  16504. this._scene = scene;
  16505. scene._activeAnimatables.push(this);
  16506. }
  16507. // Methods
  16508. Animatable.prototype.appendAnimations = function (target, animations) {
  16509. for (var index = 0; index < animations.length; index++) {
  16510. var animation = animations[index];
  16511. animation._target = target;
  16512. this._animations.push(animation);
  16513. }
  16514. };
  16515. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16516. var animations = this._animations;
  16517. for (var index = 0; index < animations.length; index++) {
  16518. if (animations[index].targetProperty === property) {
  16519. return animations[index];
  16520. }
  16521. }
  16522. return null;
  16523. };
  16524. Animatable.prototype.pause = function () {
  16525. if (this._paused) {
  16526. return;
  16527. }
  16528. this._paused = true;
  16529. };
  16530. Animatable.prototype.restart = function () {
  16531. this._paused = false;
  16532. };
  16533. Animatable.prototype.stop = function () {
  16534. var index = this._scene._activeAnimatables.indexOf(this);
  16535. if (index > -1) {
  16536. this._scene._activeAnimatables.splice(index, 1);
  16537. }
  16538. if (this.onAnimationEnd) {
  16539. this.onAnimationEnd();
  16540. }
  16541. };
  16542. Animatable.prototype._animate = function (delay) {
  16543. if (this._paused) {
  16544. if (!this._pausedDelay) {
  16545. this._pausedDelay = delay;
  16546. }
  16547. return true;
  16548. }
  16549. if (!this._localDelayOffset) {
  16550. this._localDelayOffset = delay;
  16551. }
  16552. else if (this._pausedDelay) {
  16553. this._localDelayOffset += delay - this._pausedDelay;
  16554. this._pausedDelay = null;
  16555. }
  16556. // Animating
  16557. var running = false;
  16558. var animations = this._animations;
  16559. for (var index = 0; index < animations.length; index++) {
  16560. var animation = animations[index];
  16561. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16562. running = running || isRunning;
  16563. }
  16564. if (!running && this.onAnimationEnd) {
  16565. this.onAnimationEnd();
  16566. }
  16567. return running;
  16568. };
  16569. return Animatable;
  16570. })();
  16571. BABYLON.Animatable = Animatable;
  16572. })(BABYLON || (BABYLON = {}));
  16573. //# sourceMappingURL=babylon.animatable.js.map
  16574. var BABYLON;
  16575. (function (BABYLON) {
  16576. var EasingFunction = (function () {
  16577. function EasingFunction() {
  16578. // Properties
  16579. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16580. }
  16581. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16582. get: function () {
  16583. return EasingFunction._EASINGMODE_EASEIN;
  16584. },
  16585. enumerable: true,
  16586. configurable: true
  16587. });
  16588. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16589. get: function () {
  16590. return EasingFunction._EASINGMODE_EASEOUT;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16596. get: function () {
  16597. return EasingFunction._EASINGMODE_EASEINOUT;
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16603. var n = Math.min(Math.max(easingMode, 0), 2);
  16604. this._easingMode = n;
  16605. };
  16606. EasingFunction.prototype.getEasingMode = function () {
  16607. return this._easingMode;
  16608. };
  16609. EasingFunction.prototype.easeInCore = function (gradient) {
  16610. throw new Error('You must implement this method');
  16611. };
  16612. EasingFunction.prototype.ease = function (gradient) {
  16613. switch (this._easingMode) {
  16614. case EasingFunction.EASINGMODE_EASEIN:
  16615. return this.easeInCore(gradient);
  16616. case EasingFunction.EASINGMODE_EASEOUT:
  16617. return (1 - this.easeInCore(1 - gradient));
  16618. }
  16619. if (gradient >= 0.5) {
  16620. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16621. }
  16622. return (this.easeInCore(gradient * 2) * 0.5);
  16623. };
  16624. //Statics
  16625. EasingFunction._EASINGMODE_EASEIN = 0;
  16626. EasingFunction._EASINGMODE_EASEOUT = 1;
  16627. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16628. return EasingFunction;
  16629. })();
  16630. BABYLON.EasingFunction = EasingFunction;
  16631. var CircleEase = (function (_super) {
  16632. __extends(CircleEase, _super);
  16633. function CircleEase() {
  16634. _super.apply(this, arguments);
  16635. }
  16636. CircleEase.prototype.easeInCore = function (gradient) {
  16637. gradient = Math.max(0, Math.min(1, gradient));
  16638. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16639. };
  16640. return CircleEase;
  16641. })(EasingFunction);
  16642. BABYLON.CircleEase = CircleEase;
  16643. var BackEase = (function (_super) {
  16644. __extends(BackEase, _super);
  16645. function BackEase(amplitude) {
  16646. if (amplitude === void 0) { amplitude = 1; }
  16647. _super.call(this);
  16648. this.amplitude = amplitude;
  16649. }
  16650. BackEase.prototype.easeInCore = function (gradient) {
  16651. var num = Math.max(0, this.amplitude);
  16652. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16653. };
  16654. return BackEase;
  16655. })(EasingFunction);
  16656. BABYLON.BackEase = BackEase;
  16657. var BounceEase = (function (_super) {
  16658. __extends(BounceEase, _super);
  16659. function BounceEase(bounces, bounciness) {
  16660. if (bounces === void 0) { bounces = 3; }
  16661. if (bounciness === void 0) { bounciness = 2; }
  16662. _super.call(this);
  16663. this.bounces = bounces;
  16664. this.bounciness = bounciness;
  16665. }
  16666. BounceEase.prototype.easeInCore = function (gradient) {
  16667. var y = Math.max(0.0, this.bounces);
  16668. var bounciness = this.bounciness;
  16669. if (bounciness <= 1.0) {
  16670. bounciness = 1.001;
  16671. }
  16672. var num9 = Math.pow(bounciness, y);
  16673. var num5 = 1.0 - bounciness;
  16674. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16675. var num15 = gradient * num4;
  16676. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16677. var num3 = Math.floor(num65);
  16678. var num13 = num3 + 1.0;
  16679. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16680. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16681. var num7 = (num8 + num12) * 0.5;
  16682. var num6 = gradient - num7;
  16683. var num2 = num7 - num8;
  16684. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16685. };
  16686. return BounceEase;
  16687. })(EasingFunction);
  16688. BABYLON.BounceEase = BounceEase;
  16689. var CubicEase = (function (_super) {
  16690. __extends(CubicEase, _super);
  16691. function CubicEase() {
  16692. _super.apply(this, arguments);
  16693. }
  16694. CubicEase.prototype.easeInCore = function (gradient) {
  16695. return (gradient * gradient * gradient);
  16696. };
  16697. return CubicEase;
  16698. })(EasingFunction);
  16699. BABYLON.CubicEase = CubicEase;
  16700. var ElasticEase = (function (_super) {
  16701. __extends(ElasticEase, _super);
  16702. function ElasticEase(oscillations, springiness) {
  16703. if (oscillations === void 0) { oscillations = 3; }
  16704. if (springiness === void 0) { springiness = 3; }
  16705. _super.call(this);
  16706. this.oscillations = oscillations;
  16707. this.springiness = springiness;
  16708. }
  16709. ElasticEase.prototype.easeInCore = function (gradient) {
  16710. var num2;
  16711. var num3 = Math.max(0.0, this.oscillations);
  16712. var num = Math.max(0.0, this.springiness);
  16713. if (num == 0) {
  16714. num2 = gradient;
  16715. }
  16716. else {
  16717. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16718. }
  16719. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16720. };
  16721. return ElasticEase;
  16722. })(EasingFunction);
  16723. BABYLON.ElasticEase = ElasticEase;
  16724. var ExponentialEase = (function (_super) {
  16725. __extends(ExponentialEase, _super);
  16726. function ExponentialEase(exponent) {
  16727. if (exponent === void 0) { exponent = 2; }
  16728. _super.call(this);
  16729. this.exponent = exponent;
  16730. }
  16731. ExponentialEase.prototype.easeInCore = function (gradient) {
  16732. if (this.exponent <= 0) {
  16733. return gradient;
  16734. }
  16735. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16736. };
  16737. return ExponentialEase;
  16738. })(EasingFunction);
  16739. BABYLON.ExponentialEase = ExponentialEase;
  16740. var PowerEase = (function (_super) {
  16741. __extends(PowerEase, _super);
  16742. function PowerEase(power) {
  16743. if (power === void 0) { power = 2; }
  16744. _super.call(this);
  16745. this.power = power;
  16746. }
  16747. PowerEase.prototype.easeInCore = function (gradient) {
  16748. var y = Math.max(0.0, this.power);
  16749. return Math.pow(gradient, y);
  16750. };
  16751. return PowerEase;
  16752. })(EasingFunction);
  16753. BABYLON.PowerEase = PowerEase;
  16754. var QuadraticEase = (function (_super) {
  16755. __extends(QuadraticEase, _super);
  16756. function QuadraticEase() {
  16757. _super.apply(this, arguments);
  16758. }
  16759. QuadraticEase.prototype.easeInCore = function (gradient) {
  16760. return (gradient * gradient);
  16761. };
  16762. return QuadraticEase;
  16763. })(EasingFunction);
  16764. BABYLON.QuadraticEase = QuadraticEase;
  16765. var QuarticEase = (function (_super) {
  16766. __extends(QuarticEase, _super);
  16767. function QuarticEase() {
  16768. _super.apply(this, arguments);
  16769. }
  16770. QuarticEase.prototype.easeInCore = function (gradient) {
  16771. return (gradient * gradient * gradient * gradient);
  16772. };
  16773. return QuarticEase;
  16774. })(EasingFunction);
  16775. BABYLON.QuarticEase = QuarticEase;
  16776. var QuinticEase = (function (_super) {
  16777. __extends(QuinticEase, _super);
  16778. function QuinticEase() {
  16779. _super.apply(this, arguments);
  16780. }
  16781. QuinticEase.prototype.easeInCore = function (gradient) {
  16782. return (gradient * gradient * gradient * gradient * gradient);
  16783. };
  16784. return QuinticEase;
  16785. })(EasingFunction);
  16786. BABYLON.QuinticEase = QuinticEase;
  16787. var SineEase = (function (_super) {
  16788. __extends(SineEase, _super);
  16789. function SineEase() {
  16790. _super.apply(this, arguments);
  16791. }
  16792. SineEase.prototype.easeInCore = function (gradient) {
  16793. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16794. };
  16795. return SineEase;
  16796. })(EasingFunction);
  16797. BABYLON.SineEase = SineEase;
  16798. var BezierCurveEase = (function (_super) {
  16799. __extends(BezierCurveEase, _super);
  16800. function BezierCurveEase(x1, y1, x2, y2) {
  16801. if (x1 === void 0) { x1 = 0; }
  16802. if (y1 === void 0) { y1 = 0; }
  16803. if (x2 === void 0) { x2 = 1; }
  16804. if (y2 === void 0) { y2 = 1; }
  16805. _super.call(this);
  16806. this.x1 = x1;
  16807. this.y1 = y1;
  16808. this.x2 = x2;
  16809. this.y2 = y2;
  16810. }
  16811. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16812. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16813. };
  16814. return BezierCurveEase;
  16815. })(EasingFunction);
  16816. BABYLON.BezierCurveEase = BezierCurveEase;
  16817. })(BABYLON || (BABYLON = {}));
  16818. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16819. (function (BABYLON) {
  16820. var Octree = (function () {
  16821. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16822. if (maxDepth === void 0) { maxDepth = 2; }
  16823. this.maxDepth = maxDepth;
  16824. this.dynamicContent = new Array();
  16825. this._maxBlockCapacity = maxBlockCapacity || 64;
  16826. this._selectionContent = new BABYLON.SmartArray(1024);
  16827. this._creationFunc = creationFunc;
  16828. }
  16829. // Methods
  16830. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16831. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16832. };
  16833. Octree.prototype.addMesh = function (entry) {
  16834. for (var index = 0; index < this.blocks.length; index++) {
  16835. var block = this.blocks[index];
  16836. block.addEntry(entry);
  16837. }
  16838. };
  16839. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16840. this._selectionContent.reset();
  16841. for (var index = 0; index < this.blocks.length; index++) {
  16842. var block = this.blocks[index];
  16843. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16844. }
  16845. if (allowDuplicate) {
  16846. this._selectionContent.concat(this.dynamicContent);
  16847. }
  16848. else {
  16849. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16850. }
  16851. return this._selectionContent;
  16852. };
  16853. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16854. this._selectionContent.reset();
  16855. for (var index = 0; index < this.blocks.length; index++) {
  16856. var block = this.blocks[index];
  16857. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16858. }
  16859. if (allowDuplicate) {
  16860. this._selectionContent.concat(this.dynamicContent);
  16861. }
  16862. else {
  16863. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16864. }
  16865. return this._selectionContent;
  16866. };
  16867. Octree.prototype.intersectsRay = function (ray) {
  16868. this._selectionContent.reset();
  16869. for (var index = 0; index < this.blocks.length; index++) {
  16870. var block = this.blocks[index];
  16871. block.intersectsRay(ray, this._selectionContent);
  16872. }
  16873. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16874. return this._selectionContent;
  16875. };
  16876. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16877. target.blocks = new Array();
  16878. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16879. for (var x = 0; x < 2; x++) {
  16880. for (var y = 0; y < 2; y++) {
  16881. for (var z = 0; z < 2; z++) {
  16882. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16883. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16884. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16885. block.addEntries(entries);
  16886. target.blocks.push(block);
  16887. }
  16888. }
  16889. }
  16890. };
  16891. Octree.CreationFuncForMeshes = function (entry, block) {
  16892. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16893. block.entries.push(entry);
  16894. }
  16895. };
  16896. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16897. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16898. block.entries.push(entry);
  16899. }
  16900. };
  16901. return Octree;
  16902. })();
  16903. BABYLON.Octree = Octree;
  16904. })(BABYLON || (BABYLON = {}));
  16905. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16906. (function (BABYLON) {
  16907. var OctreeBlock = (function () {
  16908. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16909. this.entries = new Array();
  16910. this._boundingVectors = new Array();
  16911. this._capacity = capacity;
  16912. this._depth = depth;
  16913. this._maxDepth = maxDepth;
  16914. this._creationFunc = creationFunc;
  16915. this._minPoint = minPoint;
  16916. this._maxPoint = maxPoint;
  16917. this._boundingVectors.push(minPoint.clone());
  16918. this._boundingVectors.push(maxPoint.clone());
  16919. this._boundingVectors.push(minPoint.clone());
  16920. this._boundingVectors[2].x = maxPoint.x;
  16921. this._boundingVectors.push(minPoint.clone());
  16922. this._boundingVectors[3].y = maxPoint.y;
  16923. this._boundingVectors.push(minPoint.clone());
  16924. this._boundingVectors[4].z = maxPoint.z;
  16925. this._boundingVectors.push(maxPoint.clone());
  16926. this._boundingVectors[5].z = minPoint.z;
  16927. this._boundingVectors.push(maxPoint.clone());
  16928. this._boundingVectors[6].x = minPoint.x;
  16929. this._boundingVectors.push(maxPoint.clone());
  16930. this._boundingVectors[7].y = minPoint.y;
  16931. }
  16932. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16933. // Property
  16934. get: function () {
  16935. return this._capacity;
  16936. },
  16937. enumerable: true,
  16938. configurable: true
  16939. });
  16940. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16941. get: function () {
  16942. return this._minPoint;
  16943. },
  16944. enumerable: true,
  16945. configurable: true
  16946. });
  16947. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16948. get: function () {
  16949. return this._maxPoint;
  16950. },
  16951. enumerable: true,
  16952. configurable: true
  16953. });
  16954. // Methods
  16955. OctreeBlock.prototype.addEntry = function (entry) {
  16956. if (this.blocks) {
  16957. for (var index = 0; index < this.blocks.length; index++) {
  16958. var block = this.blocks[index];
  16959. block.addEntry(entry);
  16960. }
  16961. return;
  16962. }
  16963. this._creationFunc(entry, this);
  16964. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16965. this.createInnerBlocks();
  16966. }
  16967. };
  16968. OctreeBlock.prototype.addEntries = function (entries) {
  16969. for (var index = 0; index < entries.length; index++) {
  16970. var mesh = entries[index];
  16971. this.addEntry(mesh);
  16972. }
  16973. };
  16974. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16975. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16976. if (this.blocks) {
  16977. for (var index = 0; index < this.blocks.length; index++) {
  16978. var block = this.blocks[index];
  16979. block.select(frustumPlanes, selection, allowDuplicate);
  16980. }
  16981. return;
  16982. }
  16983. if (allowDuplicate) {
  16984. selection.concat(this.entries);
  16985. }
  16986. else {
  16987. selection.concatWithNoDuplicate(this.entries);
  16988. }
  16989. }
  16990. };
  16991. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16992. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16993. if (this.blocks) {
  16994. for (var index = 0; index < this.blocks.length; index++) {
  16995. var block = this.blocks[index];
  16996. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16997. }
  16998. return;
  16999. }
  17000. if (allowDuplicate) {
  17001. selection.concat(this.entries);
  17002. }
  17003. else {
  17004. selection.concatWithNoDuplicate(this.entries);
  17005. }
  17006. }
  17007. };
  17008. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  17009. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  17010. if (this.blocks) {
  17011. for (var index = 0; index < this.blocks.length; index++) {
  17012. var block = this.blocks[index];
  17013. block.intersectsRay(ray, selection);
  17014. }
  17015. return;
  17016. }
  17017. selection.concatWithNoDuplicate(this.entries);
  17018. }
  17019. };
  17020. OctreeBlock.prototype.createInnerBlocks = function () {
  17021. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  17022. };
  17023. return OctreeBlock;
  17024. })();
  17025. BABYLON.OctreeBlock = OctreeBlock;
  17026. })(BABYLON || (BABYLON = {}));
  17027. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  17028. (function (BABYLON) {
  17029. var Bone = (function () {
  17030. function Bone(name, skeleton, parentBone, matrix) {
  17031. this.name = name;
  17032. this.children = new Array();
  17033. this.animations = new Array();
  17034. this._worldTransform = new BABYLON.Matrix();
  17035. this._absoluteTransform = new BABYLON.Matrix();
  17036. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  17037. this._skeleton = skeleton;
  17038. this._matrix = matrix;
  17039. this._baseMatrix = matrix;
  17040. skeleton.bones.push(this);
  17041. if (parentBone) {
  17042. this._parent = parentBone;
  17043. parentBone.children.push(this);
  17044. }
  17045. else {
  17046. this._parent = null;
  17047. }
  17048. this._updateDifferenceMatrix();
  17049. }
  17050. // Members
  17051. Bone.prototype.getParent = function () {
  17052. return this._parent;
  17053. };
  17054. Bone.prototype.getLocalMatrix = function () {
  17055. return this._matrix;
  17056. };
  17057. Bone.prototype.getBaseMatrix = function () {
  17058. return this._baseMatrix;
  17059. };
  17060. Bone.prototype.getWorldMatrix = function () {
  17061. return this._worldTransform;
  17062. };
  17063. Bone.prototype.getInvertedAbsoluteTransform = function () {
  17064. return this._invertedAbsoluteTransform;
  17065. };
  17066. Bone.prototype.getAbsoluteMatrix = function () {
  17067. var matrix = this._matrix.clone();
  17068. var parent = this._parent;
  17069. while (parent) {
  17070. matrix = matrix.multiply(parent.getLocalMatrix());
  17071. parent = parent.getParent();
  17072. }
  17073. return matrix;
  17074. };
  17075. // Methods
  17076. Bone.prototype.updateMatrix = function (matrix) {
  17077. this._matrix = matrix;
  17078. this._skeleton._markAsDirty();
  17079. this._updateDifferenceMatrix();
  17080. };
  17081. Bone.prototype._updateDifferenceMatrix = function () {
  17082. if (this._parent) {
  17083. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  17084. }
  17085. else {
  17086. this._absoluteTransform.copyFrom(this._matrix);
  17087. }
  17088. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  17089. for (var index = 0; index < this.children.length; index++) {
  17090. this.children[index]._updateDifferenceMatrix();
  17091. }
  17092. };
  17093. Bone.prototype.markAsDirty = function () {
  17094. this._skeleton._markAsDirty();
  17095. };
  17096. return Bone;
  17097. })();
  17098. BABYLON.Bone = Bone;
  17099. })(BABYLON || (BABYLON = {}));
  17100. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  17101. (function (BABYLON) {
  17102. var Skeleton = (function () {
  17103. function Skeleton(name, id, scene) {
  17104. this.name = name;
  17105. this.id = id;
  17106. this.bones = new Array();
  17107. this._isDirty = true;
  17108. this._identity = BABYLON.Matrix.Identity();
  17109. this.bones = [];
  17110. this._scene = scene;
  17111. scene.skeletons.push(this);
  17112. }
  17113. // Members
  17114. Skeleton.prototype.getTransformMatrices = function () {
  17115. return this._transformMatrices;
  17116. };
  17117. // Methods
  17118. Skeleton.prototype._markAsDirty = function () {
  17119. this._isDirty = true;
  17120. };
  17121. Skeleton.prototype.prepare = function () {
  17122. if (!this._isDirty) {
  17123. return;
  17124. }
  17125. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  17126. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  17127. }
  17128. for (var index = 0; index < this.bones.length; index++) {
  17129. var bone = this.bones[index];
  17130. var parentBone = bone.getParent();
  17131. if (parentBone) {
  17132. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  17133. }
  17134. else {
  17135. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  17136. }
  17137. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  17138. }
  17139. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  17140. this._isDirty = false;
  17141. this._scene._activeBones += this.bones.length;
  17142. };
  17143. Skeleton.prototype.getAnimatables = function () {
  17144. if (!this._animatables || this._animatables.length !== this.bones.length) {
  17145. this._animatables = [];
  17146. for (var index = 0; index < this.bones.length; index++) {
  17147. this._animatables.push(this.bones[index]);
  17148. }
  17149. }
  17150. return this._animatables;
  17151. };
  17152. Skeleton.prototype.clone = function (name, id) {
  17153. var result = new Skeleton(name, id || name, this._scene);
  17154. for (var index = 0; index < this.bones.length; index++) {
  17155. var source = this.bones[index];
  17156. var parentBone = null;
  17157. if (source.getParent()) {
  17158. var parentIndex = this.bones.indexOf(source.getParent());
  17159. parentBone = result.bones[parentIndex];
  17160. }
  17161. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  17162. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  17163. }
  17164. return result;
  17165. };
  17166. return Skeleton;
  17167. })();
  17168. BABYLON.Skeleton = Skeleton;
  17169. })(BABYLON || (BABYLON = {}));
  17170. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  17171. (function (BABYLON) {
  17172. var PostProcess = (function () {
  17173. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  17174. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  17175. this.name = name;
  17176. this.width = -1;
  17177. this.height = -1;
  17178. this._reusable = false;
  17179. this._textures = new BABYLON.SmartArray(2);
  17180. this._currentRenderTextureInd = 0;
  17181. if (camera != null) {
  17182. this._camera = camera;
  17183. this._scene = camera.getScene();
  17184. camera.attachPostProcess(this);
  17185. this._engine = this._scene.getEngine();
  17186. }
  17187. else {
  17188. this._engine = engine;
  17189. }
  17190. this._renderRatio = ratio;
  17191. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  17192. this._reusable = reusable || false;
  17193. samplers = samplers || [];
  17194. samplers.push("textureSampler");
  17195. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  17196. }
  17197. PostProcess.prototype.isReusable = function () {
  17198. return this._reusable;
  17199. };
  17200. PostProcess.prototype.activate = function (camera, sourceTexture) {
  17201. camera = camera || this._camera;
  17202. var scene = camera.getScene();
  17203. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  17204. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  17205. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  17206. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  17207. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  17208. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  17209. if (this._textures.length > 0) {
  17210. for (var i = 0; i < this._textures.length; i++) {
  17211. this._engine._releaseTexture(this._textures.data[i]);
  17212. }
  17213. this._textures.reset();
  17214. }
  17215. this.width = desiredWidth;
  17216. this.height = desiredHeight;
  17217. 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 }));
  17218. if (this._reusable) {
  17219. 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 }));
  17220. }
  17221. if (this.onSizeChanged) {
  17222. this.onSizeChanged();
  17223. }
  17224. }
  17225. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  17226. if (this.onActivate) {
  17227. this.onActivate(camera);
  17228. }
  17229. // Clear
  17230. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  17231. if (this._reusable) {
  17232. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  17233. }
  17234. };
  17235. PostProcess.prototype.apply = function () {
  17236. // Check
  17237. if (!this._effect.isReady())
  17238. return null;
  17239. // States
  17240. this._engine.enableEffect(this._effect);
  17241. this._engine.setState(false);
  17242. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17243. this._engine.setDepthBuffer(false);
  17244. this._engine.setDepthWrite(false);
  17245. // Texture
  17246. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  17247. // Parameters
  17248. if (this.onApply) {
  17249. this.onApply(this._effect);
  17250. }
  17251. return this._effect;
  17252. };
  17253. PostProcess.prototype.dispose = function (camera) {
  17254. camera = camera || this._camera;
  17255. if (this._textures.length > 0) {
  17256. for (var i = 0; i < this._textures.length; i++) {
  17257. this._engine._releaseTexture(this._textures.data[i]);
  17258. }
  17259. this._textures.reset();
  17260. }
  17261. if (!camera) {
  17262. return;
  17263. }
  17264. camera.detachPostProcess(this);
  17265. var index = camera._postProcesses.indexOf(this);
  17266. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  17267. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  17268. }
  17269. };
  17270. return PostProcess;
  17271. })();
  17272. BABYLON.PostProcess = PostProcess;
  17273. })(BABYLON || (BABYLON = {}));
  17274. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  17275. (function (BABYLON) {
  17276. var PostProcessManager = (function () {
  17277. function PostProcessManager(scene) {
  17278. this._vertexDeclaration = [2];
  17279. this._vertexStrideSize = 2 * 4;
  17280. this._scene = scene;
  17281. // VBO
  17282. var vertices = [];
  17283. vertices.push(1, 1);
  17284. vertices.push(-1, 1);
  17285. vertices.push(-1, -1);
  17286. vertices.push(1, -1);
  17287. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17288. // Indices
  17289. var indices = [];
  17290. indices.push(0);
  17291. indices.push(1);
  17292. indices.push(2);
  17293. indices.push(0);
  17294. indices.push(2);
  17295. indices.push(3);
  17296. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17297. }
  17298. // Methods
  17299. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  17300. var postProcesses = this._scene.activeCamera._postProcesses;
  17301. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17302. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17303. return false;
  17304. }
  17305. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  17306. return true;
  17307. };
  17308. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  17309. var engine = this._scene.getEngine();
  17310. for (var index = 0; index < postProcesses.length; index++) {
  17311. if (index < postProcesses.length - 1) {
  17312. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  17313. }
  17314. else {
  17315. if (targetTexture) {
  17316. engine.bindFramebuffer(targetTexture);
  17317. }
  17318. else {
  17319. engine.restoreDefaultFramebuffer();
  17320. }
  17321. }
  17322. var pp = postProcesses[index];
  17323. var effect = pp.apply();
  17324. if (effect) {
  17325. if (pp.onBeforeRender) {
  17326. pp.onBeforeRender(effect);
  17327. }
  17328. // VBOs
  17329. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17330. // Draw order
  17331. engine.draw(true, 0, 6);
  17332. }
  17333. }
  17334. // Restore depth buffer
  17335. engine.setDepthBuffer(true);
  17336. engine.setDepthWrite(true);
  17337. };
  17338. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  17339. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  17340. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  17341. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  17342. return;
  17343. }
  17344. var engine = this._scene.getEngine();
  17345. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17346. if (index < postProcessesTakenIndices.length - 1) {
  17347. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17348. }
  17349. else {
  17350. if (targetTexture) {
  17351. engine.bindFramebuffer(targetTexture);
  17352. }
  17353. else {
  17354. engine.restoreDefaultFramebuffer();
  17355. }
  17356. }
  17357. if (doNotPresent) {
  17358. break;
  17359. }
  17360. var pp = postProcesses[postProcessesTakenIndices[index]];
  17361. var effect = pp.apply();
  17362. if (effect) {
  17363. if (pp.onBeforeRender) {
  17364. pp.onBeforeRender(effect);
  17365. }
  17366. // VBOs
  17367. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17368. // Draw order
  17369. engine.draw(true, 0, 6);
  17370. }
  17371. }
  17372. // Restore depth buffer
  17373. engine.setDepthBuffer(true);
  17374. engine.setDepthWrite(true);
  17375. };
  17376. PostProcessManager.prototype.dispose = function () {
  17377. if (this._vertexBuffer) {
  17378. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17379. this._vertexBuffer = null;
  17380. }
  17381. if (this._indexBuffer) {
  17382. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17383. this._indexBuffer = null;
  17384. }
  17385. };
  17386. return PostProcessManager;
  17387. })();
  17388. BABYLON.PostProcessManager = PostProcessManager;
  17389. })(BABYLON || (BABYLON = {}));
  17390. //# sourceMappingURL=babylon.postProcessManager.js.map
  17391. var BABYLON;
  17392. (function (BABYLON) {
  17393. var PassPostProcess = (function (_super) {
  17394. __extends(PassPostProcess, _super);
  17395. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17396. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17397. }
  17398. return PassPostProcess;
  17399. })(BABYLON.PostProcess);
  17400. BABYLON.PassPostProcess = PassPostProcess;
  17401. })(BABYLON || (BABYLON = {}));
  17402. //# sourceMappingURL=babylon.passPostProcess.js.map
  17403. var BABYLON;
  17404. (function (BABYLON) {
  17405. var BlurPostProcess = (function (_super) {
  17406. __extends(BlurPostProcess, _super);
  17407. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17408. var _this = this;
  17409. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17410. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17411. this.direction = direction;
  17412. this.blurWidth = blurWidth;
  17413. this.onApply = function (effect) {
  17414. effect.setFloat2("screenSize", _this.width, _this.height);
  17415. effect.setVector2("direction", _this.direction);
  17416. effect.setFloat("blurWidth", _this.blurWidth);
  17417. };
  17418. }
  17419. return BlurPostProcess;
  17420. })(BABYLON.PostProcess);
  17421. BABYLON.BlurPostProcess = BlurPostProcess;
  17422. })(BABYLON || (BABYLON = {}));
  17423. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17424. var BABYLON;
  17425. (function (BABYLON) {
  17426. var FilterPostProcess = (function (_super) {
  17427. __extends(FilterPostProcess, _super);
  17428. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17429. var _this = this;
  17430. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17431. this.kernelMatrix = kernelMatrix;
  17432. this.onApply = function (effect) {
  17433. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17434. };
  17435. }
  17436. return FilterPostProcess;
  17437. })(BABYLON.PostProcess);
  17438. BABYLON.FilterPostProcess = FilterPostProcess;
  17439. })(BABYLON || (BABYLON = {}));
  17440. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17441. var BABYLON;
  17442. (function (BABYLON) {
  17443. var RefractionPostProcess = (function (_super) {
  17444. __extends(RefractionPostProcess, _super);
  17445. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17446. var _this = this;
  17447. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17448. this.color = color;
  17449. this.depth = depth;
  17450. this.colorLevel = colorLevel;
  17451. this.onActivate = function (cam) {
  17452. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17453. };
  17454. this.onApply = function (effect) {
  17455. effect.setColor3("baseColor", _this.color);
  17456. effect.setFloat("depth", _this.depth);
  17457. effect.setFloat("colorLevel", _this.colorLevel);
  17458. effect.setTexture("refractionSampler", _this._refRexture);
  17459. };
  17460. }
  17461. // Methods
  17462. RefractionPostProcess.prototype.dispose = function (camera) {
  17463. if (this._refRexture) {
  17464. this._refRexture.dispose();
  17465. }
  17466. _super.prototype.dispose.call(this, camera);
  17467. };
  17468. return RefractionPostProcess;
  17469. })(BABYLON.PostProcess);
  17470. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17471. })(BABYLON || (BABYLON = {}));
  17472. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17473. var BABYLON;
  17474. (function (BABYLON) {
  17475. var BlackAndWhitePostProcess = (function (_super) {
  17476. __extends(BlackAndWhitePostProcess, _super);
  17477. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17478. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17479. }
  17480. return BlackAndWhitePostProcess;
  17481. })(BABYLON.PostProcess);
  17482. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17483. })(BABYLON || (BABYLON = {}));
  17484. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17485. var BABYLON;
  17486. (function (BABYLON) {
  17487. var ConvolutionPostProcess = (function (_super) {
  17488. __extends(ConvolutionPostProcess, _super);
  17489. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17490. var _this = this;
  17491. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17492. this.kernel = kernel;
  17493. this.onApply = function (effect) {
  17494. effect.setFloat2("screenSize", _this.width, _this.height);
  17495. effect.setArray("kernel", _this.kernel);
  17496. };
  17497. }
  17498. // Statics
  17499. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17500. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17501. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17502. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17503. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17504. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17505. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17506. return ConvolutionPostProcess;
  17507. })(BABYLON.PostProcess);
  17508. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17509. })(BABYLON || (BABYLON = {}));
  17510. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17511. var BABYLON;
  17512. (function (BABYLON) {
  17513. var FxaaPostProcess = (function (_super) {
  17514. __extends(FxaaPostProcess, _super);
  17515. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17516. var _this = this;
  17517. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17518. this.onSizeChanged = function () {
  17519. _this.texelWidth = 1.0 / _this.width;
  17520. _this.texelHeight = 1.0 / _this.height;
  17521. };
  17522. this.onApply = function (effect) {
  17523. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17524. };
  17525. }
  17526. return FxaaPostProcess;
  17527. })(BABYLON.PostProcess);
  17528. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17529. })(BABYLON || (BABYLON = {}));
  17530. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17531. (function (BABYLON) {
  17532. var LensFlare = (function () {
  17533. function LensFlare(size, position, color, imgUrl, system) {
  17534. this.size = size;
  17535. this.position = position;
  17536. this.dispose = function () {
  17537. if (this.texture) {
  17538. this.texture.dispose();
  17539. }
  17540. // Remove from scene
  17541. var index = this._system.lensFlares.indexOf(this);
  17542. this._system.lensFlares.splice(index, 1);
  17543. };
  17544. this.color = color || new BABYLON.Color3(1, 1, 1);
  17545. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17546. this._system = system;
  17547. system.lensFlares.push(this);
  17548. }
  17549. return LensFlare;
  17550. })();
  17551. BABYLON.LensFlare = LensFlare;
  17552. })(BABYLON || (BABYLON = {}));
  17553. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17554. (function (BABYLON) {
  17555. var LensFlareSystem = (function () {
  17556. function LensFlareSystem(name, emitter, scene) {
  17557. this.name = name;
  17558. this.lensFlares = new Array();
  17559. this.borderLimit = 300;
  17560. this._vertexDeclaration = [2];
  17561. this._vertexStrideSize = 2 * 4;
  17562. this._isEnabled = true;
  17563. this._scene = scene;
  17564. this._emitter = emitter;
  17565. scene.lensFlareSystems.push(this);
  17566. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17567. // VBO
  17568. var vertices = [];
  17569. vertices.push(1, 1);
  17570. vertices.push(-1, 1);
  17571. vertices.push(-1, -1);
  17572. vertices.push(1, -1);
  17573. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17574. // Indices
  17575. var indices = [];
  17576. indices.push(0);
  17577. indices.push(1);
  17578. indices.push(2);
  17579. indices.push(0);
  17580. indices.push(2);
  17581. indices.push(3);
  17582. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17583. // Effects
  17584. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17585. }
  17586. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17587. get: function () {
  17588. return this._isEnabled;
  17589. },
  17590. set: function (value) {
  17591. this._isEnabled = value;
  17592. },
  17593. enumerable: true,
  17594. configurable: true
  17595. });
  17596. LensFlareSystem.prototype.getScene = function () {
  17597. return this._scene;
  17598. };
  17599. LensFlareSystem.prototype.getEmitter = function () {
  17600. return this._emitter;
  17601. };
  17602. LensFlareSystem.prototype.getEmitterPosition = function () {
  17603. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17604. };
  17605. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17606. var position = this.getEmitterPosition();
  17607. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17608. this._positionX = position.x;
  17609. this._positionY = position.y;
  17610. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17611. if (position.z > 0) {
  17612. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17613. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17614. return true;
  17615. }
  17616. }
  17617. return false;
  17618. };
  17619. LensFlareSystem.prototype._isVisible = function () {
  17620. if (!this._isEnabled) {
  17621. return false;
  17622. }
  17623. var emitterPosition = this.getEmitterPosition();
  17624. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17625. var distance = direction.length();
  17626. direction.normalize();
  17627. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17628. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17629. return !pickInfo.hit || pickInfo.distance > distance;
  17630. };
  17631. LensFlareSystem.prototype.render = function () {
  17632. if (!this._effect.isReady())
  17633. return false;
  17634. var engine = this._scene.getEngine();
  17635. var viewport = this._scene.activeCamera.viewport;
  17636. var globalViewport = viewport.toGlobal(engine);
  17637. // Position
  17638. if (!this.computeEffectivePosition(globalViewport)) {
  17639. return false;
  17640. }
  17641. // Visibility
  17642. if (!this._isVisible()) {
  17643. return false;
  17644. }
  17645. // Intensity
  17646. var awayX;
  17647. var awayY;
  17648. if (this._positionX < this.borderLimit + globalViewport.x) {
  17649. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17650. }
  17651. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17652. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17653. }
  17654. else {
  17655. awayX = 0;
  17656. }
  17657. if (this._positionY < this.borderLimit + globalViewport.y) {
  17658. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17659. }
  17660. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17661. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17662. }
  17663. else {
  17664. awayY = 0;
  17665. }
  17666. var away = (awayX > awayY) ? awayX : awayY;
  17667. if (away > this.borderLimit) {
  17668. away = this.borderLimit;
  17669. }
  17670. var intensity = 1.0 - (away / this.borderLimit);
  17671. if (intensity < 0) {
  17672. return false;
  17673. }
  17674. if (intensity > 1.0) {
  17675. intensity = 1.0;
  17676. }
  17677. // Position
  17678. var centerX = globalViewport.x + globalViewport.width / 2;
  17679. var centerY = globalViewport.y + globalViewport.height / 2;
  17680. var distX = centerX - this._positionX;
  17681. var distY = centerY - this._positionY;
  17682. // Effects
  17683. engine.enableEffect(this._effect);
  17684. engine.setState(false);
  17685. engine.setDepthBuffer(false);
  17686. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17687. // VBOs
  17688. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17689. for (var index = 0; index < this.lensFlares.length; index++) {
  17690. var flare = this.lensFlares[index];
  17691. var x = centerX - (distX * flare.position);
  17692. var y = centerY - (distY * flare.position);
  17693. var cw = flare.size;
  17694. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17695. var cx = 2 * (x / globalViewport.width) - 1.0;
  17696. var cy = 1.0 - 2 * (y / globalViewport.height);
  17697. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17698. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17699. // Texture
  17700. this._effect.setTexture("textureSampler", flare.texture);
  17701. // Color
  17702. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17703. // Draw order
  17704. engine.draw(true, 0, 6);
  17705. }
  17706. engine.setDepthBuffer(true);
  17707. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17708. return true;
  17709. };
  17710. LensFlareSystem.prototype.dispose = function () {
  17711. if (this._vertexBuffer) {
  17712. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17713. this._vertexBuffer = null;
  17714. }
  17715. if (this._indexBuffer) {
  17716. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17717. this._indexBuffer = null;
  17718. }
  17719. while (this.lensFlares.length) {
  17720. this.lensFlares[0].dispose();
  17721. }
  17722. // Remove from scene
  17723. var index = this._scene.lensFlareSystems.indexOf(this);
  17724. this._scene.lensFlareSystems.splice(index, 1);
  17725. };
  17726. return LensFlareSystem;
  17727. })();
  17728. BABYLON.LensFlareSystem = LensFlareSystem;
  17729. })(BABYLON || (BABYLON = {}));
  17730. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17731. (function (BABYLON) {
  17732. var IntersectionInfo = (function () {
  17733. function IntersectionInfo(bu, bv, distance) {
  17734. this.bu = bu;
  17735. this.bv = bv;
  17736. this.distance = distance;
  17737. this.faceId = 0;
  17738. this.subMeshId = 0;
  17739. }
  17740. return IntersectionInfo;
  17741. })();
  17742. BABYLON.IntersectionInfo = IntersectionInfo;
  17743. var PickingInfo = (function () {
  17744. function PickingInfo() {
  17745. this.hit = false;
  17746. this.distance = 0;
  17747. this.pickedPoint = null;
  17748. this.pickedMesh = null;
  17749. this.bu = 0;
  17750. this.bv = 0;
  17751. this.faceId = -1;
  17752. this.subMeshId = 0;
  17753. }
  17754. // Methods
  17755. PickingInfo.prototype.getNormal = function () {
  17756. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17757. return null;
  17758. }
  17759. var indices = this.pickedMesh.getIndices();
  17760. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17761. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17762. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17763. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17764. normal0 = normal0.scale(this.bu);
  17765. normal1 = normal1.scale(this.bv);
  17766. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17767. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17768. };
  17769. PickingInfo.prototype.getTextureCoordinates = function () {
  17770. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17771. return null;
  17772. }
  17773. var indices = this.pickedMesh.getIndices();
  17774. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17775. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17776. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17777. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17778. uv0 = uv0.scale(this.bu);
  17779. uv1 = uv1.scale(this.bv);
  17780. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17781. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17782. };
  17783. return PickingInfo;
  17784. })();
  17785. BABYLON.PickingInfo = PickingInfo;
  17786. })(BABYLON || (BABYLON = {}));
  17787. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17788. (function (BABYLON) {
  17789. var FilesInput = (function () {
  17790. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17791. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17792. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17793. this._engine = p_engine;
  17794. this._canvas = p_canvas;
  17795. this._currentScene = p_scene;
  17796. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17797. this._progressCallback = p_progressCallback;
  17798. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17799. this._textureLoadingCallback = p_textureLoadingCallback;
  17800. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17801. }
  17802. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17803. var _this = this;
  17804. if (p_elementToMonitor) {
  17805. this._elementToMonitor = p_elementToMonitor;
  17806. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17807. _this.drag(e);
  17808. }, false);
  17809. this._elementToMonitor.addEventListener("dragover", function (e) {
  17810. _this.drag(e);
  17811. }, false);
  17812. this._elementToMonitor.addEventListener("drop", function (e) {
  17813. _this.drop(e);
  17814. }, false);
  17815. }
  17816. };
  17817. FilesInput.prototype.renderFunction = function () {
  17818. if (this._additionnalRenderLoopLogicCallback) {
  17819. this._additionnalRenderLoopLogicCallback();
  17820. }
  17821. if (this._currentScene) {
  17822. if (this._textureLoadingCallback) {
  17823. var remaining = this._currentScene.getWaitingItemsCount();
  17824. if (remaining > 0) {
  17825. this._textureLoadingCallback(remaining);
  17826. }
  17827. }
  17828. this._currentScene.render();
  17829. }
  17830. };
  17831. FilesInput.prototype.drag = function (e) {
  17832. e.stopPropagation();
  17833. e.preventDefault();
  17834. };
  17835. FilesInput.prototype.drop = function (eventDrop) {
  17836. eventDrop.stopPropagation();
  17837. eventDrop.preventDefault();
  17838. this.loadFiles(eventDrop);
  17839. };
  17840. FilesInput.prototype.loadFiles = function (event) {
  17841. if (this._startingProcessingFilesCallback)
  17842. this._startingProcessingFilesCallback();
  17843. // Handling data transfer via drag'n'drop
  17844. if (event && event.dataTransfer && event.dataTransfer.files) {
  17845. this._filesToLoad = event.dataTransfer.files;
  17846. }
  17847. // Handling files from input files
  17848. if (event && event.target && event.target.files) {
  17849. this._filesToLoad = event.target.files;
  17850. }
  17851. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17852. for (var i = 0; i < this._filesToLoad.length; i++) {
  17853. switch (this._filesToLoad[i].type) {
  17854. case "image/jpeg":
  17855. case "image/png":
  17856. case "image/bmp":
  17857. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17858. break;
  17859. case "image/targa":
  17860. case "image/vnd.ms-dds":
  17861. case "audio/wav":
  17862. case "audio/x-wav":
  17863. case "audio/mp3":
  17864. case "audio/mpeg":
  17865. case "audio/mpeg3":
  17866. case "audio/x-mpeg-3":
  17867. case "audio/ogg":
  17868. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17869. break;
  17870. default:
  17871. 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) {
  17872. this._sceneFileToLoad = this._filesToLoad[i];
  17873. }
  17874. break;
  17875. }
  17876. }
  17877. this.reload();
  17878. }
  17879. };
  17880. FilesInput.prototype.reload = function () {
  17881. var _this = this;
  17882. var that = this;
  17883. // If a ".babylon" file has been provided
  17884. if (this._sceneFileToLoad) {
  17885. if (this._currentScene) {
  17886. this._engine.stopRenderLoop();
  17887. this._currentScene.dispose();
  17888. }
  17889. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17890. that._currentScene = newScene;
  17891. // Wait for textures and shaders to be ready
  17892. that._currentScene.executeWhenReady(function () {
  17893. // Attach camera to canvas inputs
  17894. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17895. that._currentScene.createDefaultCameraOrLight();
  17896. }
  17897. that._currentScene.activeCamera.attachControl(that._canvas);
  17898. if (that._sceneLoadedCallback) {
  17899. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17900. }
  17901. that._engine.runRenderLoop(function () {
  17902. that.renderFunction();
  17903. });
  17904. });
  17905. }, function (progress) {
  17906. if (_this._progressCallback) {
  17907. _this._progressCallback(progress);
  17908. }
  17909. });
  17910. }
  17911. else {
  17912. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17913. }
  17914. };
  17915. FilesInput.FilesTextures = new Array();
  17916. FilesInput.FilesToLoad = new Array();
  17917. return FilesInput;
  17918. })();
  17919. BABYLON.FilesInput = FilesInput;
  17920. })(BABYLON || (BABYLON = {}));
  17921. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17922. (function (BABYLON) {
  17923. var OimoJSPlugin = (function () {
  17924. function OimoJSPlugin() {
  17925. this._registeredMeshes = [];
  17926. /**
  17927. * Update the body position according to the mesh position
  17928. * @param mesh
  17929. */
  17930. this.updateBodyPosition = function (mesh) {
  17931. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17932. var registeredMesh = this._registeredMeshes[index];
  17933. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17934. var body = registeredMesh.body.body;
  17935. mesh.computeWorldMatrix(true);
  17936. var center = mesh.getBoundingInfo().boundingBox.center;
  17937. body.setPosition(center.x, center.y, center.z);
  17938. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17939. return;
  17940. }
  17941. // Case where the parent has been updated
  17942. if (registeredMesh.mesh.parent === mesh) {
  17943. mesh.computeWorldMatrix(true);
  17944. registeredMesh.mesh.computeWorldMatrix(true);
  17945. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17946. var absoluteRotation = mesh.rotation;
  17947. body = registeredMesh.body.body;
  17948. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17949. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17950. return;
  17951. }
  17952. }
  17953. };
  17954. }
  17955. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17956. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17957. };
  17958. OimoJSPlugin.prototype.initialize = function (iterations) {
  17959. this._world = new OIMO.World();
  17960. this._world.clear();
  17961. };
  17962. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17963. this._world.gravity = gravity;
  17964. };
  17965. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17966. var body = null;
  17967. this.unregisterMesh(mesh);
  17968. mesh.computeWorldMatrix(true);
  17969. var initialRotation = null;
  17970. if (mesh.rotationQuaternion) {
  17971. initialRotation = mesh.rotationQuaternion.clone();
  17972. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17973. mesh.computeWorldMatrix(true);
  17974. }
  17975. var bbox = mesh.getBoundingInfo().boundingBox;
  17976. // The delta between the mesh position and the mesh bounding box center
  17977. var deltaPosition = mesh.position.subtract(bbox.center);
  17978. // Transform delta position with the rotation
  17979. if (initialRotation) {
  17980. var m = new BABYLON.Matrix();
  17981. initialRotation.toRotationMatrix(m);
  17982. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17983. }
  17984. switch (impostor) {
  17985. case BABYLON.PhysicsEngine.SphereImpostor:
  17986. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17987. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17988. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17989. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17990. body = new OIMO.Body({
  17991. type: 'sphere',
  17992. size: [size],
  17993. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17994. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17995. move: options.mass != 0,
  17996. config: [options.mass, options.friction, options.restitution],
  17997. world: this._world
  17998. });
  17999. break;
  18000. case BABYLON.PhysicsEngine.PlaneImpostor:
  18001. case BABYLON.PhysicsEngine.CylinderImpostor:
  18002. case BABYLON.PhysicsEngine.BoxImpostor:
  18003. var min = bbox.minimumWorld;
  18004. var max = bbox.maximumWorld;
  18005. var box = max.subtract(min);
  18006. var sizeX = this._checkWithEpsilon(box.x);
  18007. var sizeY = this._checkWithEpsilon(box.y);
  18008. var sizeZ = this._checkWithEpsilon(box.z);
  18009. body = new OIMO.Body({
  18010. type: 'box',
  18011. size: [sizeX, sizeY, sizeZ],
  18012. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  18013. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  18014. move: options.mass != 0,
  18015. config: [options.mass, options.friction, options.restitution],
  18016. world: this._world
  18017. });
  18018. break;
  18019. }
  18020. //If quaternion was set as the rotation of the object
  18021. if (initialRotation) {
  18022. //We have to access the rigid body's properties to set the quaternion.
  18023. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  18024. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  18025. //update the internal rotation matrix
  18026. body.body.syncShapes();
  18027. }
  18028. this._registeredMeshes.push({
  18029. mesh: mesh,
  18030. body: body,
  18031. delta: deltaPosition
  18032. });
  18033. return body;
  18034. };
  18035. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  18036. var types = [], sizes = [], positions = [], rotations = [];
  18037. var initialMesh = parts[0].mesh;
  18038. for (var index = 0; index < parts.length; index++) {
  18039. var part = parts[index];
  18040. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  18041. types.push(bodyParameters.type);
  18042. sizes.push.apply(sizes, bodyParameters.size);
  18043. positions.push.apply(positions, bodyParameters.pos);
  18044. rotations.push.apply(rotations, bodyParameters.rot);
  18045. }
  18046. var body = new OIMO.Body({
  18047. type: types,
  18048. size: sizes,
  18049. pos: positions,
  18050. rot: rotations,
  18051. move: options.mass != 0,
  18052. config: [options.mass, options.friction, options.restitution],
  18053. world: this._world
  18054. });
  18055. this._registeredMeshes.push({
  18056. mesh: initialMesh,
  18057. body: body
  18058. });
  18059. return body;
  18060. };
  18061. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  18062. var bodyParameters = null;
  18063. var mesh = part.mesh;
  18064. // We need the bounding box/sphere info to compute the physics body
  18065. mesh.computeWorldMatrix();
  18066. switch (part.impostor) {
  18067. case BABYLON.PhysicsEngine.SphereImpostor:
  18068. var bbox = mesh.getBoundingInfo().boundingBox;
  18069. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  18070. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  18071. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  18072. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  18073. bodyParameters = {
  18074. type: 'sphere',
  18075. /* bug with oimo : sphere needs 3 sizes in this case */
  18076. size: [size, -1, -1],
  18077. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  18078. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18079. };
  18080. break;
  18081. case BABYLON.PhysicsEngine.PlaneImpostor:
  18082. case BABYLON.PhysicsEngine.BoxImpostor:
  18083. bbox = mesh.getBoundingInfo().boundingBox;
  18084. var min = bbox.minimumWorld;
  18085. var max = bbox.maximumWorld;
  18086. var box = max.subtract(min);
  18087. var sizeX = this._checkWithEpsilon(box.x);
  18088. var sizeY = this._checkWithEpsilon(box.y);
  18089. var sizeZ = this._checkWithEpsilon(box.z);
  18090. var relativePosition = mesh.position;
  18091. bodyParameters = {
  18092. type: 'box',
  18093. size: [sizeX, sizeY, sizeZ],
  18094. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  18095. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  18096. };
  18097. break;
  18098. }
  18099. return bodyParameters;
  18100. };
  18101. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  18102. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18103. var registeredMesh = this._registeredMeshes[index];
  18104. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18105. if (registeredMesh.body) {
  18106. this._world.removeRigidBody(registeredMesh.body.body);
  18107. this._unbindBody(registeredMesh.body);
  18108. }
  18109. this._registeredMeshes.splice(index, 1);
  18110. return;
  18111. }
  18112. }
  18113. };
  18114. OimoJSPlugin.prototype._unbindBody = function (body) {
  18115. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18116. var registeredMesh = this._registeredMeshes[index];
  18117. if (registeredMesh.body === body) {
  18118. registeredMesh.body = null;
  18119. }
  18120. }
  18121. };
  18122. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  18123. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18124. var registeredMesh = this._registeredMeshes[index];
  18125. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  18126. // Get object mass to have a behaviour similar to cannon.js
  18127. var mass = registeredMesh.body.body.massInfo.mass;
  18128. // The force is scaled with the mass of object
  18129. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  18130. return;
  18131. }
  18132. }
  18133. };
  18134. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18135. var body1 = null, body2 = null;
  18136. for (var index = 0; index < this._registeredMeshes.length; index++) {
  18137. var registeredMesh = this._registeredMeshes[index];
  18138. if (registeredMesh.mesh === mesh1) {
  18139. body1 = registeredMesh.body.body;
  18140. }
  18141. else if (registeredMesh.mesh === mesh2) {
  18142. body2 = registeredMesh.body.body;
  18143. }
  18144. }
  18145. if (!body1 || !body2) {
  18146. return false;
  18147. }
  18148. if (!options) {
  18149. options = {};
  18150. }
  18151. new OIMO.Link({
  18152. type: options.type,
  18153. body1: body1,
  18154. body2: body2,
  18155. min: options.min,
  18156. max: options.max,
  18157. axe1: options.axe1,
  18158. axe2: options.axe2,
  18159. pos1: [pivot1.x, pivot1.y, pivot1.z],
  18160. pos2: [pivot2.x, pivot2.y, pivot2.z],
  18161. collision: options.collision,
  18162. spring: options.spring,
  18163. world: this._world
  18164. });
  18165. return true;
  18166. };
  18167. OimoJSPlugin.prototype.dispose = function () {
  18168. this._world.clear();
  18169. while (this._registeredMeshes.length) {
  18170. this.unregisterMesh(this._registeredMeshes[0].mesh);
  18171. }
  18172. };
  18173. OimoJSPlugin.prototype.isSupported = function () {
  18174. return OIMO !== undefined;
  18175. };
  18176. OimoJSPlugin.prototype._getLastShape = function (body) {
  18177. var lastShape = body.shapes;
  18178. while (lastShape.next) {
  18179. lastShape = lastShape.next;
  18180. }
  18181. return lastShape;
  18182. };
  18183. OimoJSPlugin.prototype.runOneStep = function (time) {
  18184. this._world.step();
  18185. // Update the position of all registered meshes
  18186. var i = this._registeredMeshes.length;
  18187. var m;
  18188. while (i--) {
  18189. var body = this._registeredMeshes[i].body.body;
  18190. var mesh = this._registeredMeshes[i].mesh;
  18191. var delta = this._registeredMeshes[i].delta;
  18192. if (!body.sleeping) {
  18193. if (body.shapes.next) {
  18194. var parentShape = this._getLastShape(body);
  18195. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  18196. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  18197. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  18198. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  18199. if (!mesh.rotationQuaternion) {
  18200. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18201. }
  18202. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  18203. mesh.computeWorldMatrix();
  18204. }
  18205. else {
  18206. m = body.getMatrix();
  18207. mtx = BABYLON.Matrix.FromArray(m);
  18208. // Body position
  18209. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  18210. if (!delta) {
  18211. mesh.position.x = bodyX;
  18212. mesh.position.y = bodyY;
  18213. mesh.position.z = bodyZ;
  18214. }
  18215. else {
  18216. mesh.position.x = bodyX + delta.x;
  18217. mesh.position.y = bodyY + delta.y;
  18218. mesh.position.z = bodyZ + delta.z;
  18219. }
  18220. if (!mesh.rotationQuaternion) {
  18221. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  18222. }
  18223. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  18224. mesh.computeWorldMatrix();
  18225. }
  18226. }
  18227. }
  18228. };
  18229. return OimoJSPlugin;
  18230. })();
  18231. BABYLON.OimoJSPlugin = OimoJSPlugin;
  18232. })(BABYLON || (BABYLON = {}));
  18233. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  18234. (function (BABYLON) {
  18235. var PhysicsEngine = (function () {
  18236. function PhysicsEngine(plugin) {
  18237. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  18238. }
  18239. PhysicsEngine.prototype._initialize = function (gravity) {
  18240. this._currentPlugin.initialize();
  18241. this._setGravity(gravity);
  18242. };
  18243. PhysicsEngine.prototype._runOneStep = function (delta) {
  18244. if (delta > 0.1) {
  18245. delta = 0.1;
  18246. }
  18247. else if (delta <= 0) {
  18248. delta = 1.0 / 60.0;
  18249. }
  18250. this._currentPlugin.runOneStep(delta);
  18251. };
  18252. PhysicsEngine.prototype._setGravity = function (gravity) {
  18253. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  18254. this._currentPlugin.setGravity(this.gravity);
  18255. };
  18256. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  18257. return this._currentPlugin.registerMesh(mesh, impostor, options);
  18258. };
  18259. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  18260. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  18261. };
  18262. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  18263. this._currentPlugin.unregisterMesh(mesh);
  18264. };
  18265. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  18266. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  18267. };
  18268. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  18269. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  18270. };
  18271. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  18272. this._currentPlugin.updateBodyPosition(mesh);
  18273. };
  18274. PhysicsEngine.prototype.dispose = function () {
  18275. this._currentPlugin.dispose();
  18276. };
  18277. PhysicsEngine.prototype.isSupported = function () {
  18278. return this._currentPlugin.isSupported();
  18279. };
  18280. // Statics
  18281. PhysicsEngine.NoImpostor = 0;
  18282. PhysicsEngine.SphereImpostor = 1;
  18283. PhysicsEngine.BoxImpostor = 2;
  18284. PhysicsEngine.PlaneImpostor = 3;
  18285. PhysicsEngine.MeshImpostor = 4;
  18286. PhysicsEngine.CapsuleImpostor = 5;
  18287. PhysicsEngine.ConeImpostor = 6;
  18288. PhysicsEngine.CylinderImpostor = 7;
  18289. PhysicsEngine.ConvexHullImpostor = 8;
  18290. PhysicsEngine.Epsilon = 0.001;
  18291. return PhysicsEngine;
  18292. })();
  18293. BABYLON.PhysicsEngine = PhysicsEngine;
  18294. })(BABYLON || (BABYLON = {}));
  18295. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  18296. (function (BABYLON) {
  18297. var serializeLight = function (light) {
  18298. var serializationObject = {};
  18299. serializationObject.name = light.name;
  18300. serializationObject.id = light.id;
  18301. serializationObject.tags = BABYLON.Tags.GetTags(light);
  18302. if (light instanceof BABYLON.PointLight) {
  18303. serializationObject.type = 0;
  18304. serializationObject.position = light.position.asArray();
  18305. }
  18306. else if (light instanceof BABYLON.DirectionalLight) {
  18307. serializationObject.type = 1;
  18308. var directionalLight = light;
  18309. serializationObject.position = directionalLight.position.asArray();
  18310. serializationObject.direction = directionalLight.direction.asArray();
  18311. }
  18312. else if (light instanceof BABYLON.SpotLight) {
  18313. serializationObject.type = 2;
  18314. var spotLight = light;
  18315. serializationObject.position = spotLight.position.asArray();
  18316. serializationObject.direction = spotLight.position.asArray();
  18317. serializationObject.angle = spotLight.angle;
  18318. serializationObject.exponent = spotLight.exponent;
  18319. }
  18320. else if (light instanceof BABYLON.HemisphericLight) {
  18321. serializationObject.type = 3;
  18322. var hemisphericLight = light;
  18323. serializationObject.direction = hemisphericLight.direction.asArray();
  18324. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  18325. }
  18326. if (light.intensity) {
  18327. serializationObject.intensity = light.intensity;
  18328. }
  18329. serializationObject.range = light.range;
  18330. serializationObject.diffuse = light.diffuse.asArray();
  18331. serializationObject.specular = light.specular.asArray();
  18332. return serializationObject;
  18333. };
  18334. var serializeFresnelParameter = function (fresnelParameter) {
  18335. var serializationObject = {};
  18336. serializationObject.isEnabled = fresnelParameter.isEnabled;
  18337. serializationObject.leftColor = fresnelParameter.leftColor;
  18338. serializationObject.rightColor = fresnelParameter.rightColor;
  18339. serializationObject.bias = fresnelParameter.bias;
  18340. serializationObject.power = fresnelParameter.power;
  18341. return serializationObject;
  18342. };
  18343. var appendAnimations = function (source, destination) {
  18344. if (source.animations) {
  18345. destination.animations = [];
  18346. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18347. var animation = source.animations[animationIndex];
  18348. destination.animations.push(serializeAnimation(animation));
  18349. }
  18350. }
  18351. };
  18352. var serializeCamera = function (camera) {
  18353. var serializationObject = {};
  18354. serializationObject.name = camera.name;
  18355. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18356. serializationObject.id = camera.id;
  18357. serializationObject.position = camera.position.asArray();
  18358. // Parent
  18359. if (camera.parent) {
  18360. serializationObject.parentId = camera.parent.id;
  18361. }
  18362. serializationObject.fov = camera.fov;
  18363. serializationObject.minZ = camera.minZ;
  18364. serializationObject.maxZ = camera.maxZ;
  18365. serializationObject.inertia = camera.inertia;
  18366. //setting the type
  18367. if (camera instanceof BABYLON.FreeCamera) {
  18368. serializationObject.type = "FreeCamera";
  18369. }
  18370. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18371. serializationObject.type = "ArcRotateCamera";
  18372. }
  18373. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18374. serializationObject.type = "AnaglyphArcRotateCamera";
  18375. }
  18376. else if (camera instanceof BABYLON.GamepadCamera) {
  18377. serializationObject.type = "GamepadCamera";
  18378. }
  18379. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18380. serializationObject.type = "AnaglyphFreeCamera";
  18381. }
  18382. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18383. serializationObject.type = "DeviceOrientationCamera";
  18384. }
  18385. else if (camera instanceof BABYLON.FollowCamera) {
  18386. serializationObject.type = "FollowCamera";
  18387. }
  18388. else if (camera instanceof BABYLON.OculusCamera) {
  18389. serializationObject.type = "OculusCamera";
  18390. }
  18391. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18392. serializationObject.type = "OculusGamepadCamera";
  18393. }
  18394. else if (camera instanceof BABYLON.TouchCamera) {
  18395. serializationObject.type = "TouchCamera";
  18396. }
  18397. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18398. serializationObject.type = "VirtualJoysticksCamera";
  18399. }
  18400. else if (camera instanceof BABYLON.WebVRCamera) {
  18401. serializationObject.type = "WebVRCamera";
  18402. }
  18403. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18404. serializationObject.type = "VRDeviceOrientationCamera";
  18405. }
  18406. //special properties of specific cameras
  18407. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18408. var arcCamera = camera;
  18409. serializationObject.alpha = arcCamera.alpha;
  18410. serializationObject.beta = arcCamera.beta;
  18411. serializationObject.radius = arcCamera.radius;
  18412. if (arcCamera.target && arcCamera.target.id) {
  18413. serializationObject.lockedTargetId = arcCamera.target.id;
  18414. }
  18415. }
  18416. else if (camera instanceof BABYLON.FollowCamera) {
  18417. var followCam = camera;
  18418. serializationObject.radius = followCam.radius;
  18419. serializationObject.heightOffset = followCam.heightOffset;
  18420. serializationObject.rotationOffset = followCam.rotationOffset;
  18421. }
  18422. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18423. //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.
  18424. if (camera['_eyeSpace'] !== undefined) {
  18425. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18426. }
  18427. }
  18428. //general properties that not all cameras have. The [] is due to typescript's type safety
  18429. if (camera['speed'] !== undefined) {
  18430. serializationObject.speed = camera['speed'];
  18431. }
  18432. if (camera['target'] && camera['target'] instanceof BABYLON.Vector3) {
  18433. serializationObject.target = camera['target'].asArray();
  18434. }
  18435. // Target
  18436. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18437. serializationObject.rotation = camera['rotation'].asArray();
  18438. }
  18439. // Locked target
  18440. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18441. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18442. }
  18443. serializationObject.checkCollisions = camera['checkCollisions'] || false;
  18444. serializationObject.applyGravity = camera['applyGravity'] || false;
  18445. if (camera['ellipsoid']) {
  18446. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18447. }
  18448. // Animations
  18449. appendAnimations(camera, serializationObject);
  18450. // Layer mask
  18451. serializationObject.layerMask = camera.layerMask;
  18452. return serializationObject;
  18453. };
  18454. var serializeAnimation = function (animation) {
  18455. var serializationObject = {};
  18456. serializationObject.name = animation.name;
  18457. serializationObject.property = animation.targetProperty;
  18458. serializationObject.framePerSecond = animation.framePerSecond;
  18459. serializationObject.dataType = animation.dataType;
  18460. serializationObject.loopBehavior = animation.loopMode;
  18461. var dataType = animation.dataType;
  18462. serializationObject.keys = [];
  18463. var keys = animation.getKeys();
  18464. for (var index = 0; index < keys.length; index++) {
  18465. var animationKey = keys[index];
  18466. var key = {};
  18467. key.frame = animationKey.frame;
  18468. switch (dataType) {
  18469. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18470. key.values = [animationKey.value];
  18471. break;
  18472. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18473. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18474. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18475. key.values = animationKey.value.asArray();
  18476. break;
  18477. }
  18478. serializationObject.keys.push(key);
  18479. }
  18480. return serializationObject;
  18481. };
  18482. var serializeMultiMaterial = function (material) {
  18483. var serializationObject = {};
  18484. serializationObject.name = material.name;
  18485. serializationObject.id = material.id;
  18486. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18487. serializationObject.materials = [];
  18488. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18489. var subMat = material.subMaterials[matIndex];
  18490. if (subMat) {
  18491. serializationObject.materials.push(subMat.id);
  18492. }
  18493. else {
  18494. serializationObject.materials.push(null);
  18495. }
  18496. }
  18497. return serializationObject;
  18498. };
  18499. var serializeMaterial = function (material) {
  18500. var serializationObject = {};
  18501. serializationObject.name = material.name;
  18502. serializationObject.ambient = material.ambientColor.asArray();
  18503. serializationObject.diffuse = material.diffuseColor.asArray();
  18504. serializationObject.specular = material.specularColor.asArray();
  18505. serializationObject.specularPower = material.specularPower;
  18506. serializationObject.emissive = material.emissiveColor.asArray();
  18507. serializationObject.alpha = material.alpha;
  18508. serializationObject.id = material.id;
  18509. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18510. serializationObject.backFaceCulling = material.backFaceCulling;
  18511. if (material.diffuseTexture) {
  18512. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18513. }
  18514. if (material.diffuseFresnelParameters) {
  18515. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18516. }
  18517. if (material.ambientTexture) {
  18518. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18519. }
  18520. if (material.opacityTexture) {
  18521. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18522. }
  18523. if (material.opacityFresnelParameters) {
  18524. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18525. }
  18526. if (material.reflectionTexture) {
  18527. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18528. }
  18529. if (material.reflectionFresnelParameters) {
  18530. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18531. }
  18532. if (material.emissiveTexture) {
  18533. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18534. }
  18535. if (material.emissiveFresnelParameters) {
  18536. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18537. }
  18538. if (material.specularTexture) {
  18539. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18540. }
  18541. if (material.bumpTexture) {
  18542. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18543. }
  18544. return serializationObject;
  18545. };
  18546. var serializeTexture = function (texture) {
  18547. var serializationObject = {};
  18548. if (!texture.name) {
  18549. return null;
  18550. }
  18551. if (texture instanceof BABYLON.CubeTexture) {
  18552. serializationObject.name = texture.name;
  18553. serializationObject.hasAlpha = texture.hasAlpha;
  18554. serializationObject.level = texture.level;
  18555. serializationObject.coordinatesMode = texture.coordinatesMode;
  18556. return serializationObject;
  18557. }
  18558. if (texture instanceof BABYLON.MirrorTexture) {
  18559. var mirrorTexture = texture;
  18560. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18561. serializationObject.renderList = [];
  18562. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18563. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18564. }
  18565. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18566. }
  18567. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18568. var renderTargetTexture = texture;
  18569. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18570. serializationObject.renderList = [];
  18571. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18572. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18573. }
  18574. }
  18575. var regularTexture = texture;
  18576. serializationObject.name = texture.name;
  18577. serializationObject.hasAlpha = texture.hasAlpha;
  18578. serializationObject.level = texture.level;
  18579. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18580. serializationObject.coordinatesMode = texture.coordinatesMode;
  18581. serializationObject.uOffset = regularTexture.uOffset;
  18582. serializationObject.vOffset = regularTexture.vOffset;
  18583. serializationObject.uScale = regularTexture.uScale;
  18584. serializationObject.vScale = regularTexture.vScale;
  18585. serializationObject.uAng = regularTexture.uAng;
  18586. serializationObject.vAng = regularTexture.vAng;
  18587. serializationObject.wAng = regularTexture.wAng;
  18588. serializationObject.wrapU = texture.wrapU;
  18589. serializationObject.wrapV = texture.wrapV;
  18590. // Animations
  18591. appendAnimations(texture, serializationObject);
  18592. return serializationObject;
  18593. };
  18594. var serializeSkeleton = function (skeleton) {
  18595. var serializationObject = {};
  18596. serializationObject.name = skeleton.name;
  18597. serializationObject.id = skeleton.id;
  18598. serializationObject.bones = [];
  18599. for (var index = 0; index < skeleton.bones.length; index++) {
  18600. var bone = skeleton.bones[index];
  18601. var serializedBone = {
  18602. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18603. name: bone.name,
  18604. matrix: bone.getLocalMatrix().toArray()
  18605. };
  18606. serializationObject.bones.push(serializedBone);
  18607. if (bone.animations && bone.animations.length > 0) {
  18608. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18609. }
  18610. }
  18611. return serializationObject;
  18612. };
  18613. var serializeParticleSystem = function (particleSystem) {
  18614. var serializationObject = {};
  18615. serializationObject.emitterId = particleSystem.emitter.id;
  18616. serializationObject.capacity = particleSystem.getCapacity();
  18617. if (particleSystem.particleTexture) {
  18618. serializationObject.textureName = particleSystem.particleTexture.name;
  18619. }
  18620. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18621. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18622. serializationObject.minSize = particleSystem.minSize;
  18623. serializationObject.maxSize = particleSystem.maxSize;
  18624. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18625. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18626. serializationObject.emitRate = particleSystem.emitRate;
  18627. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18628. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18629. serializationObject.gravity = particleSystem.gravity.asArray();
  18630. serializationObject.direction1 = particleSystem.direction1.asArray();
  18631. serializationObject.direction2 = particleSystem.direction2.asArray();
  18632. serializationObject.color1 = particleSystem.color1.asArray();
  18633. serializationObject.color2 = particleSystem.color2.asArray();
  18634. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18635. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18636. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18637. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18638. serializationObject.blendMode = particleSystem.blendMode;
  18639. return serializationObject;
  18640. };
  18641. var serializeLensFlareSystem = function (lensFlareSystem) {
  18642. var serializationObject = {};
  18643. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18644. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18645. serializationObject.flares = [];
  18646. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18647. var flare = lensFlareSystem.lensFlares[index];
  18648. serializationObject.flares.push({
  18649. size: flare.size,
  18650. position: flare.position,
  18651. color: flare.color.asArray(),
  18652. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18653. });
  18654. }
  18655. return serializationObject;
  18656. };
  18657. var serializeShadowGenerator = function (light) {
  18658. var serializationObject = {};
  18659. var shadowGenerator = light.getShadowGenerator();
  18660. serializationObject.lightId = light.id;
  18661. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18662. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18663. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18664. serializationObject.renderList = [];
  18665. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18666. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18667. serializationObject.renderList.push(mesh.id);
  18668. }
  18669. return serializationObject;
  18670. };
  18671. var serializedGeometries = [];
  18672. var serializeGeometry = function (geometry, serializationGeometries) {
  18673. if (serializedGeometries[geometry.id]) {
  18674. return;
  18675. }
  18676. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18677. serializationGeometries.boxes.push(serializeBox(geometry));
  18678. }
  18679. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18680. serializationGeometries.spheres.push(serializeSphere(geometry));
  18681. }
  18682. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18683. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18684. }
  18685. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18686. serializationGeometries.toruses.push(serializeTorus(geometry));
  18687. }
  18688. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18689. serializationGeometries.grounds.push(serializeGround(geometry));
  18690. }
  18691. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18692. serializationGeometries.planes.push(serializePlane(geometry));
  18693. }
  18694. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18695. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18696. }
  18697. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18698. throw new Error("Unknow primitive type");
  18699. }
  18700. else {
  18701. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18702. }
  18703. serializedGeometries[geometry.id] = true;
  18704. };
  18705. var serializeGeometryBase = function (geometry) {
  18706. var serializationObject = {};
  18707. serializationObject.id = geometry.id;
  18708. if (BABYLON.Tags.HasTags(geometry)) {
  18709. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18710. }
  18711. return serializationObject;
  18712. };
  18713. var serializeVertexData = function (vertexData) {
  18714. var serializationObject = serializeGeometryBase(vertexData);
  18715. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18716. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18717. }
  18718. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18719. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18720. }
  18721. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18722. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18723. }
  18724. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18725. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18726. }
  18727. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18728. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18729. }
  18730. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18731. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18732. serializationObject.matricesIndices._isExpanded = true;
  18733. }
  18734. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18735. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18736. }
  18737. serializationObject.indices = vertexData.getIndices();
  18738. return serializationObject;
  18739. };
  18740. var serializePrimitive = function (primitive) {
  18741. var serializationObject = serializeGeometryBase(primitive);
  18742. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18743. return serializationObject;
  18744. };
  18745. var serializeBox = function (box) {
  18746. var serializationObject = serializePrimitive(box);
  18747. serializationObject.size = box.size;
  18748. return serializationObject;
  18749. };
  18750. var serializeSphere = function (sphere) {
  18751. var serializationObject = serializePrimitive(sphere);
  18752. serializationObject.segments = sphere.segments;
  18753. serializationObject.diameter = sphere.diameter;
  18754. return serializationObject;
  18755. };
  18756. var serializeCylinder = function (cylinder) {
  18757. var serializationObject = serializePrimitive(cylinder);
  18758. serializationObject.height = cylinder.height;
  18759. serializationObject.diameterTop = cylinder.diameterTop;
  18760. serializationObject.diameterBottom = cylinder.diameterBottom;
  18761. serializationObject.tessellation = cylinder.tessellation;
  18762. return serializationObject;
  18763. };
  18764. var serializeTorus = function (torus) {
  18765. var serializationObject = serializePrimitive(torus);
  18766. serializationObject.diameter = torus.diameter;
  18767. serializationObject.thickness = torus.thickness;
  18768. serializationObject.tessellation = torus.tessellation;
  18769. return serializationObject;
  18770. };
  18771. var serializeGround = function (ground) {
  18772. var serializationObject = serializePrimitive(ground);
  18773. serializationObject.width = ground.width;
  18774. serializationObject.height = ground.height;
  18775. serializationObject.subdivisions = ground.subdivisions;
  18776. return serializationObject;
  18777. };
  18778. var serializePlane = function (plane) {
  18779. var serializationObject = serializePrimitive(plane);
  18780. serializationObject.size = plane.size;
  18781. return serializationObject;
  18782. };
  18783. var serializeTorusKnot = function (torusKnot) {
  18784. var serializationObject = serializePrimitive(torusKnot);
  18785. serializationObject.radius = torusKnot.radius;
  18786. serializationObject.tube = torusKnot.tube;
  18787. serializationObject.radialSegments = torusKnot.radialSegments;
  18788. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18789. serializationObject.p = torusKnot.p;
  18790. serializationObject.q = torusKnot.q;
  18791. return serializationObject;
  18792. };
  18793. var serializeMesh = function (mesh, serializationScene) {
  18794. var serializationObject = {};
  18795. serializationObject.name = mesh.name;
  18796. serializationObject.id = mesh.id;
  18797. if (BABYLON.Tags.HasTags(mesh)) {
  18798. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18799. }
  18800. serializationObject.position = mesh.position.asArray();
  18801. if (mesh.rotationQuaternion) {
  18802. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18803. }
  18804. else if (mesh.rotation) {
  18805. serializationObject.rotation = mesh.rotation.asArray();
  18806. }
  18807. serializationObject.scaling = mesh.scaling.asArray();
  18808. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18809. serializationObject.isEnabled = mesh.isEnabled();
  18810. serializationObject.isVisible = mesh.isVisible;
  18811. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18812. serializationObject.pickable = mesh.isPickable;
  18813. serializationObject.receiveShadows = mesh.receiveShadows;
  18814. serializationObject.billboardMode = mesh.billboardMode;
  18815. serializationObject.visibility = mesh.visibility;
  18816. serializationObject.checkCollisions = mesh.checkCollisions;
  18817. // Parent
  18818. if (mesh.parent) {
  18819. serializationObject.parentId = mesh.parent.id;
  18820. }
  18821. // Geometry
  18822. var geometry = mesh._geometry;
  18823. if (geometry) {
  18824. var geometryId = geometry.id;
  18825. serializationObject.geometryId = geometryId;
  18826. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18827. // 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
  18828. serializeGeometry(geometry, serializationScene.geometries);
  18829. }
  18830. // SubMeshes
  18831. serializationObject.subMeshes = [];
  18832. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18833. var subMesh = mesh.subMeshes[subIndex];
  18834. serializationObject.subMeshes.push({
  18835. materialIndex: subMesh.materialIndex,
  18836. verticesStart: subMesh.verticesStart,
  18837. verticesCount: subMesh.verticesCount,
  18838. indexStart: subMesh.indexStart,
  18839. indexCount: subMesh.indexCount
  18840. });
  18841. }
  18842. }
  18843. // Material
  18844. if (mesh.material) {
  18845. serializationObject.materialId = mesh.material.id;
  18846. }
  18847. else {
  18848. mesh.material = null;
  18849. }
  18850. // Skeleton
  18851. if (mesh.skeleton) {
  18852. serializationObject.skeletonId = mesh.skeleton.id;
  18853. }
  18854. // Physics
  18855. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18856. serializationObject.physicsMass = mesh.getPhysicsMass();
  18857. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18858. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18859. switch (mesh.getPhysicsImpostor()) {
  18860. case BABYLON.PhysicsEngine.BoxImpostor:
  18861. serializationObject.physicsImpostor = 1;
  18862. break;
  18863. case BABYLON.PhysicsEngine.SphereImpostor:
  18864. serializationObject.physicsImpostor = 2;
  18865. break;
  18866. }
  18867. }
  18868. // Instances
  18869. serializationObject.instances = [];
  18870. for (var index = 0; index < mesh.instances.length; index++) {
  18871. var instance = mesh.instances[index];
  18872. var serializationInstance = {
  18873. name: instance.name,
  18874. position: instance.position,
  18875. rotation: instance.rotation,
  18876. rotationQuaternion: instance.rotationQuaternion,
  18877. scaling: instance.scaling
  18878. };
  18879. serializationObject.instances.push(serializationInstance);
  18880. // Animations
  18881. appendAnimations(instance, serializationInstance);
  18882. }
  18883. // Animations
  18884. appendAnimations(mesh, serializationObject);
  18885. // Layer mask
  18886. serializationObject.layerMask = mesh.layerMask;
  18887. return serializationObject;
  18888. };
  18889. var SceneSerializer = (function () {
  18890. function SceneSerializer() {
  18891. }
  18892. SceneSerializer.Serialize = function (scene) {
  18893. var serializationObject = {};
  18894. // Scene
  18895. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18896. serializationObject.autoClear = scene.autoClear;
  18897. serializationObject.clearColor = scene.clearColor.asArray();
  18898. serializationObject.ambientColor = scene.ambientColor.asArray();
  18899. serializationObject.gravity = scene.gravity.asArray();
  18900. // Fog
  18901. if (scene.fogMode && scene.fogMode !== 0) {
  18902. serializationObject.fogMode = scene.fogMode;
  18903. serializationObject.fogColor = scene.fogColor.asArray();
  18904. serializationObject.fogStart = scene.fogStart;
  18905. serializationObject.fogEnd = scene.fogEnd;
  18906. serializationObject.fogDensity = scene.fogDensity;
  18907. }
  18908. // Lights
  18909. serializationObject.lights = [];
  18910. for (var index = 0; index < scene.lights.length; index++) {
  18911. var light = scene.lights[index];
  18912. serializationObject.lights.push(serializeLight(light));
  18913. }
  18914. // Cameras
  18915. serializationObject.cameras = [];
  18916. for (index = 0; index < scene.cameras.length; index++) {
  18917. var camera = scene.cameras[index];
  18918. serializationObject.cameras.push(serializeCamera(camera));
  18919. }
  18920. if (scene.activeCamera) {
  18921. serializationObject.activeCameraID = scene.activeCamera.id;
  18922. }
  18923. // Materials
  18924. serializationObject.materials = [];
  18925. serializationObject.multiMaterials = [];
  18926. for (index = 0; index < scene.materials.length; index++) {
  18927. var material = scene.materials[index];
  18928. if (material instanceof BABYLON.StandardMaterial) {
  18929. serializationObject.materials.push(serializeMaterial(material));
  18930. }
  18931. else if (material instanceof BABYLON.MultiMaterial) {
  18932. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18933. }
  18934. }
  18935. // Skeletons
  18936. serializationObject.skeletons = [];
  18937. for (index = 0; index < scene.skeletons.length; index++) {
  18938. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18939. }
  18940. // Geometries
  18941. serializationObject.geometries = {};
  18942. serializationObject.geometries.boxes = [];
  18943. serializationObject.geometries.spheres = [];
  18944. serializationObject.geometries.cylinders = [];
  18945. serializationObject.geometries.toruses = [];
  18946. serializationObject.geometries.grounds = [];
  18947. serializationObject.geometries.planes = [];
  18948. serializationObject.geometries.torusKnots = [];
  18949. serializationObject.geometries.vertexData = [];
  18950. serializedGeometries = [];
  18951. var geometries = scene.getGeometries();
  18952. for (index = 0; index < geometries.length; index++) {
  18953. var geometry = geometries[index];
  18954. if (geometry.isReady()) {
  18955. serializeGeometry(geometry, serializationObject.geometries);
  18956. }
  18957. }
  18958. // Meshes
  18959. serializationObject.meshes = [];
  18960. for (index = 0; index < scene.meshes.length; index++) {
  18961. var abstractMesh = scene.meshes[index];
  18962. if (abstractMesh instanceof BABYLON.Mesh) {
  18963. var mesh = abstractMesh;
  18964. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18965. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18966. }
  18967. }
  18968. }
  18969. // Particles Systems
  18970. serializationObject.particleSystems = [];
  18971. for (index = 0; index < scene.particleSystems.length; index++) {
  18972. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18973. }
  18974. // Lens flares
  18975. serializationObject.lensFlareSystems = [];
  18976. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18977. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18978. }
  18979. // Shadows
  18980. serializationObject.shadowGenerators = [];
  18981. for (index = 0; index < scene.lights.length; index++) {
  18982. light = scene.lights[index];
  18983. if (light.getShadowGenerator()) {
  18984. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18985. }
  18986. }
  18987. return serializationObject;
  18988. };
  18989. return SceneSerializer;
  18990. })();
  18991. BABYLON.SceneSerializer = SceneSerializer;
  18992. })(BABYLON || (BABYLON = {}));
  18993. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18994. (function (BABYLON) {
  18995. var SceneLoader = (function () {
  18996. function SceneLoader() {
  18997. }
  18998. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18999. get: function () {
  19000. return SceneLoader._ForceFullSceneLoadingForIncremental;
  19001. },
  19002. set: function (value) {
  19003. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  19004. },
  19005. enumerable: true,
  19006. configurable: true
  19007. });
  19008. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  19009. get: function () {
  19010. return SceneLoader._ShowLoadingScreen;
  19011. },
  19012. set: function (value) {
  19013. SceneLoader._ShowLoadingScreen = value;
  19014. },
  19015. enumerable: true,
  19016. configurable: true
  19017. });
  19018. SceneLoader._getPluginForFilename = function (sceneFilename) {
  19019. var dotPosition = sceneFilename.lastIndexOf(".");
  19020. var queryStringPosition = sceneFilename.indexOf("?");
  19021. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  19022. for (var index = 0; index < this._registeredPlugins.length; index++) {
  19023. var plugin = this._registeredPlugins[index];
  19024. if (plugin.extensions.indexOf(extension) !== -1) {
  19025. return plugin;
  19026. }
  19027. }
  19028. return this._registeredPlugins[this._registeredPlugins.length - 1];
  19029. };
  19030. // Public functions
  19031. SceneLoader.RegisterPlugin = function (plugin) {
  19032. plugin.extensions = plugin.extensions.toLowerCase();
  19033. SceneLoader._registeredPlugins.push(plugin);
  19034. };
  19035. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19036. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19037. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19038. return;
  19039. }
  19040. var manifestChecked = function (success) {
  19041. scene.database = database;
  19042. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  19043. var importMeshFromData = function (data) {
  19044. var meshes = [];
  19045. var particleSystems = [];
  19046. var skeletons = [];
  19047. try {
  19048. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  19049. if (onerror) {
  19050. onerror(scene, 'unable to load the scene');
  19051. }
  19052. return;
  19053. }
  19054. }
  19055. catch (e) {
  19056. if (onerror) {
  19057. onerror(scene, e);
  19058. }
  19059. return;
  19060. }
  19061. if (onsuccess) {
  19062. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  19063. onsuccess(meshes, particleSystems, skeletons);
  19064. }
  19065. };
  19066. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19067. // Direct load
  19068. importMeshFromData(sceneFilename.substr(5));
  19069. return;
  19070. }
  19071. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  19072. importMeshFromData(data);
  19073. }, progressCallBack, database);
  19074. };
  19075. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19076. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19077. };
  19078. /**
  19079. * Load a scene
  19080. * @param rootUrl a string that defines the root url for scene and resources
  19081. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19082. * @param engine is the instance of BABYLON.Engine to use to create the scene
  19083. */
  19084. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  19085. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  19086. };
  19087. /**
  19088. * Append a scene
  19089. * @param rootUrl a string that defines the root url for scene and resources
  19090. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  19091. * @param scene is the instance of BABYLON.Scene to append to
  19092. */
  19093. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  19094. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  19095. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  19096. return;
  19097. }
  19098. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  19099. var database;
  19100. if (SceneLoader.ShowLoadingScreen) {
  19101. scene.getEngine().displayLoadingUI();
  19102. }
  19103. var loadSceneFromData = function (data) {
  19104. scene.database = database;
  19105. if (!plugin.load(scene, data, rootUrl)) {
  19106. if (onerror) {
  19107. onerror(scene);
  19108. }
  19109. scene.getEngine().hideLoadingUI();
  19110. return;
  19111. }
  19112. if (onsuccess) {
  19113. onsuccess(scene);
  19114. }
  19115. if (SceneLoader.ShowLoadingScreen) {
  19116. scene.executeWhenReady(function () {
  19117. scene.getEngine().hideLoadingUI();
  19118. });
  19119. }
  19120. };
  19121. var manifestChecked = function (success) {
  19122. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  19123. };
  19124. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  19125. // Direct load
  19126. loadSceneFromData(sceneFilename.substr(5));
  19127. return;
  19128. }
  19129. if (rootUrl.indexOf("file:") === -1) {
  19130. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  19131. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  19132. }
  19133. else {
  19134. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  19135. }
  19136. };
  19137. // Flags
  19138. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  19139. SceneLoader._ShowLoadingScreen = true;
  19140. // Members
  19141. SceneLoader._registeredPlugins = new Array();
  19142. return SceneLoader;
  19143. })();
  19144. BABYLON.SceneLoader = SceneLoader;
  19145. ;
  19146. })(BABYLON || (BABYLON = {}));
  19147. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  19148. (function (BABYLON) {
  19149. var Internals;
  19150. (function (Internals) {
  19151. var checkColors4 = function (colors, count) {
  19152. // Check if color3 was used
  19153. if (colors.length === count * 3) {
  19154. var colors4 = [];
  19155. for (var index = 0; index < colors.length; index += 3) {
  19156. var newIndex = (index / 3) * 4;
  19157. colors4[newIndex] = colors[index];
  19158. colors4[newIndex + 1] = colors[index + 1];
  19159. colors4[newIndex + 2] = colors[index + 2];
  19160. colors4[newIndex + 3] = 1.0;
  19161. }
  19162. return colors4;
  19163. }
  19164. return colors;
  19165. };
  19166. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  19167. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  19168. texture.name = parsedTexture.name;
  19169. texture.hasAlpha = parsedTexture.hasAlpha;
  19170. texture.level = parsedTexture.level;
  19171. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19172. return texture;
  19173. };
  19174. var loadTexture = function (rootUrl, parsedTexture, scene) {
  19175. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  19176. return null;
  19177. }
  19178. if (parsedTexture.isCube) {
  19179. return loadCubeTexture(rootUrl, parsedTexture, scene);
  19180. }
  19181. var texture;
  19182. if (parsedTexture.mirrorPlane) {
  19183. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19184. texture._waitingRenderList = parsedTexture.renderList;
  19185. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  19186. }
  19187. else if (parsedTexture.isRenderTarget) {
  19188. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  19189. texture._waitingRenderList = parsedTexture.renderList;
  19190. }
  19191. else {
  19192. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  19193. }
  19194. texture.name = parsedTexture.name;
  19195. texture.hasAlpha = parsedTexture.hasAlpha;
  19196. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  19197. texture.level = parsedTexture.level;
  19198. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  19199. texture.coordinatesMode = parsedTexture.coordinatesMode;
  19200. texture.uOffset = parsedTexture.uOffset;
  19201. texture.vOffset = parsedTexture.vOffset;
  19202. texture.uScale = parsedTexture.uScale;
  19203. texture.vScale = parsedTexture.vScale;
  19204. texture.uAng = parsedTexture.uAng;
  19205. texture.vAng = parsedTexture.vAng;
  19206. texture.wAng = parsedTexture.wAng;
  19207. texture.wrapU = parsedTexture.wrapU;
  19208. texture.wrapV = parsedTexture.wrapV;
  19209. // Animations
  19210. if (parsedTexture.animations) {
  19211. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  19212. var parsedAnimation = parsedTexture.animations[animationIndex];
  19213. texture.animations.push(parseAnimation(parsedAnimation));
  19214. }
  19215. }
  19216. return texture;
  19217. };
  19218. var parseSkeleton = function (parsedSkeleton, scene) {
  19219. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  19220. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  19221. var parsedBone = parsedSkeleton.bones[index];
  19222. var parentBone = null;
  19223. if (parsedBone.parentBoneIndex > -1) {
  19224. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  19225. }
  19226. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  19227. if (parsedBone.animation) {
  19228. bone.animations.push(parseAnimation(parsedBone.animation));
  19229. }
  19230. }
  19231. return skeleton;
  19232. };
  19233. var parseFresnelParameters = function (parsedFresnelParameters) {
  19234. var fresnelParameters = new BABYLON.FresnelParameters();
  19235. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  19236. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  19237. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  19238. fresnelParameters.bias = parsedFresnelParameters.bias;
  19239. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  19240. return fresnelParameters;
  19241. };
  19242. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  19243. var material;
  19244. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  19245. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  19246. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  19247. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  19248. material.specularPower = parsedMaterial.specularPower;
  19249. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  19250. material.alpha = parsedMaterial.alpha;
  19251. material.id = parsedMaterial.id;
  19252. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  19253. material.backFaceCulling = parsedMaterial.backFaceCulling;
  19254. material.wireframe = parsedMaterial.wireframe;
  19255. if (parsedMaterial.diffuseTexture) {
  19256. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  19257. }
  19258. if (parsedMaterial.diffuseFresnelParameters) {
  19259. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  19260. }
  19261. if (parsedMaterial.ambientTexture) {
  19262. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  19263. }
  19264. if (parsedMaterial.opacityTexture) {
  19265. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  19266. }
  19267. if (parsedMaterial.opacityFresnelParameters) {
  19268. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  19269. }
  19270. if (parsedMaterial.reflectionTexture) {
  19271. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  19272. }
  19273. if (parsedMaterial.reflectionFresnelParameters) {
  19274. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  19275. }
  19276. if (parsedMaterial.emissiveTexture) {
  19277. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  19278. }
  19279. if (parsedMaterial.emissiveFresnelParameters) {
  19280. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  19281. }
  19282. if (parsedMaterial.specularTexture) {
  19283. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  19284. }
  19285. if (parsedMaterial.bumpTexture) {
  19286. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  19287. }
  19288. return material;
  19289. };
  19290. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  19291. for (var index = 0; index < parsedData.materials.length; index++) {
  19292. var parsedMaterial = parsedData.materials[index];
  19293. if (parsedMaterial.id === id) {
  19294. return parseMaterial(parsedMaterial, scene, rootUrl);
  19295. }
  19296. }
  19297. return null;
  19298. };
  19299. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  19300. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  19301. multiMaterial.id = parsedMultiMaterial.id;
  19302. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  19303. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19304. var subMatId = parsedMultiMaterial.materials[matIndex];
  19305. if (subMatId) {
  19306. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  19307. }
  19308. else {
  19309. multiMaterial.subMaterials.push(null);
  19310. }
  19311. }
  19312. return multiMaterial;
  19313. };
  19314. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  19315. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  19316. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  19317. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  19318. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  19319. var parsedFlare = parsedLensFlareSystem.flares[index];
  19320. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  19321. }
  19322. return lensFlareSystem;
  19323. };
  19324. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  19325. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  19326. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  19327. if (parsedParticleSystem.textureName) {
  19328. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  19329. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  19330. }
  19331. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  19332. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  19333. particleSystem.minSize = parsedParticleSystem.minSize;
  19334. particleSystem.maxSize = parsedParticleSystem.maxSize;
  19335. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  19336. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  19337. particleSystem.emitter = emitter;
  19338. particleSystem.emitRate = parsedParticleSystem.emitRate;
  19339. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  19340. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  19341. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  19342. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  19343. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  19344. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  19345. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  19346. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19347. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19348. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19349. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19350. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19351. particleSystem.start();
  19352. return particleSystem;
  19353. };
  19354. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19355. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19356. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19357. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19358. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19359. shadowGenerator.getShadowMap().renderList.push(mesh);
  19360. }
  19361. if (parsedShadowGenerator.usePoissonSampling) {
  19362. shadowGenerator.usePoissonSampling = true;
  19363. }
  19364. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19365. shadowGenerator.useVarianceShadowMap = true;
  19366. }
  19367. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19368. shadowGenerator.useBlurVarianceShadowMap = true;
  19369. if (parsedShadowGenerator.blurScale) {
  19370. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  19371. }
  19372. if (parsedShadowGenerator.blurBoxOffset) {
  19373. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  19374. }
  19375. }
  19376. if (parsedShadowGenerator.bias !== undefined) {
  19377. shadowGenerator.bias = parsedShadowGenerator.bias;
  19378. }
  19379. return shadowGenerator;
  19380. };
  19381. var parseAnimation = function (parsedAnimation) {
  19382. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19383. var dataType = parsedAnimation.dataType;
  19384. var keys = [];
  19385. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19386. var key = parsedAnimation.keys[index];
  19387. var data;
  19388. switch (dataType) {
  19389. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19390. data = key.values[0];
  19391. break;
  19392. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19393. data = BABYLON.Quaternion.FromArray(key.values);
  19394. break;
  19395. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19396. data = BABYLON.Matrix.FromArray(key.values);
  19397. break;
  19398. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19399. default:
  19400. data = BABYLON.Vector3.FromArray(key.values);
  19401. break;
  19402. }
  19403. keys.push({
  19404. frame: key.frame,
  19405. value: data
  19406. });
  19407. }
  19408. animation.setKeys(keys);
  19409. return animation;
  19410. };
  19411. var parseLight = function (parsedLight, scene) {
  19412. var light;
  19413. switch (parsedLight.type) {
  19414. case 0:
  19415. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19416. break;
  19417. case 1:
  19418. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19419. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19420. break;
  19421. case 2:
  19422. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19423. break;
  19424. case 3:
  19425. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19426. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19427. break;
  19428. }
  19429. light.id = parsedLight.id;
  19430. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19431. if (parsedLight.intensity !== undefined) {
  19432. light.intensity = parsedLight.intensity;
  19433. }
  19434. if (parsedLight.range) {
  19435. light.range = parsedLight.range;
  19436. }
  19437. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19438. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19439. if (parsedLight.excludedMeshesIds) {
  19440. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19441. }
  19442. // Parent
  19443. if (parsedLight.parentId) {
  19444. light._waitingParentId = parsedLight.parentId;
  19445. }
  19446. if (parsedLight.includedOnlyMeshesIds) {
  19447. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19448. }
  19449. // Animations
  19450. if (parsedLight.animations) {
  19451. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19452. var parsedAnimation = parsedLight.animations[animationIndex];
  19453. light.animations.push(parseAnimation(parsedAnimation));
  19454. }
  19455. }
  19456. if (parsedLight.autoAnimate) {
  19457. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19458. }
  19459. };
  19460. var parseCamera = function (parsedCamera, scene) {
  19461. var camera;
  19462. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19463. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19464. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19465. var alpha = parsedCamera.alpha;
  19466. var beta = parsedCamera.beta;
  19467. var radius = parsedCamera.radius;
  19468. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19469. var eye_space = parsedCamera.eye_space;
  19470. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19471. }
  19472. else {
  19473. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19474. }
  19475. }
  19476. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19477. eye_space = parsedCamera.eye_space;
  19478. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19479. }
  19480. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19481. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19482. }
  19483. else if (parsedCamera.type === "FollowCamera") {
  19484. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19485. camera.heightOffset = parsedCamera.heightOffset;
  19486. camera.radius = parsedCamera.radius;
  19487. camera.rotationOffset = parsedCamera.rotationOffset;
  19488. if (lockedTargetMesh)
  19489. camera.target = lockedTargetMesh;
  19490. }
  19491. else if (parsedCamera.type === "GamepadCamera") {
  19492. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19493. }
  19494. else if (parsedCamera.type === "OculusCamera") {
  19495. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19496. }
  19497. else if (parsedCamera.type === "OculusGamepadCamera") {
  19498. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19499. }
  19500. else if (parsedCamera.type === "TouchCamera") {
  19501. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19502. }
  19503. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19504. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19505. }
  19506. else if (parsedCamera.type === "WebVRCamera") {
  19507. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19508. }
  19509. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19510. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19511. }
  19512. else {
  19513. // Free Camera is the default value
  19514. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19515. }
  19516. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19517. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19518. camera.lockedTarget = lockedTargetMesh;
  19519. }
  19520. camera.id = parsedCamera.id;
  19521. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19522. // Parent
  19523. if (parsedCamera.parentId) {
  19524. camera._waitingParentId = parsedCamera.parentId;
  19525. }
  19526. // Target
  19527. if (parsedCamera.target) {
  19528. if (camera.setTarget) {
  19529. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19530. }
  19531. else {
  19532. //For ArcRotate
  19533. camera.target = BABYLON.Vector3.FromArray(parsedCamera.target);
  19534. }
  19535. }
  19536. else {
  19537. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19538. }
  19539. camera.fov = parsedCamera.fov;
  19540. camera.minZ = parsedCamera.minZ;
  19541. camera.maxZ = parsedCamera.maxZ;
  19542. camera.speed = parsedCamera.speed;
  19543. camera.inertia = parsedCamera.inertia;
  19544. camera.checkCollisions = parsedCamera.checkCollisions;
  19545. camera.applyGravity = parsedCamera.applyGravity;
  19546. if (parsedCamera.ellipsoid) {
  19547. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19548. }
  19549. // Animations
  19550. if (parsedCamera.animations) {
  19551. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19552. var parsedAnimation = parsedCamera.animations[animationIndex];
  19553. camera.animations.push(parseAnimation(parsedAnimation));
  19554. }
  19555. }
  19556. if (parsedCamera.autoAnimate) {
  19557. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19558. }
  19559. // Layer Mask
  19560. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19561. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19562. }
  19563. else {
  19564. camera.layerMask = 0xFFFFFFFF;
  19565. }
  19566. return camera;
  19567. };
  19568. var parseGeometry = function (parsedGeometry, scene) {
  19569. var id = parsedGeometry.id;
  19570. return scene.getGeometryByID(id);
  19571. };
  19572. var parseBox = function (parsedBox, scene) {
  19573. if (parseGeometry(parsedBox, scene)) {
  19574. return null; // null since geometry could be something else than a box...
  19575. }
  19576. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19577. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19578. scene.pushGeometry(box, true);
  19579. return box;
  19580. };
  19581. var parseSphere = function (parsedSphere, scene) {
  19582. if (parseGeometry(parsedSphere, scene)) {
  19583. return null; // null since geometry could be something else than a sphere...
  19584. }
  19585. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19586. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19587. scene.pushGeometry(sphere, true);
  19588. return sphere;
  19589. };
  19590. var parseCylinder = function (parsedCylinder, scene) {
  19591. if (parseGeometry(parsedCylinder, scene)) {
  19592. return null; // null since geometry could be something else than a cylinder...
  19593. }
  19594. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19595. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19596. scene.pushGeometry(cylinder, true);
  19597. return cylinder;
  19598. };
  19599. var parseTorus = function (parsedTorus, scene) {
  19600. if (parseGeometry(parsedTorus, scene)) {
  19601. return null; // null since geometry could be something else than a torus...
  19602. }
  19603. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19604. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19605. scene.pushGeometry(torus, true);
  19606. return torus;
  19607. };
  19608. var parseGround = function (parsedGround, scene) {
  19609. if (parseGeometry(parsedGround, scene)) {
  19610. return null; // null since geometry could be something else than a ground...
  19611. }
  19612. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19613. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19614. scene.pushGeometry(ground, true);
  19615. return ground;
  19616. };
  19617. var parsePlane = function (parsedPlane, scene) {
  19618. if (parseGeometry(parsedPlane, scene)) {
  19619. return null; // null since geometry could be something else than a plane...
  19620. }
  19621. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19622. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19623. scene.pushGeometry(plane, true);
  19624. return plane;
  19625. };
  19626. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19627. if (parseGeometry(parsedTorusKnot, scene)) {
  19628. return null; // null since geometry could be something else than a torusKnot...
  19629. }
  19630. 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);
  19631. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19632. scene.pushGeometry(torusKnot, true);
  19633. return torusKnot;
  19634. };
  19635. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19636. if (parseGeometry(parsedVertexData, scene)) {
  19637. return null; // null since geometry could be a primitive
  19638. }
  19639. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19640. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19641. if (parsedVertexData.delayLoadingFile) {
  19642. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19643. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19644. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19645. geometry._delayInfo = [];
  19646. if (parsedVertexData.hasUVs) {
  19647. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19648. }
  19649. if (parsedVertexData.hasUVs2) {
  19650. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19651. }
  19652. if (parsedVertexData.hasColors) {
  19653. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19654. }
  19655. if (parsedVertexData.hasMatricesIndices) {
  19656. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19657. }
  19658. if (parsedVertexData.hasMatricesWeights) {
  19659. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19660. }
  19661. geometry._delayLoadingFunction = importVertexData;
  19662. }
  19663. else {
  19664. importVertexData(parsedVertexData, geometry);
  19665. }
  19666. scene.pushGeometry(geometry, true);
  19667. return geometry;
  19668. };
  19669. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19670. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19671. mesh.id = parsedMesh.id;
  19672. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19673. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19674. if (parsedMesh.rotationQuaternion) {
  19675. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19676. }
  19677. else if (parsedMesh.rotation) {
  19678. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19679. }
  19680. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19681. if (parsedMesh.localMatrix) {
  19682. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19683. }
  19684. else if (parsedMesh.pivotMatrix) {
  19685. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19686. }
  19687. mesh.setEnabled(parsedMesh.isEnabled);
  19688. mesh.isVisible = parsedMesh.isVisible;
  19689. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19690. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19691. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19692. if (parsedMesh.applyFog !== undefined) {
  19693. mesh.applyFog = parsedMesh.applyFog;
  19694. }
  19695. if (parsedMesh.pickable !== undefined) {
  19696. mesh.isPickable = parsedMesh.pickable;
  19697. }
  19698. if (parsedMesh.alphaIndex !== undefined) {
  19699. mesh.alphaIndex = parsedMesh.alphaIndex;
  19700. }
  19701. mesh.receiveShadows = parsedMesh.receiveShadows;
  19702. mesh.billboardMode = parsedMesh.billboardMode;
  19703. if (parsedMesh.visibility !== undefined) {
  19704. mesh.visibility = parsedMesh.visibility;
  19705. }
  19706. mesh.checkCollisions = parsedMesh.checkCollisions;
  19707. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19708. // Parent
  19709. if (parsedMesh.parentId) {
  19710. mesh._waitingParentId = parsedMesh.parentId;
  19711. }
  19712. // Actions
  19713. if (parsedMesh.actions !== undefined) {
  19714. mesh._waitingActions = parsedMesh.actions;
  19715. }
  19716. // Geometry
  19717. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19718. if (parsedMesh.delayLoadingFile) {
  19719. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19720. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19721. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19722. if (parsedMesh._binaryInfo) {
  19723. mesh._binaryInfo = parsedMesh._binaryInfo;
  19724. }
  19725. mesh._delayInfo = [];
  19726. if (parsedMesh.hasUVs) {
  19727. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19728. }
  19729. if (parsedMesh.hasUVs2) {
  19730. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19731. }
  19732. if (parsedMesh.hasColors) {
  19733. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19734. }
  19735. if (parsedMesh.hasMatricesIndices) {
  19736. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19737. }
  19738. if (parsedMesh.hasMatricesWeights) {
  19739. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19740. }
  19741. mesh._delayLoadingFunction = importGeometry;
  19742. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19743. mesh._checkDelayState();
  19744. }
  19745. }
  19746. else {
  19747. importGeometry(parsedMesh, mesh);
  19748. }
  19749. // Material
  19750. if (parsedMesh.materialId) {
  19751. mesh.setMaterialByID(parsedMesh.materialId);
  19752. }
  19753. else {
  19754. mesh.material = null;
  19755. }
  19756. // Skeleton
  19757. if (parsedMesh.skeletonId > -1) {
  19758. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19759. }
  19760. // Physics
  19761. if (parsedMesh.physicsImpostor) {
  19762. if (!scene.isPhysicsEnabled()) {
  19763. scene.enablePhysics();
  19764. }
  19765. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19766. }
  19767. // Animations
  19768. if (parsedMesh.animations) {
  19769. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19770. var parsedAnimation = parsedMesh.animations[animationIndex];
  19771. mesh.animations.push(parseAnimation(parsedAnimation));
  19772. }
  19773. }
  19774. if (parsedMesh.autoAnimate) {
  19775. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19776. }
  19777. // Layer Mask
  19778. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19779. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19780. }
  19781. else {
  19782. mesh.layerMask = 0xFFFFFFFF;
  19783. }
  19784. // Instances
  19785. if (parsedMesh.instances) {
  19786. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19787. var parsedInstance = parsedMesh.instances[index];
  19788. var instance = mesh.createInstance(parsedInstance.name);
  19789. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19790. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19791. if (parsedInstance.rotationQuaternion) {
  19792. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19793. }
  19794. else if (parsedInstance.rotation) {
  19795. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19796. }
  19797. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19798. instance.checkCollisions = mesh.checkCollisions;
  19799. if (parsedMesh.animations) {
  19800. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19801. parsedAnimation = parsedMesh.animations[animationIndex];
  19802. instance.animations.push(parseAnimation(parsedAnimation));
  19803. }
  19804. }
  19805. }
  19806. }
  19807. return mesh;
  19808. };
  19809. var parseActions = function (parsedActions, object, scene) {
  19810. var actionManager = new BABYLON.ActionManager(scene);
  19811. if (object === null)
  19812. scene.actionManager = actionManager;
  19813. else
  19814. object.actionManager = actionManager;
  19815. // instanciate a new object
  19816. var instanciate = function (name, params) {
  19817. var newInstance = Object.create(BABYLON[name].prototype);
  19818. newInstance.constructor.apply(newInstance, params);
  19819. return newInstance;
  19820. };
  19821. var parseParameter = function (name, value, target, propertyPath) {
  19822. if (propertyPath === null) {
  19823. // String, boolean or float
  19824. var floatValue = parseFloat(value);
  19825. if (value === "true" || value === "false")
  19826. return value === "true";
  19827. else
  19828. return isNaN(floatValue) ? value : floatValue;
  19829. }
  19830. var effectiveTarget = propertyPath.split(".");
  19831. var values = value.split(",");
  19832. for (var i = 0; i < effectiveTarget.length; i++) {
  19833. target = target[effectiveTarget[i]];
  19834. }
  19835. // Return appropriate value with its type
  19836. if (target instanceof Boolean)
  19837. return values[0] === "true";
  19838. if (target instanceof String)
  19839. return values[0];
  19840. // Parameters with multiple values such as Vector3 etc.
  19841. var split = new Array();
  19842. for (var i = 0; i < values.length; i++)
  19843. split.push(parseFloat(values[i]));
  19844. if (target instanceof BABYLON.Vector3)
  19845. return BABYLON.Vector3.FromArray(split);
  19846. if (target instanceof BABYLON.Vector4)
  19847. return BABYLON.Vector4.FromArray(split);
  19848. if (target instanceof BABYLON.Color3)
  19849. return BABYLON.Color3.FromArray(split);
  19850. if (target instanceof BABYLON.Color4)
  19851. return BABYLON.Color4.FromArray(split);
  19852. return parseFloat(values[0]);
  19853. };
  19854. // traverse graph per trigger
  19855. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19856. if (combineArray === void 0) { combineArray = null; }
  19857. if (parsedAction.detached)
  19858. return;
  19859. var parameters = new Array();
  19860. var target = null;
  19861. var propertyPath = null;
  19862. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19863. // Parameters
  19864. if (parsedAction.type === 2)
  19865. parameters.push(actionManager);
  19866. else
  19867. parameters.push(trigger);
  19868. if (combine) {
  19869. var actions = new Array();
  19870. for (var j = 0; j < parsedAction.combine.length; j++) {
  19871. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19872. }
  19873. parameters.push(actions);
  19874. }
  19875. else {
  19876. for (var i = 0; i < parsedAction.properties.length; i++) {
  19877. var value = parsedAction.properties[i].value;
  19878. var name = parsedAction.properties[i].name;
  19879. if (name === "target")
  19880. value = target = scene.getNodeByName(value);
  19881. else if (name === "parent")
  19882. value = scene.getNodeByName(value);
  19883. else if (name === "sound")
  19884. value = scene.getSoundByName(value);
  19885. else if (name !== "propertyPath") {
  19886. if (parsedAction.type === 2 && name === "operator")
  19887. value = BABYLON.ValueCondition[value];
  19888. else
  19889. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19890. }
  19891. else {
  19892. propertyPath = value;
  19893. }
  19894. parameters.push(value);
  19895. }
  19896. }
  19897. parameters.push(condition);
  19898. // If interpolate value action
  19899. if (parsedAction.name === "InterpolateValueAction") {
  19900. var param = parameters[parameters.length - 2];
  19901. parameters[parameters.length - 1] = param;
  19902. parameters[parameters.length - 2] = condition;
  19903. }
  19904. // Action or condition(s) and not CombineAction
  19905. var newAction = instanciate(parsedAction.name, parameters);
  19906. if (combineArray === null) {
  19907. if (newAction instanceof BABYLON.Condition) {
  19908. condition = newAction;
  19909. newAction = action;
  19910. }
  19911. else {
  19912. condition = null;
  19913. if (action)
  19914. action.then(newAction);
  19915. else
  19916. actionManager.registerAction(newAction);
  19917. }
  19918. }
  19919. else {
  19920. combineArray.push(newAction);
  19921. }
  19922. for (var i = 0; i < parsedAction.children.length; i++)
  19923. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19924. };
  19925. for (var i = 0; i < parsedActions.children.length; i++) {
  19926. var triggerParams;
  19927. var trigger = parsedActions.children[i];
  19928. if (trigger.properties.length > 0) {
  19929. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19930. }
  19931. else
  19932. triggerParams = BABYLON.ActionManager[trigger.name];
  19933. for (var j = 0; j < trigger.children.length; j++) {
  19934. if (!trigger.detached)
  19935. traverse(trigger.children[j], triggerParams, null, null);
  19936. }
  19937. }
  19938. };
  19939. var parseSound = function (parsedSound, scene, rootUrl) {
  19940. var soundName = parsedSound.name;
  19941. var soundUrl = rootUrl + soundName;
  19942. var options = {
  19943. autoplay: parsedSound.autoplay,
  19944. loop: parsedSound.loop,
  19945. volume: parsedSound.volume,
  19946. spatialSound: parsedSound.spatialSound,
  19947. maxDistance: parsedSound.maxDistance,
  19948. rolloffFactor: parsedSound.rolloffFactor,
  19949. refDistance: parsedSound.refDistance,
  19950. distanceModel: parsedSound.distanceModel,
  19951. playbackRate: parsedSound.playbackRate
  19952. };
  19953. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19954. scene._removePendingData(newSound);
  19955. }, options);
  19956. scene._addPendingData(newSound);
  19957. if (parsedSound.position) {
  19958. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19959. newSound.setPosition(soundPosition);
  19960. }
  19961. if (parsedSound.isDirectional) {
  19962. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19963. if (parsedSound.localDirectionToMesh) {
  19964. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19965. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19966. }
  19967. }
  19968. if (parsedSound.connectedMeshId) {
  19969. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19970. if (connectedMesh) {
  19971. newSound.attachToMesh(connectedMesh);
  19972. }
  19973. }
  19974. };
  19975. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19976. names = (names instanceof Array) ? names : [names];
  19977. for (var i in names) {
  19978. if (mesh.name === names[i]) {
  19979. hierarchyIds.push(mesh.id);
  19980. return true;
  19981. }
  19982. }
  19983. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19984. hierarchyIds.push(mesh.id);
  19985. return true;
  19986. }
  19987. return false;
  19988. };
  19989. var importVertexData = function (parsedVertexData, geometry) {
  19990. var vertexData = new BABYLON.VertexData();
  19991. // positions
  19992. var positions = parsedVertexData.positions;
  19993. if (positions) {
  19994. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19995. }
  19996. // normals
  19997. var normals = parsedVertexData.normals;
  19998. if (normals) {
  19999. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  20000. }
  20001. // uvs
  20002. var uvs = parsedVertexData.uvs;
  20003. if (uvs) {
  20004. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  20005. }
  20006. // uv2s
  20007. var uv2s = parsedVertexData.uv2s;
  20008. if (uv2s) {
  20009. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  20010. }
  20011. // colors
  20012. var colors = parsedVertexData.colors;
  20013. if (colors) {
  20014. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  20015. }
  20016. // matricesIndices
  20017. var matricesIndices = parsedVertexData.matricesIndices;
  20018. if (matricesIndices) {
  20019. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  20020. }
  20021. // matricesWeights
  20022. var matricesWeights = parsedVertexData.matricesWeights;
  20023. if (matricesWeights) {
  20024. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  20025. }
  20026. // indices
  20027. var indices = parsedVertexData.indices;
  20028. if (indices) {
  20029. vertexData.indices = indices;
  20030. }
  20031. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  20032. };
  20033. var importGeometry = function (parsedGeometry, mesh) {
  20034. var scene = mesh.getScene();
  20035. // Geometry
  20036. var geometryId = parsedGeometry.geometryId;
  20037. if (geometryId) {
  20038. var geometry = scene.getGeometryByID(geometryId);
  20039. if (geometry) {
  20040. geometry.applyToMesh(mesh);
  20041. }
  20042. }
  20043. else if (parsedGeometry instanceof ArrayBuffer) {
  20044. var binaryInfo = mesh._binaryInfo;
  20045. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  20046. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  20047. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  20048. }
  20049. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  20050. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  20051. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  20052. }
  20053. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  20054. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  20055. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  20056. }
  20057. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  20058. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  20059. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  20060. }
  20061. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  20062. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  20063. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  20064. }
  20065. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  20066. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  20067. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  20068. }
  20069. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  20070. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  20071. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  20072. }
  20073. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  20074. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  20075. mesh.setIndices(indicesData);
  20076. }
  20077. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  20078. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  20079. mesh.subMeshes = [];
  20080. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  20081. var materialIndex = subMeshesData[(i * 5) + 0];
  20082. var verticesStart = subMeshesData[(i * 5) + 1];
  20083. var verticesCount = subMeshesData[(i * 5) + 2];
  20084. var indexStart = subMeshesData[(i * 5) + 3];
  20085. var indexCount = subMeshesData[(i * 5) + 4];
  20086. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  20087. }
  20088. }
  20089. }
  20090. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  20091. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  20092. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  20093. if (parsedGeometry.uvs) {
  20094. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  20095. }
  20096. if (parsedGeometry.uvs2) {
  20097. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  20098. }
  20099. if (parsedGeometry.colors) {
  20100. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  20101. }
  20102. if (parsedGeometry.matricesIndices) {
  20103. if (!parsedGeometry.matricesIndices._isExpanded) {
  20104. var floatIndices = [];
  20105. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  20106. var matricesIndex = parsedGeometry.matricesIndices[i];
  20107. floatIndices.push(matricesIndex & 0x000000FF);
  20108. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  20109. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  20110. floatIndices.push(matricesIndex >> 24);
  20111. }
  20112. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  20113. }
  20114. else {
  20115. delete parsedGeometry.matricesIndices._isExpanded;
  20116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  20117. }
  20118. }
  20119. if (parsedGeometry.matricesWeights) {
  20120. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  20121. }
  20122. mesh.setIndices(parsedGeometry.indices);
  20123. // SubMeshes
  20124. if (parsedGeometry.subMeshes) {
  20125. mesh.subMeshes = [];
  20126. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  20127. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  20128. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  20129. }
  20130. }
  20131. }
  20132. // Flat shading
  20133. if (mesh._shouldGenerateFlatShading) {
  20134. mesh.convertToFlatShadedMesh();
  20135. delete mesh._shouldGenerateFlatShading;
  20136. }
  20137. // Update
  20138. mesh.computeWorldMatrix(true);
  20139. // Octree
  20140. if (scene._selectionOctree) {
  20141. scene._selectionOctree.addMesh(mesh);
  20142. }
  20143. };
  20144. BABYLON.SceneLoader.RegisterPlugin({
  20145. extensions: ".babylon",
  20146. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  20147. var parsedData = JSON.parse(data);
  20148. var loadedSkeletonsIds = [];
  20149. var loadedMaterialsIds = [];
  20150. var hierarchyIds = [];
  20151. for (var index = 0; index < parsedData.meshes.length; index++) {
  20152. var parsedMesh = parsedData.meshes[index];
  20153. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  20154. if (meshesNames instanceof Array) {
  20155. // Remove found mesh name from list.
  20156. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  20157. }
  20158. // Material ?
  20159. if (parsedMesh.materialId) {
  20160. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  20161. if (!materialFound) {
  20162. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  20163. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  20164. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  20165. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  20166. var subMatId = parsedMultiMaterial.materials[matIndex];
  20167. loadedMaterialsIds.push(subMatId);
  20168. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  20169. }
  20170. loadedMaterialsIds.push(parsedMultiMaterial.id);
  20171. parseMultiMaterial(parsedMultiMaterial, scene);
  20172. materialFound = true;
  20173. break;
  20174. }
  20175. }
  20176. }
  20177. if (!materialFound) {
  20178. loadedMaterialsIds.push(parsedMesh.materialId);
  20179. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  20180. }
  20181. }
  20182. // Skeleton ?
  20183. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  20184. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  20185. if (!skeletonAlreadyLoaded) {
  20186. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  20187. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  20188. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  20189. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  20190. loadedSkeletonsIds.push(parsedSkeleton.id);
  20191. }
  20192. }
  20193. }
  20194. }
  20195. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  20196. meshes.push(mesh);
  20197. }
  20198. }
  20199. for (index = 0; index < scene.meshes.length; index++) {
  20200. var currentMesh = scene.meshes[index];
  20201. if (currentMesh._waitingParentId) {
  20202. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  20203. currentMesh._waitingParentId = undefined;
  20204. }
  20205. }
  20206. // Particles
  20207. if (parsedData.particleSystems) {
  20208. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20209. var parsedParticleSystem = parsedData.particleSystems[index];
  20210. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  20211. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  20212. }
  20213. }
  20214. }
  20215. return true;
  20216. },
  20217. load: function (scene, data, rootUrl) {
  20218. var parsedData = JSON.parse(data);
  20219. // Scene
  20220. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  20221. scene.autoClear = parsedData.autoClear;
  20222. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  20223. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  20224. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  20225. // Fog
  20226. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  20227. scene.fogMode = parsedData.fogMode;
  20228. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  20229. scene.fogStart = parsedData.fogStart;
  20230. scene.fogEnd = parsedData.fogEnd;
  20231. scene.fogDensity = parsedData.fogDensity;
  20232. }
  20233. for (var index = 0; index < parsedData.lights.length; index++) {
  20234. var parsedLight = parsedData.lights[index];
  20235. parseLight(parsedLight, scene);
  20236. }
  20237. // Materials
  20238. if (parsedData.materials) {
  20239. for (index = 0; index < parsedData.materials.length; index++) {
  20240. var parsedMaterial = parsedData.materials[index];
  20241. parseMaterial(parsedMaterial, scene, rootUrl);
  20242. }
  20243. }
  20244. if (parsedData.multiMaterials) {
  20245. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  20246. var parsedMultiMaterial = parsedData.multiMaterials[index];
  20247. parseMultiMaterial(parsedMultiMaterial, scene);
  20248. }
  20249. }
  20250. // Skeletons
  20251. if (parsedData.skeletons) {
  20252. for (index = 0; index < parsedData.skeletons.length; index++) {
  20253. var parsedSkeleton = parsedData.skeletons[index];
  20254. parseSkeleton(parsedSkeleton, scene);
  20255. }
  20256. }
  20257. // Geometries
  20258. var geometries = parsedData.geometries;
  20259. if (geometries) {
  20260. // Boxes
  20261. var boxes = geometries.boxes;
  20262. if (boxes) {
  20263. for (index = 0; index < boxes.length; index++) {
  20264. var parsedBox = boxes[index];
  20265. parseBox(parsedBox, scene);
  20266. }
  20267. }
  20268. // Spheres
  20269. var spheres = geometries.spheres;
  20270. if (spheres) {
  20271. for (index = 0; index < spheres.length; index++) {
  20272. var parsedSphere = spheres[index];
  20273. parseSphere(parsedSphere, scene);
  20274. }
  20275. }
  20276. // Cylinders
  20277. var cylinders = geometries.cylinders;
  20278. if (cylinders) {
  20279. for (index = 0; index < cylinders.length; index++) {
  20280. var parsedCylinder = cylinders[index];
  20281. parseCylinder(parsedCylinder, scene);
  20282. }
  20283. }
  20284. // Toruses
  20285. var toruses = geometries.toruses;
  20286. if (toruses) {
  20287. for (index = 0; index < toruses.length; index++) {
  20288. var parsedTorus = toruses[index];
  20289. parseTorus(parsedTorus, scene);
  20290. }
  20291. }
  20292. // Grounds
  20293. var grounds = geometries.grounds;
  20294. if (grounds) {
  20295. for (index = 0; index < grounds.length; index++) {
  20296. var parsedGround = grounds[index];
  20297. parseGround(parsedGround, scene);
  20298. }
  20299. }
  20300. // Planes
  20301. var planes = geometries.planes;
  20302. if (planes) {
  20303. for (index = 0; index < planes.length; index++) {
  20304. var parsedPlane = planes[index];
  20305. parsePlane(parsedPlane, scene);
  20306. }
  20307. }
  20308. // TorusKnots
  20309. var torusKnots = geometries.torusKnots;
  20310. if (torusKnots) {
  20311. for (index = 0; index < torusKnots.length; index++) {
  20312. var parsedTorusKnot = torusKnots[index];
  20313. parseTorusKnot(parsedTorusKnot, scene);
  20314. }
  20315. }
  20316. // VertexData
  20317. var vertexData = geometries.vertexData;
  20318. if (vertexData) {
  20319. for (index = 0; index < vertexData.length; index++) {
  20320. var parsedVertexData = vertexData[index];
  20321. parseVertexData(parsedVertexData, scene, rootUrl);
  20322. }
  20323. }
  20324. }
  20325. for (index = 0; index < parsedData.meshes.length; index++) {
  20326. var parsedMesh = parsedData.meshes[index];
  20327. parseMesh(parsedMesh, scene, rootUrl);
  20328. }
  20329. for (index = 0; index < parsedData.cameras.length; index++) {
  20330. var parsedCamera = parsedData.cameras[index];
  20331. parseCamera(parsedCamera, scene);
  20332. }
  20333. if (parsedData.activeCameraID) {
  20334. scene.setActiveCameraByID(parsedData.activeCameraID);
  20335. }
  20336. for (index = 0; index < scene.cameras.length; index++) {
  20337. var camera = scene.cameras[index];
  20338. if (camera._waitingParentId) {
  20339. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  20340. camera._waitingParentId = undefined;
  20341. }
  20342. }
  20343. for (index = 0; index < scene.lights.length; index++) {
  20344. var light = scene.lights[index];
  20345. if (light._waitingParentId) {
  20346. light.parent = scene.getLastEntryByID(light._waitingParentId);
  20347. light._waitingParentId = undefined;
  20348. }
  20349. }
  20350. // Sounds
  20351. if (parsedData.sounds) {
  20352. for (index = 0; index < parsedData.sounds.length; index++) {
  20353. var parsedSound = parsedData.sounds[index];
  20354. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  20355. parseSound(parsedSound, scene, rootUrl);
  20356. }
  20357. else {
  20358. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  20359. }
  20360. }
  20361. }
  20362. for (index = 0; index < scene.meshes.length; index++) {
  20363. var mesh = scene.meshes[index];
  20364. if (mesh._waitingParentId) {
  20365. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20366. mesh._waitingParentId = undefined;
  20367. }
  20368. if (mesh._waitingActions) {
  20369. parseActions(mesh._waitingActions, mesh, scene);
  20370. mesh._waitingActions = undefined;
  20371. }
  20372. }
  20373. // Particles Systems
  20374. if (parsedData.particleSystems) {
  20375. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20376. var parsedParticleSystem = parsedData.particleSystems[index];
  20377. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20378. }
  20379. }
  20380. // Lens flares
  20381. if (parsedData.lensFlareSystems) {
  20382. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20383. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20384. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20385. }
  20386. }
  20387. // Shadows
  20388. if (parsedData.shadowGenerators) {
  20389. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20390. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20391. parseShadowGenerator(parsedShadowGenerator, scene);
  20392. }
  20393. }
  20394. // Actions (scene)
  20395. if (parsedData.actions) {
  20396. parseActions(parsedData.actions, null, scene);
  20397. }
  20398. // Finish
  20399. return true;
  20400. }
  20401. });
  20402. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20403. })(BABYLON || (BABYLON = {}));
  20404. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20405. (function (BABYLON) {
  20406. // Unique ID when we import meshes from Babylon to CSG
  20407. var currentCSGMeshId = 0;
  20408. // # class Vertex
  20409. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20410. // one to provide additional features like texture coordinates and vertex
  20411. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20412. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20413. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20414. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20415. // is not used anywhere else.
  20416. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20417. var Vertex = (function () {
  20418. function Vertex(pos, normal, uv) {
  20419. this.pos = pos;
  20420. this.normal = normal;
  20421. this.uv = uv;
  20422. }
  20423. Vertex.prototype.clone = function () {
  20424. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20425. };
  20426. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20427. // orientation of a polygon is flipped.
  20428. Vertex.prototype.flip = function () {
  20429. this.normal = this.normal.scale(-1);
  20430. };
  20431. // Create a new vertex between this vertex and `other` by linearly
  20432. // interpolating all properties using a parameter of `t`. Subclasses should
  20433. // override this to interpolate additional properties.
  20434. Vertex.prototype.interpolate = function (other, t) {
  20435. 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));
  20436. };
  20437. return Vertex;
  20438. })();
  20439. // # class Plane
  20440. // Represents a plane in 3D space.
  20441. var Plane = (function () {
  20442. function Plane(normal, w) {
  20443. this.normal = normal;
  20444. this.w = w;
  20445. }
  20446. Plane.FromPoints = function (a, b, c) {
  20447. var v0 = c.subtract(a);
  20448. var v1 = b.subtract(a);
  20449. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20450. return null;
  20451. }
  20452. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20453. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20454. };
  20455. Plane.prototype.clone = function () {
  20456. return new Plane(this.normal.clone(), this.w);
  20457. };
  20458. Plane.prototype.flip = function () {
  20459. this.normal.scaleInPlace(-1);
  20460. this.w = -this.w;
  20461. };
  20462. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20463. // fragments in the appropriate lists. Coplanar polygons go into either
  20464. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20465. // respect to this plane. Polygons in front or in back of this plane go into
  20466. // either `front` or `back`.
  20467. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20468. var COPLANAR = 0;
  20469. var FRONT = 1;
  20470. var BACK = 2;
  20471. var SPANNING = 3;
  20472. // Classify each point as well as the entire polygon into one of the above
  20473. // four classes.
  20474. var polygonType = 0;
  20475. var types = [];
  20476. for (var i = 0; i < polygon.vertices.length; i++) {
  20477. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20478. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20479. polygonType |= type;
  20480. types.push(type);
  20481. }
  20482. switch (polygonType) {
  20483. case COPLANAR:
  20484. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20485. break;
  20486. case FRONT:
  20487. front.push(polygon);
  20488. break;
  20489. case BACK:
  20490. back.push(polygon);
  20491. break;
  20492. case SPANNING:
  20493. var f = [], b = [];
  20494. for (i = 0; i < polygon.vertices.length; i++) {
  20495. var j = (i + 1) % polygon.vertices.length;
  20496. var ti = types[i], tj = types[j];
  20497. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20498. if (ti != BACK)
  20499. f.push(vi);
  20500. if (ti != FRONT)
  20501. b.push(ti != BACK ? vi.clone() : vi);
  20502. if ((ti | tj) == SPANNING) {
  20503. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20504. var v = vi.interpolate(vj, t);
  20505. f.push(v);
  20506. b.push(v.clone());
  20507. }
  20508. }
  20509. if (f.length >= 3) {
  20510. var poly = new Polygon(f, polygon.shared);
  20511. if (poly.plane)
  20512. front.push(poly);
  20513. }
  20514. if (b.length >= 3) {
  20515. poly = new Polygon(b, polygon.shared);
  20516. if (poly.plane)
  20517. back.push(poly);
  20518. }
  20519. break;
  20520. }
  20521. };
  20522. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20523. // point is on the plane.
  20524. Plane.EPSILON = 1e-5;
  20525. return Plane;
  20526. })();
  20527. // # class Polygon
  20528. // Represents a convex polygon. The vertices used to initialize a polygon must
  20529. // be coplanar and form a convex loop.
  20530. //
  20531. // Each convex polygon has a `shared` property, which is shared between all
  20532. // polygons that are clones of each other or were split from the same polygon.
  20533. // This can be used to define per-polygon properties (such as surface color).
  20534. var Polygon = (function () {
  20535. function Polygon(vertices, shared) {
  20536. this.vertices = vertices;
  20537. this.shared = shared;
  20538. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20539. }
  20540. Polygon.prototype.clone = function () {
  20541. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20542. return new Polygon(vertices, this.shared);
  20543. };
  20544. Polygon.prototype.flip = function () {
  20545. this.vertices.reverse().map(function (v) {
  20546. v.flip();
  20547. });
  20548. this.plane.flip();
  20549. };
  20550. return Polygon;
  20551. })();
  20552. // # class Node
  20553. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20554. // by picking a polygon to split along. That polygon (and all other coplanar
  20555. // polygons) are added directly to that node and the other polygons are added to
  20556. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20557. // no distinction between internal and leaf nodes.
  20558. var Node = (function () {
  20559. function Node(polygons) {
  20560. this.plane = null;
  20561. this.front = null;
  20562. this.back = null;
  20563. this.polygons = [];
  20564. if (polygons) {
  20565. this.build(polygons);
  20566. }
  20567. }
  20568. Node.prototype.clone = function () {
  20569. var node = new Node();
  20570. node.plane = this.plane && this.plane.clone();
  20571. node.front = this.front && this.front.clone();
  20572. node.back = this.back && this.back.clone();
  20573. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20574. return node;
  20575. };
  20576. // Convert solid space to empty space and empty space to solid space.
  20577. Node.prototype.invert = function () {
  20578. for (var i = 0; i < this.polygons.length; i++) {
  20579. this.polygons[i].flip();
  20580. }
  20581. if (this.plane) {
  20582. this.plane.flip();
  20583. }
  20584. if (this.front) {
  20585. this.front.invert();
  20586. }
  20587. if (this.back) {
  20588. this.back.invert();
  20589. }
  20590. var temp = this.front;
  20591. this.front = this.back;
  20592. this.back = temp;
  20593. };
  20594. // Recursively remove all polygons in `polygons` that are inside this BSP
  20595. // tree.
  20596. Node.prototype.clipPolygons = function (polygons) {
  20597. if (!this.plane)
  20598. return polygons.slice();
  20599. var front = [], back = [];
  20600. for (var i = 0; i < polygons.length; i++) {
  20601. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20602. }
  20603. if (this.front) {
  20604. front = this.front.clipPolygons(front);
  20605. }
  20606. if (this.back) {
  20607. back = this.back.clipPolygons(back);
  20608. }
  20609. else {
  20610. back = [];
  20611. }
  20612. return front.concat(back);
  20613. };
  20614. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20615. // `bsp`.
  20616. Node.prototype.clipTo = function (bsp) {
  20617. this.polygons = bsp.clipPolygons(this.polygons);
  20618. if (this.front)
  20619. this.front.clipTo(bsp);
  20620. if (this.back)
  20621. this.back.clipTo(bsp);
  20622. };
  20623. // Return a list of all polygons in this BSP tree.
  20624. Node.prototype.allPolygons = function () {
  20625. var polygons = this.polygons.slice();
  20626. if (this.front)
  20627. polygons = polygons.concat(this.front.allPolygons());
  20628. if (this.back)
  20629. polygons = polygons.concat(this.back.allPolygons());
  20630. return polygons;
  20631. };
  20632. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20633. // new polygons are filtered down to the bottom of the tree and become new
  20634. // nodes there. Each set of polygons is partitioned using the first polygon
  20635. // (no heuristic is used to pick a good split).
  20636. Node.prototype.build = function (polygons) {
  20637. if (!polygons.length)
  20638. return;
  20639. if (!this.plane)
  20640. this.plane = polygons[0].plane.clone();
  20641. var front = [], back = [];
  20642. for (var i = 0; i < polygons.length; i++) {
  20643. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20644. }
  20645. if (front.length) {
  20646. if (!this.front)
  20647. this.front = new Node();
  20648. this.front.build(front);
  20649. }
  20650. if (back.length) {
  20651. if (!this.back)
  20652. this.back = new Node();
  20653. this.back.build(back);
  20654. }
  20655. };
  20656. return Node;
  20657. })();
  20658. var CSG = (function () {
  20659. function CSG() {
  20660. this.polygons = new Array();
  20661. }
  20662. // Convert BABYLON.Mesh to BABYLON.CSG
  20663. CSG.FromMesh = function (mesh) {
  20664. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20665. if (mesh instanceof BABYLON.Mesh) {
  20666. mesh.computeWorldMatrix(true);
  20667. var matrix = mesh.getWorldMatrix();
  20668. var meshPosition = mesh.position.clone();
  20669. var meshRotation = mesh.rotation.clone();
  20670. var meshScaling = mesh.scaling.clone();
  20671. }
  20672. else {
  20673. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20674. }
  20675. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20676. var subMeshes = mesh.subMeshes;
  20677. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20678. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20679. vertices = [];
  20680. for (var j = 0; j < 3; j++) {
  20681. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20682. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20683. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20684. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20685. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20686. vertex = new Vertex(position, normal, uv);
  20687. vertices.push(vertex);
  20688. }
  20689. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20690. // To handle the case of degenerated triangle
  20691. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20692. if (polygon.plane)
  20693. polygons.push(polygon);
  20694. }
  20695. }
  20696. var csg = CSG.FromPolygons(polygons);
  20697. csg.matrix = matrix;
  20698. csg.position = meshPosition;
  20699. csg.rotation = meshRotation;
  20700. csg.scaling = meshScaling;
  20701. currentCSGMeshId++;
  20702. return csg;
  20703. };
  20704. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20705. CSG.FromPolygons = function (polygons) {
  20706. var csg = new BABYLON.CSG();
  20707. csg.polygons = polygons;
  20708. return csg;
  20709. };
  20710. CSG.prototype.clone = function () {
  20711. var csg = new BABYLON.CSG();
  20712. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20713. csg.copyTransformAttributes(this);
  20714. return csg;
  20715. };
  20716. CSG.prototype.toPolygons = function () {
  20717. return this.polygons;
  20718. };
  20719. CSG.prototype.union = function (csg) {
  20720. var a = new Node(this.clone().polygons);
  20721. var b = new Node(csg.clone().polygons);
  20722. a.clipTo(b);
  20723. b.clipTo(a);
  20724. b.invert();
  20725. b.clipTo(a);
  20726. b.invert();
  20727. a.build(b.allPolygons());
  20728. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20729. };
  20730. CSG.prototype.unionInPlace = function (csg) {
  20731. var a = new Node(this.polygons);
  20732. var b = new Node(csg.polygons);
  20733. a.clipTo(b);
  20734. b.clipTo(a);
  20735. b.invert();
  20736. b.clipTo(a);
  20737. b.invert();
  20738. a.build(b.allPolygons());
  20739. this.polygons = a.allPolygons();
  20740. };
  20741. CSG.prototype.subtract = function (csg) {
  20742. var a = new Node(this.clone().polygons);
  20743. var b = new Node(csg.clone().polygons);
  20744. a.invert();
  20745. a.clipTo(b);
  20746. b.clipTo(a);
  20747. b.invert();
  20748. b.clipTo(a);
  20749. b.invert();
  20750. a.build(b.allPolygons());
  20751. a.invert();
  20752. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20753. };
  20754. CSG.prototype.subtractInPlace = function (csg) {
  20755. var a = new Node(this.polygons);
  20756. var b = new Node(csg.polygons);
  20757. a.invert();
  20758. a.clipTo(b);
  20759. b.clipTo(a);
  20760. b.invert();
  20761. b.clipTo(a);
  20762. b.invert();
  20763. a.build(b.allPolygons());
  20764. a.invert();
  20765. this.polygons = a.allPolygons();
  20766. };
  20767. CSG.prototype.intersect = function (csg) {
  20768. var a = new Node(this.clone().polygons);
  20769. var b = new Node(csg.clone().polygons);
  20770. a.invert();
  20771. b.clipTo(a);
  20772. b.invert();
  20773. a.clipTo(b);
  20774. b.clipTo(a);
  20775. a.build(b.allPolygons());
  20776. a.invert();
  20777. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20778. };
  20779. CSG.prototype.intersectInPlace = function (csg) {
  20780. var a = new Node(this.polygons);
  20781. var b = new Node(csg.polygons);
  20782. a.invert();
  20783. b.clipTo(a);
  20784. b.invert();
  20785. a.clipTo(b);
  20786. b.clipTo(a);
  20787. a.build(b.allPolygons());
  20788. a.invert();
  20789. this.polygons = a.allPolygons();
  20790. };
  20791. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20792. // not modified.
  20793. CSG.prototype.inverse = function () {
  20794. var csg = this.clone();
  20795. csg.inverseInPlace();
  20796. return csg;
  20797. };
  20798. CSG.prototype.inverseInPlace = function () {
  20799. this.polygons.map(function (p) {
  20800. p.flip();
  20801. });
  20802. };
  20803. // This is used to keep meshes transformations so they can be restored
  20804. // when we build back a Babylon Mesh
  20805. // NB : All CSG operations are performed in world coordinates
  20806. CSG.prototype.copyTransformAttributes = function (csg) {
  20807. this.matrix = csg.matrix;
  20808. this.position = csg.position;
  20809. this.rotation = csg.rotation;
  20810. this.scaling = csg.scaling;
  20811. return this;
  20812. };
  20813. // Build Raw mesh from CSG
  20814. // Coordinates here are in world space
  20815. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20816. var matrix = this.matrix.clone();
  20817. matrix.invert();
  20818. 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;
  20819. if (keepSubMeshes) {
  20820. // Sort Polygons, since subMeshes are indices range
  20821. polygons.sort(function (a, b) {
  20822. if (a.shared.meshId === b.shared.meshId) {
  20823. return a.shared.subMeshId - b.shared.subMeshId;
  20824. }
  20825. else {
  20826. return a.shared.meshId - b.shared.meshId;
  20827. }
  20828. });
  20829. }
  20830. for (var i = 0, il = polygons.length; i < il; i++) {
  20831. polygon = polygons[i];
  20832. // Building SubMeshes
  20833. if (!subMesh_dict[polygon.shared.meshId]) {
  20834. subMesh_dict[polygon.shared.meshId] = {};
  20835. }
  20836. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20837. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20838. indexStart: +Infinity,
  20839. indexEnd: -Infinity,
  20840. materialIndex: polygon.shared.materialIndex
  20841. };
  20842. }
  20843. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20844. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20845. polygonIndices[0] = 0;
  20846. polygonIndices[1] = j - 1;
  20847. polygonIndices[2] = j;
  20848. for (var k = 0; k < 3; k++) {
  20849. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20850. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20851. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20852. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20853. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20854. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20855. // Check if 2 points can be merged
  20856. 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)) {
  20857. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20858. uvs.push(uv.x, uv.y);
  20859. normals.push(normal.x, normal.y, normal.z);
  20860. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20861. }
  20862. indices.push(vertex_idx);
  20863. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20864. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20865. currentIndex++;
  20866. }
  20867. }
  20868. }
  20869. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20870. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20871. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20872. mesh.setIndices(indices);
  20873. if (keepSubMeshes) {
  20874. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20875. var materialIndexOffset = 0, materialMaxIndex;
  20876. mesh.subMeshes.length = 0;
  20877. for (var m in subMesh_dict) {
  20878. materialMaxIndex = -1;
  20879. for (var sm in subMesh_dict[m]) {
  20880. subMesh_obj = subMesh_dict[m][sm];
  20881. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20882. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20883. }
  20884. materialIndexOffset += ++materialMaxIndex;
  20885. }
  20886. }
  20887. return mesh;
  20888. };
  20889. // Build Mesh from CSG taking material and transforms into account
  20890. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20891. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20892. mesh.material = material;
  20893. mesh.position.copyFrom(this.position);
  20894. mesh.rotation.copyFrom(this.rotation);
  20895. mesh.scaling.copyFrom(this.scaling);
  20896. mesh.computeWorldMatrix(true);
  20897. return mesh;
  20898. };
  20899. return CSG;
  20900. })();
  20901. BABYLON.CSG = CSG;
  20902. })(BABYLON || (BABYLON = {}));
  20903. //# sourceMappingURL=babylon.csg.js.map
  20904. var BABYLON;
  20905. (function (BABYLON) {
  20906. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20907. __extends(OculusDistortionCorrectionPostProcess, _super);
  20908. //ANY
  20909. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20910. var _this = this;
  20911. _super.call(this, name, "oculusDistortionCorrection", [
  20912. 'LensCenter',
  20913. 'Scale',
  20914. 'ScaleIn',
  20915. 'HmdWarpParam'
  20916. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20917. this._isRightEye = isRightEye;
  20918. this._distortionFactors = cameraSettings.DistortionK;
  20919. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20920. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20921. this.onSizeChanged = function () {
  20922. _this.aspectRatio = _this.width * .5 / _this.height;
  20923. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20924. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20925. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20926. };
  20927. this.onApply = function (effect) {
  20928. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20929. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20930. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20931. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20932. };
  20933. }
  20934. return OculusDistortionCorrectionPostProcess;
  20935. })(BABYLON.PostProcess);
  20936. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20937. })(BABYLON || (BABYLON = {}));
  20938. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20939. // 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
  20940. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20941. var BABYLON;
  20942. (function (BABYLON) {
  20943. (function (JoystickAxis) {
  20944. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20945. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20946. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20947. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20948. var JoystickAxis = BABYLON.JoystickAxis;
  20949. var VirtualJoystick = (function () {
  20950. function VirtualJoystick(leftJoystick) {
  20951. var _this = this;
  20952. if (leftJoystick) {
  20953. this._leftJoystick = true;
  20954. }
  20955. else {
  20956. this._leftJoystick = false;
  20957. }
  20958. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20959. VirtualJoystick._globalJoystickIndex++;
  20960. // By default left & right arrow keys are moving the X
  20961. // and up & down keys are moving the Y
  20962. this._axisTargetedByLeftAndRight = 0 /* X */;
  20963. this._axisTargetedByUpAndDown = 1 /* Y */;
  20964. this.reverseLeftRight = false;
  20965. this.reverseUpDown = false;
  20966. // collections of pointers
  20967. this._touches = new BABYLON.VirtualJoystick.Collection();
  20968. this.deltaPosition = BABYLON.Vector3.Zero();
  20969. this._joystickSensibility = 25;
  20970. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20971. this._rotationSpeed = 25;
  20972. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20973. this._rotateOnAxisRelativeToMesh = false;
  20974. // injecting a canvas element on top of the canvas 3D game
  20975. if (!VirtualJoystick.vjCanvas) {
  20976. window.addEventListener("resize", function () {
  20977. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20978. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20979. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20980. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20981. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20982. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20983. }, false);
  20984. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20985. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20986. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20987. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20988. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20989. VirtualJoystick.vjCanvas.style.width = "100%";
  20990. VirtualJoystick.vjCanvas.style.height = "100%";
  20991. VirtualJoystick.vjCanvas.style.position = "absolute";
  20992. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20993. VirtualJoystick.vjCanvas.style.top = "0px";
  20994. VirtualJoystick.vjCanvas.style.left = "0px";
  20995. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20996. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20997. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20998. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20999. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21000. document.body.appendChild(VirtualJoystick.vjCanvas);
  21001. }
  21002. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  21003. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  21004. this.pressed = false;
  21005. // default joystick color
  21006. this._joystickColor = "cyan";
  21007. this._joystickPointerID = -1;
  21008. // current joystick position
  21009. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  21010. // origin joystick position
  21011. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  21012. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  21013. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  21014. _this._onPointerDown(evt);
  21015. }, false);
  21016. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  21017. _this._onPointerMove(evt);
  21018. }, false);
  21019. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  21020. _this._onPointerUp(evt);
  21021. }, false);
  21022. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  21023. _this._onPointerUp(evt);
  21024. }, false);
  21025. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  21026. evt.preventDefault(); // Disables system menu
  21027. }, false);
  21028. requestAnimationFrame(function () {
  21029. _this._drawVirtualJoystick();
  21030. });
  21031. }
  21032. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  21033. this._joystickSensibility = newJoystickSensibility;
  21034. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  21035. };
  21036. VirtualJoystick.prototype._onPointerDown = function (e) {
  21037. var positionOnScreenCondition;
  21038. e.preventDefault();
  21039. if (this._leftJoystick === true) {
  21040. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  21041. }
  21042. else {
  21043. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  21044. }
  21045. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  21046. // First contact will be dedicated to the virtual joystick
  21047. this._joystickPointerID = e.pointerId;
  21048. this._joystickPointerStartPos.x = e.clientX;
  21049. this._joystickPointerStartPos.y = e.clientY;
  21050. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  21051. this._deltaJoystickVector.x = 0;
  21052. this._deltaJoystickVector.y = 0;
  21053. this.pressed = true;
  21054. this._touches.add(e.pointerId.toString(), e);
  21055. }
  21056. else {
  21057. // You can only trigger the action buttons with a joystick declared
  21058. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  21059. this._action();
  21060. this._touches.add(e.pointerId.toString(), e);
  21061. }
  21062. }
  21063. };
  21064. VirtualJoystick.prototype._onPointerMove = function (e) {
  21065. // If the current pointer is the one associated to the joystick (first touch contact)
  21066. if (this._joystickPointerID == e.pointerId) {
  21067. this._joystickPointerPos.x = e.clientX;
  21068. this._joystickPointerPos.y = e.clientY;
  21069. this._deltaJoystickVector = this._joystickPointerPos.clone();
  21070. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  21071. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  21072. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  21073. switch (this._axisTargetedByLeftAndRight) {
  21074. case 0 /* X */:
  21075. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  21076. break;
  21077. case 1 /* Y */:
  21078. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  21079. break;
  21080. case 2 /* Z */:
  21081. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  21082. break;
  21083. }
  21084. var directionUpDown = this.reverseUpDown ? 1 : -1;
  21085. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  21086. switch (this._axisTargetedByUpAndDown) {
  21087. case 0 /* X */:
  21088. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  21089. break;
  21090. case 1 /* Y */:
  21091. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  21092. break;
  21093. case 2 /* Z */:
  21094. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  21095. break;
  21096. }
  21097. }
  21098. else {
  21099. if (this._touches.item(e.pointerId.toString())) {
  21100. this._touches.item(e.pointerId.toString()).x = e.clientX;
  21101. this._touches.item(e.pointerId.toString()).y = e.clientY;
  21102. }
  21103. }
  21104. };
  21105. VirtualJoystick.prototype._onPointerUp = function (e) {
  21106. this._clearCanvas();
  21107. if (this._joystickPointerID == e.pointerId) {
  21108. this._joystickPointerID = -1;
  21109. this.pressed = false;
  21110. }
  21111. this._deltaJoystickVector.x = 0;
  21112. this._deltaJoystickVector.y = 0;
  21113. this._touches.remove(e.pointerId.toString());
  21114. };
  21115. /**
  21116. * Change the color of the virtual joystick
  21117. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  21118. */
  21119. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  21120. this._joystickColor = newColor;
  21121. };
  21122. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  21123. this._action = action;
  21124. };
  21125. // Define which axis you'd like to control for left & right
  21126. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  21127. switch (axis) {
  21128. case 0 /* X */:
  21129. case 1 /* Y */:
  21130. case 2 /* Z */:
  21131. this._axisTargetedByLeftAndRight = axis;
  21132. break;
  21133. default:
  21134. this._axisTargetedByLeftAndRight = 0 /* X */;
  21135. break;
  21136. }
  21137. };
  21138. // Define which axis you'd like to control for up & down
  21139. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  21140. switch (axis) {
  21141. case 0 /* X */:
  21142. case 1 /* Y */:
  21143. case 2 /* Z */:
  21144. this._axisTargetedByUpAndDown = axis;
  21145. break;
  21146. default:
  21147. this._axisTargetedByUpAndDown = 1 /* Y */;
  21148. break;
  21149. }
  21150. };
  21151. VirtualJoystick.prototype._clearCanvas = function () {
  21152. if (this._leftJoystick) {
  21153. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  21154. }
  21155. else {
  21156. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  21157. }
  21158. };
  21159. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  21160. var _this = this;
  21161. if (this.pressed) {
  21162. this._clearCanvas();
  21163. this._touches.forEach(function (touch) {
  21164. if (touch.pointerId === _this._joystickPointerID) {
  21165. VirtualJoystick.vjCanvasContext.beginPath();
  21166. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21167. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21168. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  21169. VirtualJoystick.vjCanvasContext.stroke();
  21170. VirtualJoystick.vjCanvasContext.beginPath();
  21171. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21172. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  21173. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  21174. VirtualJoystick.vjCanvasContext.stroke();
  21175. VirtualJoystick.vjCanvasContext.beginPath();
  21176. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  21177. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  21178. VirtualJoystick.vjCanvasContext.stroke();
  21179. }
  21180. else {
  21181. VirtualJoystick.vjCanvasContext.beginPath();
  21182. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  21183. VirtualJoystick.vjCanvasContext.beginPath();
  21184. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  21185. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  21186. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  21187. VirtualJoystick.vjCanvasContext.stroke();
  21188. }
  21189. ;
  21190. });
  21191. }
  21192. requestAnimationFrame(function () {
  21193. _this._drawVirtualJoystick();
  21194. });
  21195. };
  21196. VirtualJoystick.prototype.releaseCanvas = function () {
  21197. if (VirtualJoystick.vjCanvas) {
  21198. document.body.removeChild(VirtualJoystick.vjCanvas);
  21199. VirtualJoystick.vjCanvas = null;
  21200. }
  21201. };
  21202. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  21203. VirtualJoystick._globalJoystickIndex = 0;
  21204. return VirtualJoystick;
  21205. })();
  21206. BABYLON.VirtualJoystick = VirtualJoystick;
  21207. })(BABYLON || (BABYLON = {}));
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. var VirtualJoystick;
  21211. (function (VirtualJoystick) {
  21212. var Collection = (function () {
  21213. function Collection() {
  21214. this._count = 0;
  21215. this._collection = new Array();
  21216. }
  21217. Collection.prototype.Count = function () {
  21218. return this._count;
  21219. };
  21220. Collection.prototype.add = function (key, item) {
  21221. if (this._collection[key] != undefined) {
  21222. return undefined;
  21223. }
  21224. this._collection[key] = item;
  21225. return ++this._count;
  21226. };
  21227. Collection.prototype.remove = function (key) {
  21228. if (this._collection[key] == undefined) {
  21229. return undefined;
  21230. }
  21231. delete this._collection[key];
  21232. return --this._count;
  21233. };
  21234. Collection.prototype.item = function (key) {
  21235. return this._collection[key];
  21236. };
  21237. Collection.prototype.forEach = function (block) {
  21238. var key;
  21239. for (key in this._collection) {
  21240. if (this._collection.hasOwnProperty(key)) {
  21241. block(this._collection[key]);
  21242. }
  21243. }
  21244. };
  21245. return Collection;
  21246. })();
  21247. VirtualJoystick.Collection = Collection;
  21248. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  21249. })(BABYLON || (BABYLON = {}));
  21250. //# sourceMappingURL=babylon.virtualJoystick.js.map
  21251. var BABYLON;
  21252. (function (BABYLON) {
  21253. var OculusRiftDevKit2013_Metric = {
  21254. HResolution: 1280,
  21255. VResolution: 800,
  21256. HScreenSize: 0.149759993,
  21257. VScreenSize: 0.0935999975,
  21258. VScreenCenter: 0.0467999987,
  21259. EyeToScreenDistance: 0.0410000011,
  21260. LensSeparationDistance: 0.0635000020,
  21261. InterpupillaryDistance: 0.0640000030,
  21262. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21263. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21264. PostProcessScaleFactor: 1.714605507808412,
  21265. LensCenterOffset: 0.151976421
  21266. };
  21267. var _OculusInnerCamera = (function (_super) {
  21268. __extends(_OculusInnerCamera, _super);
  21269. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  21270. _super.call(this, name, position, scene);
  21271. this._workMatrix = new BABYLON.Matrix();
  21272. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21273. // Constants
  21274. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21275. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21276. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21277. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21278. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21279. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21280. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21281. // Postprocess
  21282. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21283. }
  21284. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  21285. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21286. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21287. return this._projectionMatrix;
  21288. };
  21289. _OculusInnerCamera.prototype._getViewMatrix = function () {
  21290. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21291. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21292. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21293. // Computing target and final matrix
  21294. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21295. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21296. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21297. return this._viewMatrix;
  21298. };
  21299. return _OculusInnerCamera;
  21300. })(BABYLON.FreeCamera);
  21301. var OculusCamera = (function (_super) {
  21302. __extends(OculusCamera, _super);
  21303. function OculusCamera(name, position, scene) {
  21304. _super.call(this, name, position, scene);
  21305. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  21306. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  21307. this.subCameras.push(this._leftCamera);
  21308. this.subCameras.push(this._rightCamera);
  21309. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21310. }
  21311. OculusCamera.prototype._update = function () {
  21312. this._leftCamera.position.copyFrom(this.position);
  21313. this._rightCamera.position.copyFrom(this.position);
  21314. this._updateCamera(this._leftCamera);
  21315. this._updateCamera(this._rightCamera);
  21316. _super.prototype._update.call(this);
  21317. };
  21318. OculusCamera.prototype._updateCamera = function (camera) {
  21319. camera.minZ = this.minZ;
  21320. camera.maxZ = this.maxZ;
  21321. camera.rotation.x = this.rotation.x;
  21322. camera.rotation.y = this.rotation.y;
  21323. camera.rotation.z = this.rotation.z;
  21324. };
  21325. // Oculus events
  21326. OculusCamera.prototype._onOrientationEvent = function (evt) {
  21327. var yaw = evt.alpha / 180 * Math.PI;
  21328. var pitch = evt.beta / 180 * Math.PI;
  21329. var roll = evt.gamma / 180 * Math.PI;
  21330. if (!this._offsetOrientation) {
  21331. this._offsetOrientation = {
  21332. yaw: yaw,
  21333. pitch: pitch,
  21334. roll: roll
  21335. };
  21336. return;
  21337. }
  21338. else {
  21339. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21340. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21341. this.rotation.z += this._offsetOrientation.roll - roll;
  21342. this._offsetOrientation.yaw = yaw;
  21343. this._offsetOrientation.pitch = pitch;
  21344. this._offsetOrientation.roll = roll;
  21345. }
  21346. };
  21347. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  21348. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21349. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21350. };
  21351. OculusCamera.prototype.detachControl = function (element) {
  21352. _super.prototype.detachControl.call(this, element);
  21353. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21354. };
  21355. return OculusCamera;
  21356. })(BABYLON.FreeCamera);
  21357. BABYLON.OculusCamera = OculusCamera;
  21358. })(BABYLON || (BABYLON = {}));
  21359. //# sourceMappingURL=babylon.oculusCamera.js.map
  21360. var BABYLON;
  21361. (function (BABYLON) {
  21362. var OculusRiftDevKit2013_Metric = {
  21363. HResolution: 1280,
  21364. VResolution: 800,
  21365. HScreenSize: 0.149759993,
  21366. VScreenSize: 0.0935999975,
  21367. VScreenCenter: 0.0467999987,
  21368. EyeToScreenDistance: 0.0410000011,
  21369. LensSeparationDistance: 0.0635000020,
  21370. InterpupillaryDistance: 0.0640000030,
  21371. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21372. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21373. PostProcessScaleFactor: 1.714605507808412,
  21374. LensCenterOffset: 0.151976421
  21375. };
  21376. var _OculusInnerGamepadCamera = (function (_super) {
  21377. __extends(_OculusInnerGamepadCamera, _super);
  21378. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21379. _super.call(this, name, position, scene);
  21380. this._workMatrix = new BABYLON.Matrix();
  21381. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21382. // Constants
  21383. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21384. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21385. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21386. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21387. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21388. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21389. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21390. // Postprocess
  21391. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21392. }
  21393. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21394. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21395. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21396. return this._projectionMatrix;
  21397. };
  21398. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21399. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21400. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21401. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21402. // Computing target and final matrix
  21403. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21404. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21405. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21406. return this._viewMatrix;
  21407. };
  21408. return _OculusInnerGamepadCamera;
  21409. })(BABYLON.FreeCamera);
  21410. var OculusGamepadCamera = (function (_super) {
  21411. __extends(OculusGamepadCamera, _super);
  21412. function OculusGamepadCamera(name, position, scene) {
  21413. var _this = this;
  21414. _super.call(this, name, position, scene);
  21415. this.angularSensibility = 200;
  21416. this.moveSensibility = 75;
  21417. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21418. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21419. this.subCameras.push(this._leftCamera);
  21420. this.subCameras.push(this._rightCamera);
  21421. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21422. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21423. _this._onNewGameConnected(gamepad);
  21424. });
  21425. }
  21426. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21427. // Only the first gamepad can control the camera
  21428. if (gamepad.index === 0) {
  21429. this._gamepad = gamepad;
  21430. }
  21431. };
  21432. OculusGamepadCamera.prototype._update = function () {
  21433. this._leftCamera.position.copyFrom(this.position);
  21434. this._rightCamera.position.copyFrom(this.position);
  21435. this._updateCamera(this._leftCamera);
  21436. this._updateCamera(this._rightCamera);
  21437. _super.prototype._update.call(this);
  21438. };
  21439. OculusGamepadCamera.prototype._checkInputs = function () {
  21440. if (!this._gamepad) {
  21441. return;
  21442. }
  21443. var LSValues = this._gamepad.leftStick;
  21444. var normalizedLX = LSValues.x / this.moveSensibility;
  21445. var normalizedLY = LSValues.y / this.moveSensibility;
  21446. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21447. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21448. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21449. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21450. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21451. };
  21452. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21453. camera.minZ = this.minZ;
  21454. camera.maxZ = this.maxZ;
  21455. camera.rotation.x = this.rotation.x;
  21456. camera.rotation.y = this.rotation.y;
  21457. camera.rotation.z = this.rotation.z;
  21458. };
  21459. // Oculus events
  21460. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21461. var yaw = evt.alpha / 180 * Math.PI;
  21462. var pitch = evt.beta / 180 * Math.PI;
  21463. var roll = evt.gamma / 180 * Math.PI;
  21464. if (!this._offsetOrientation) {
  21465. this._offsetOrientation = {
  21466. yaw: yaw,
  21467. pitch: pitch,
  21468. roll: roll
  21469. };
  21470. return;
  21471. }
  21472. else {
  21473. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21474. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21475. this.rotation.z += this._offsetOrientation.roll - roll;
  21476. this._offsetOrientation.yaw = yaw;
  21477. this._offsetOrientation.pitch = pitch;
  21478. this._offsetOrientation.roll = roll;
  21479. }
  21480. };
  21481. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21482. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21483. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21484. };
  21485. OculusGamepadCamera.prototype.detachControl = function (element) {
  21486. _super.prototype.detachControl.call(this, element);
  21487. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21488. };
  21489. OculusGamepadCamera.prototype.dispose = function () {
  21490. this._gamepads.dispose();
  21491. _super.prototype.dispose.call(this);
  21492. };
  21493. return OculusGamepadCamera;
  21494. })(BABYLON.FreeCamera);
  21495. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21496. })(BABYLON || (BABYLON = {}));
  21497. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21498. var BABYLON;
  21499. (function (BABYLON) {
  21500. // We're mainly based on the logic defined into the FreeCamera code
  21501. var VirtualJoysticksCamera = (function (_super) {
  21502. __extends(VirtualJoysticksCamera, _super);
  21503. function VirtualJoysticksCamera(name, position, scene) {
  21504. _super.call(this, name, position, scene);
  21505. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21506. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21507. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21508. this._leftjoystick.setJoystickSensibility(0.15);
  21509. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21510. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21511. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21512. this._rightjoystick.reverseUpDown = true;
  21513. this._rightjoystick.setJoystickSensibility(0.05);
  21514. this._rightjoystick.setJoystickColor("yellow");
  21515. }
  21516. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21517. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21518. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21519. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21520. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21521. if (!this._leftjoystick.pressed) {
  21522. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21523. }
  21524. if (!this._rightjoystick.pressed) {
  21525. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21526. }
  21527. };
  21528. VirtualJoysticksCamera.prototype.dispose = function () {
  21529. this._leftjoystick.releaseCanvas();
  21530. _super.prototype.dispose.call(this);
  21531. };
  21532. return VirtualJoysticksCamera;
  21533. })(BABYLON.FreeCamera);
  21534. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21535. })(BABYLON || (BABYLON = {}));
  21536. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21537. var BABYLON;
  21538. (function (BABYLON) {
  21539. var ShaderMaterial = (function (_super) {
  21540. __extends(ShaderMaterial, _super);
  21541. function ShaderMaterial(name, scene, shaderPath, options) {
  21542. _super.call(this, name, scene);
  21543. this._textures = new Array();
  21544. this._floats = new Array();
  21545. this._floatsArrays = {};
  21546. this._colors3 = new Array();
  21547. this._colors4 = new Array();
  21548. this._vectors2 = new Array();
  21549. this._vectors3 = new Array();
  21550. this._matrices = new Array();
  21551. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21552. this._shaderPath = shaderPath;
  21553. options.needAlphaBlending = options.needAlphaBlending || false;
  21554. options.needAlphaTesting = options.needAlphaTesting || false;
  21555. options.attributes = options.attributes || ["position", "normal", "uv"];
  21556. options.uniforms = options.uniforms || ["worldViewProjection"];
  21557. options.samplers = options.samplers || [];
  21558. this._options = options;
  21559. }
  21560. ShaderMaterial.prototype.needAlphaBlending = function () {
  21561. return this._options.needAlphaBlending;
  21562. };
  21563. ShaderMaterial.prototype.needAlphaTesting = function () {
  21564. return this._options.needAlphaTesting;
  21565. };
  21566. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21567. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21568. this._options.uniforms.push(uniformName);
  21569. }
  21570. };
  21571. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21572. if (this._options.samplers.indexOf(name) === -1) {
  21573. this._options.samplers.push(name);
  21574. }
  21575. this._textures[name] = texture;
  21576. return this;
  21577. };
  21578. ShaderMaterial.prototype.setFloat = function (name, value) {
  21579. this._checkUniform(name);
  21580. this._floats[name] = value;
  21581. return this;
  21582. };
  21583. ShaderMaterial.prototype.setFloats = function (name, value) {
  21584. this._checkUniform(name);
  21585. this._floatsArrays[name] = value;
  21586. return this;
  21587. };
  21588. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21589. this._checkUniform(name);
  21590. this._colors3[name] = value;
  21591. return this;
  21592. };
  21593. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21594. this._checkUniform(name);
  21595. this._colors4[name] = value;
  21596. return this;
  21597. };
  21598. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21599. this._checkUniform(name);
  21600. this._vectors2[name] = value;
  21601. return this;
  21602. };
  21603. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21604. this._checkUniform(name);
  21605. this._vectors3[name] = value;
  21606. return this;
  21607. };
  21608. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21609. this._checkUniform(name);
  21610. this._matrices[name] = value;
  21611. return this;
  21612. };
  21613. ShaderMaterial.prototype.isReady = function () {
  21614. var scene = this.getScene();
  21615. var engine = scene.getEngine();
  21616. if (!this.checkReadyOnEveryCall) {
  21617. if (this._renderId === scene.getRenderId()) {
  21618. return true;
  21619. }
  21620. }
  21621. var previousEffect = this._effect;
  21622. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21623. if (!this._effect.isReady()) {
  21624. return false;
  21625. }
  21626. if (previousEffect !== this._effect) {
  21627. scene.resetCachedMaterial();
  21628. }
  21629. this._renderId = scene.getRenderId();
  21630. return true;
  21631. };
  21632. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21633. var scene = this.getScene();
  21634. if (this._options.uniforms.indexOf("world") !== -1) {
  21635. this._effect.setMatrix("world", world);
  21636. }
  21637. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21638. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21639. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21640. }
  21641. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21642. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21643. }
  21644. };
  21645. ShaderMaterial.prototype.bind = function (world) {
  21646. // Std values
  21647. this.bindOnlyWorldMatrix(world);
  21648. if (this.getScene().getCachedMaterial() !== this) {
  21649. if (this._options.uniforms.indexOf("view") !== -1) {
  21650. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21651. }
  21652. if (this._options.uniforms.indexOf("projection") !== -1) {
  21653. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21654. }
  21655. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21656. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21657. }
  21658. for (var name in this._textures) {
  21659. this._effect.setTexture(name, this._textures[name]);
  21660. }
  21661. for (name in this._floats) {
  21662. this._effect.setFloat(name, this._floats[name]);
  21663. }
  21664. for (name in this._floatsArrays) {
  21665. this._effect.setArray(name, this._floatsArrays[name]);
  21666. }
  21667. for (name in this._colors3) {
  21668. this._effect.setColor3(name, this._colors3[name]);
  21669. }
  21670. for (name in this._colors4) {
  21671. var color = this._colors4[name];
  21672. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21673. }
  21674. for (name in this._vectors2) {
  21675. this._effect.setVector2(name, this._vectors2[name]);
  21676. }
  21677. for (name in this._vectors3) {
  21678. this._effect.setVector3(name, this._vectors3[name]);
  21679. }
  21680. for (name in this._matrices) {
  21681. this._effect.setMatrix(name, this._matrices[name]);
  21682. }
  21683. }
  21684. _super.prototype.bind.call(this, world, null);
  21685. };
  21686. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21687. for (var name in this._textures) {
  21688. this._textures[name].dispose();
  21689. }
  21690. this._textures = [];
  21691. _super.prototype.dispose.call(this, forceDisposeEffect);
  21692. };
  21693. return ShaderMaterial;
  21694. })(BABYLON.Material);
  21695. BABYLON.ShaderMaterial = ShaderMaterial;
  21696. })(BABYLON || (BABYLON = {}));
  21697. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21698. (function (BABYLON) {
  21699. var VertexData = (function () {
  21700. function VertexData() {
  21701. }
  21702. VertexData.prototype.set = function (data, kind) {
  21703. switch (kind) {
  21704. case BABYLON.VertexBuffer.PositionKind:
  21705. this.positions = data;
  21706. break;
  21707. case BABYLON.VertexBuffer.NormalKind:
  21708. this.normals = data;
  21709. break;
  21710. case BABYLON.VertexBuffer.UVKind:
  21711. this.uvs = data;
  21712. break;
  21713. case BABYLON.VertexBuffer.UV2Kind:
  21714. this.uv2s = data;
  21715. break;
  21716. case BABYLON.VertexBuffer.ColorKind:
  21717. this.colors = data;
  21718. break;
  21719. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21720. this.matricesIndices = data;
  21721. break;
  21722. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21723. this.matricesWeights = data;
  21724. break;
  21725. }
  21726. };
  21727. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21728. this._applyTo(mesh, updatable);
  21729. };
  21730. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21731. this._applyTo(geometry, updatable);
  21732. };
  21733. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21734. this._update(mesh);
  21735. };
  21736. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21737. this._update(geometry);
  21738. };
  21739. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21740. if (this.positions) {
  21741. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21742. }
  21743. if (this.normals) {
  21744. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21745. }
  21746. if (this.uvs) {
  21747. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21748. }
  21749. if (this.uv2s) {
  21750. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21751. }
  21752. if (this.colors) {
  21753. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21754. }
  21755. if (this.matricesIndices) {
  21756. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21757. }
  21758. if (this.matricesWeights) {
  21759. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21760. }
  21761. if (this.indices) {
  21762. meshOrGeometry.setIndices(this.indices);
  21763. }
  21764. };
  21765. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21766. if (this.positions) {
  21767. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21768. }
  21769. if (this.normals) {
  21770. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21771. }
  21772. if (this.uvs) {
  21773. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21774. }
  21775. if (this.uv2s) {
  21776. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21777. }
  21778. if (this.colors) {
  21779. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21780. }
  21781. if (this.matricesIndices) {
  21782. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21783. }
  21784. if (this.matricesWeights) {
  21785. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21786. }
  21787. if (this.indices) {
  21788. meshOrGeometry.setIndices(this.indices);
  21789. }
  21790. };
  21791. VertexData.prototype.transform = function (matrix) {
  21792. var transformed = BABYLON.Vector3.Zero();
  21793. if (this.positions) {
  21794. var position = BABYLON.Vector3.Zero();
  21795. for (var index = 0; index < this.positions.length; index += 3) {
  21796. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21797. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21798. this.positions[index] = transformed.x;
  21799. this.positions[index + 1] = transformed.y;
  21800. this.positions[index + 2] = transformed.z;
  21801. }
  21802. }
  21803. if (this.normals) {
  21804. var normal = BABYLON.Vector3.Zero();
  21805. for (index = 0; index < this.normals.length; index += 3) {
  21806. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21807. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21808. this.normals[index] = transformed.x;
  21809. this.normals[index + 1] = transformed.y;
  21810. this.normals[index + 2] = transformed.z;
  21811. }
  21812. }
  21813. };
  21814. VertexData.prototype.merge = function (other) {
  21815. if (other.indices) {
  21816. if (!this.indices) {
  21817. this.indices = [];
  21818. }
  21819. var offset = this.positions ? this.positions.length / 3 : 0;
  21820. for (var index = 0; index < other.indices.length; index++) {
  21821. this.indices.push(other.indices[index] + offset);
  21822. }
  21823. }
  21824. if (other.positions) {
  21825. if (!this.positions) {
  21826. this.positions = [];
  21827. }
  21828. for (index = 0; index < other.positions.length; index++) {
  21829. this.positions.push(other.positions[index]);
  21830. }
  21831. }
  21832. if (other.normals) {
  21833. if (!this.normals) {
  21834. this.normals = [];
  21835. }
  21836. for (index = 0; index < other.normals.length; index++) {
  21837. this.normals.push(other.normals[index]);
  21838. }
  21839. }
  21840. if (other.uvs) {
  21841. if (!this.uvs) {
  21842. this.uvs = [];
  21843. }
  21844. for (index = 0; index < other.uvs.length; index++) {
  21845. this.uvs.push(other.uvs[index]);
  21846. }
  21847. }
  21848. if (other.uv2s) {
  21849. if (!this.uv2s) {
  21850. this.uv2s = [];
  21851. }
  21852. for (index = 0; index < other.uv2s.length; index++) {
  21853. this.uv2s.push(other.uv2s[index]);
  21854. }
  21855. }
  21856. if (other.matricesIndices) {
  21857. if (!this.matricesIndices) {
  21858. this.matricesIndices = [];
  21859. }
  21860. for (index = 0; index < other.matricesIndices.length; index++) {
  21861. this.matricesIndices.push(other.matricesIndices[index]);
  21862. }
  21863. }
  21864. if (other.matricesWeights) {
  21865. if (!this.matricesWeights) {
  21866. this.matricesWeights = [];
  21867. }
  21868. for (index = 0; index < other.matricesWeights.length; index++) {
  21869. this.matricesWeights.push(other.matricesWeights[index]);
  21870. }
  21871. }
  21872. if (other.colors) {
  21873. if (!this.colors) {
  21874. this.colors = [];
  21875. }
  21876. for (index = 0; index < other.colors.length; index++) {
  21877. this.colors.push(other.colors[index]);
  21878. }
  21879. }
  21880. };
  21881. // Statics
  21882. VertexData.ExtractFromMesh = function (mesh) {
  21883. return VertexData._ExtractFrom(mesh);
  21884. };
  21885. VertexData.ExtractFromGeometry = function (geometry) {
  21886. return VertexData._ExtractFrom(geometry);
  21887. };
  21888. VertexData._ExtractFrom = function (meshOrGeometry) {
  21889. var result = new VertexData();
  21890. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21891. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21892. }
  21893. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21894. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21895. }
  21896. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21897. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21898. }
  21899. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21900. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21901. }
  21902. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21903. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21904. }
  21905. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21906. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21907. }
  21908. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21909. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21910. }
  21911. result.indices = meshOrGeometry.getIndices();
  21912. return result;
  21913. };
  21914. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21915. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21916. closeArray = closeArray || false;
  21917. closePath = closePath || false;
  21918. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21919. offset = offset || defaultOffset;
  21920. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21921. var positions = [];
  21922. var indices = [];
  21923. var normals = [];
  21924. var uvs = [];
  21925. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21926. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21927. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21928. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21929. var minlg; // minimal length among all paths from pathArray
  21930. var lg = []; // array of path lengths : nb of vertex per path
  21931. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21932. var p; // path iterator
  21933. var i; // point iterator
  21934. var j; // point iterator
  21935. // if single path in pathArray
  21936. if (pathArray.length < 2) {
  21937. var ar1 = [];
  21938. var ar2 = [];
  21939. for (i = 0; i < pathArray[0].length - offset; i++) {
  21940. ar1.push(pathArray[0][i]);
  21941. ar2.push(pathArray[0][i + offset]);
  21942. }
  21943. pathArray = [ar1, ar2];
  21944. }
  21945. // positions and horizontal distances (u)
  21946. var idc = 0;
  21947. minlg = pathArray[0].length;
  21948. for (p = 0; p < pathArray.length; p++) {
  21949. uTotalDistance[p] = 0;
  21950. us[p] = [0];
  21951. var path = pathArray[p];
  21952. var l = path.length;
  21953. minlg = (minlg < l) ? minlg : l;
  21954. lg[p] = l;
  21955. idx[p] = idc;
  21956. j = 0;
  21957. while (j < l) {
  21958. positions.push(path[j].x, path[j].y, path[j].z);
  21959. if (j > 0) {
  21960. var vectlg = path[j].subtract(path[j - 1]).length();
  21961. var dist = vectlg + uTotalDistance[p];
  21962. us[p].push(dist);
  21963. uTotalDistance[p] = dist;
  21964. }
  21965. j++;
  21966. }
  21967. if (closePath) {
  21968. vectlg = path[0].subtract(path[j - 1]).length();
  21969. dist = vectlg + uTotalDistance[p];
  21970. uTotalDistance[p] = dist;
  21971. }
  21972. idc += l;
  21973. }
  21974. for (i = 0; i < minlg; i++) {
  21975. vTotalDistance[i] = 0;
  21976. vs[i] = [0];
  21977. var path1;
  21978. var path2;
  21979. for (p = 0; p < pathArray.length - 1; p++) {
  21980. path1 = pathArray[p];
  21981. path2 = pathArray[p + 1];
  21982. vectlg = path2[i].subtract(path1[i]).length();
  21983. dist = vectlg + vTotalDistance[i];
  21984. vs[i].push(dist);
  21985. vTotalDistance[i] = dist;
  21986. }
  21987. if (closeArray) {
  21988. path1 = pathArray[p];
  21989. path2 = pathArray[0];
  21990. vectlg = path2[i].subtract(path1[i]).length();
  21991. dist = vectlg + vTotalDistance[i];
  21992. vTotalDistance[i] = dist;
  21993. }
  21994. }
  21995. // uvs
  21996. var u;
  21997. var v;
  21998. for (p = 0; p < pathArray.length; p++) {
  21999. for (i = 0; i < minlg; i++) {
  22000. u = us[p][i] / uTotalDistance[p];
  22001. v = vs[i][p] / vTotalDistance[i];
  22002. uvs.push(u, v);
  22003. }
  22004. }
  22005. // indices
  22006. p = 0; // path index
  22007. var pi = 0; // positions array index
  22008. var l1 = lg[p] - 1; // path1 length
  22009. var l2 = lg[p + 1] - 1; // path2 length
  22010. var min = (l1 < l2) ? l1 : l2; // current path stop index
  22011. var shft = idx[1] - idx[0]; // shift
  22012. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  22013. var t1; // two consecutive triangles, so 4 points : point1
  22014. var t2; // point2
  22015. var t3; // point3
  22016. var t4; // point4
  22017. while (pi <= min && p < path1nb) {
  22018. // 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
  22019. t1 = pi;
  22020. t2 = pi + shft;
  22021. t3 = pi + 1;
  22022. t4 = pi + shft + 1;
  22023. indices.push(pi, pi + shft, pi + 1);
  22024. indices.push(pi + shft + 1, pi + 1, pi + shft);
  22025. pi += 1;
  22026. if (pi === min) {
  22027. if (closePath) {
  22028. indices.push(pi, pi + shft, idx[p]);
  22029. indices.push(idx[p] + shft, idx[p], pi + shft);
  22030. t3 = idx[p];
  22031. t4 = idx[p] + shft;
  22032. }
  22033. p++;
  22034. if (p === lg.length - 1) {
  22035. shft = idx[0] - idx[p];
  22036. l1 = lg[p] - 1;
  22037. l2 = lg[0] - 1;
  22038. }
  22039. else {
  22040. shft = idx[p + 1] - idx[p];
  22041. l1 = lg[p] - 1;
  22042. l2 = lg[p + 1] - 1;
  22043. }
  22044. pi = idx[p];
  22045. min = (l1 < l2) ? l1 + pi : l2 + pi;
  22046. }
  22047. }
  22048. // normals
  22049. VertexData.ComputeNormals(positions, indices, normals);
  22050. // sides
  22051. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22052. // Result
  22053. var vertexData = new VertexData();
  22054. vertexData.indices = indices;
  22055. vertexData.positions = positions;
  22056. vertexData.normals = normals;
  22057. vertexData.uvs = uvs;
  22058. return vertexData;
  22059. };
  22060. VertexData.CreateBox = function (size, sideOrientation) {
  22061. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22062. var normalsSource = [
  22063. new BABYLON.Vector3(0, 0, 1),
  22064. new BABYLON.Vector3(0, 0, -1),
  22065. new BABYLON.Vector3(1, 0, 0),
  22066. new BABYLON.Vector3(-1, 0, 0),
  22067. new BABYLON.Vector3(0, 1, 0),
  22068. new BABYLON.Vector3(0, -1, 0)
  22069. ];
  22070. var indices = [];
  22071. var positions = [];
  22072. var normals = [];
  22073. var uvs = [];
  22074. size = size || 1;
  22075. for (var index = 0; index < normalsSource.length; index++) {
  22076. var normal = normalsSource[index];
  22077. // Get two vectors perpendicular to the face normal and to each other.
  22078. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  22079. var side2 = BABYLON.Vector3.Cross(normal, side1);
  22080. // Six indices (two triangles) per face.
  22081. var verticesLength = positions.length / 3;
  22082. indices.push(verticesLength);
  22083. indices.push(verticesLength + 1);
  22084. indices.push(verticesLength + 2);
  22085. indices.push(verticesLength);
  22086. indices.push(verticesLength + 2);
  22087. indices.push(verticesLength + 3);
  22088. // Four vertices per face.
  22089. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  22090. positions.push(vertex.x, vertex.y, vertex.z);
  22091. normals.push(normal.x, normal.y, normal.z);
  22092. uvs.push(1.0, 1.0);
  22093. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  22094. positions.push(vertex.x, vertex.y, vertex.z);
  22095. normals.push(normal.x, normal.y, normal.z);
  22096. uvs.push(0.0, 1.0);
  22097. vertex = normal.add(side1).add(side2).scale(size / 2);
  22098. positions.push(vertex.x, vertex.y, vertex.z);
  22099. normals.push(normal.x, normal.y, normal.z);
  22100. uvs.push(0.0, 0.0);
  22101. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  22102. positions.push(vertex.x, vertex.y, vertex.z);
  22103. normals.push(normal.x, normal.y, normal.z);
  22104. uvs.push(1.0, 0.0);
  22105. }
  22106. // sides
  22107. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22108. // Result
  22109. var vertexData = new VertexData();
  22110. vertexData.indices = indices;
  22111. vertexData.positions = positions;
  22112. vertexData.normals = normals;
  22113. vertexData.uvs = uvs;
  22114. return vertexData;
  22115. };
  22116. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  22117. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22118. segments = segments || 32;
  22119. diameter = diameter || 1;
  22120. var radius = diameter / 2;
  22121. var totalZRotationSteps = 2 + segments;
  22122. var totalYRotationSteps = 2 * totalZRotationSteps;
  22123. var indices = [];
  22124. var positions = [];
  22125. var normals = [];
  22126. var uvs = [];
  22127. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  22128. var normalizedZ = zRotationStep / totalZRotationSteps;
  22129. var angleZ = (normalizedZ * Math.PI);
  22130. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  22131. var normalizedY = yRotationStep / totalYRotationSteps;
  22132. var angleY = normalizedY * Math.PI * 2;
  22133. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  22134. var rotationY = BABYLON.Matrix.RotationY(angleY);
  22135. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  22136. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  22137. var vertex = complete.scale(radius);
  22138. var normal = BABYLON.Vector3.Normalize(vertex);
  22139. positions.push(vertex.x, vertex.y, vertex.z);
  22140. normals.push(normal.x, normal.y, normal.z);
  22141. uvs.push(normalizedZ, normalizedY);
  22142. }
  22143. if (zRotationStep > 0) {
  22144. var verticesCount = positions.length / 3;
  22145. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  22146. indices.push((firstIndex));
  22147. indices.push((firstIndex + 1));
  22148. indices.push(firstIndex + totalYRotationSteps + 1);
  22149. indices.push((firstIndex + totalYRotationSteps + 1));
  22150. indices.push((firstIndex + 1));
  22151. indices.push((firstIndex + totalYRotationSteps + 2));
  22152. }
  22153. }
  22154. }
  22155. // Sides
  22156. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22157. // Result
  22158. var vertexData = new VertexData();
  22159. vertexData.indices = indices;
  22160. vertexData.positions = positions;
  22161. vertexData.normals = normals;
  22162. vertexData.uvs = uvs;
  22163. return vertexData;
  22164. };
  22165. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  22166. if (subdivisions === void 0) { subdivisions = 1; }
  22167. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22168. var radiusTop = diameterTop / 2;
  22169. var radiusBottom = diameterBottom / 2;
  22170. var indices = [];
  22171. var positions = [];
  22172. var normals = [];
  22173. var uvs = [];
  22174. height = height || 1;
  22175. diameterTop = diameterTop || 0.5;
  22176. diameterBottom = diameterBottom || 1;
  22177. tessellation = tessellation || 16;
  22178. subdivisions = subdivisions || 1;
  22179. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  22180. var getCircleVector = function (i) {
  22181. var angle = (i * 2.0 * Math.PI / tessellation);
  22182. var dx = Math.cos(angle);
  22183. var dz = Math.sin(angle);
  22184. return new BABYLON.Vector3(dx, 0, dz);
  22185. };
  22186. var createCylinderCap = function (isTop) {
  22187. var radius = isTop ? radiusTop : radiusBottom;
  22188. if (radius === 0) {
  22189. return;
  22190. }
  22191. var vbase = positions.length / 3;
  22192. var offset = new BABYLON.Vector3(0, height / 2, 0);
  22193. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  22194. if (!isTop) {
  22195. offset.scaleInPlace(-1);
  22196. textureScale.x = -textureScale.x;
  22197. }
  22198. for (var i = 0; i < tessellation; i++) {
  22199. var circleVector = getCircleVector(i);
  22200. var position = circleVector.scale(radius).add(offset);
  22201. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  22202. positions.push(position.x, position.y, position.z);
  22203. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22204. }
  22205. for (i = 0; i < tessellation - 2; i++) {
  22206. if (!isTop) {
  22207. indices.push(vbase);
  22208. indices.push(vbase + (i + 2) % tessellation);
  22209. indices.push(vbase + (i + 1) % tessellation);
  22210. }
  22211. else {
  22212. indices.push(vbase);
  22213. indices.push(vbase + (i + 1) % tessellation);
  22214. indices.push(vbase + (i + 2) % tessellation);
  22215. }
  22216. }
  22217. };
  22218. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  22219. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  22220. var stride = tessellation + 1;
  22221. for (var i = 0; i <= tessellation; i++) {
  22222. var circleVector = getCircleVector(i);
  22223. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  22224. var position, radius = radiusBottom;
  22225. for (var s = 0; s <= subdivisions; s++) {
  22226. // Update variables
  22227. position = circleVector.scale(radius);
  22228. position.addInPlace(base.add(offset.scale(s)));
  22229. textureCoordinate.y += 1 / subdivisions;
  22230. radius += (radiusTop - radiusBottom) / subdivisions;
  22231. // Push in arrays
  22232. positions.push(position.x, position.y, position.z);
  22233. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22234. }
  22235. }
  22236. subdivisions += 1;
  22237. for (s = 0; s < subdivisions - 1; s++) {
  22238. for (i = 0; i <= tessellation; i++) {
  22239. indices.push(i * subdivisions + s);
  22240. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22241. indices.push(i * subdivisions + (s + 1));
  22242. indices.push(i * subdivisions + (s + 1));
  22243. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  22244. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  22245. }
  22246. }
  22247. // Create flat triangle fan caps to seal the top and bottom.
  22248. createCylinderCap(true);
  22249. createCylinderCap(false);
  22250. // Normals
  22251. VertexData.ComputeNormals(positions, indices, normals);
  22252. // Sides
  22253. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22254. // Result
  22255. var vertexData = new VertexData();
  22256. vertexData.indices = indices;
  22257. vertexData.positions = positions;
  22258. vertexData.normals = normals;
  22259. vertexData.uvs = uvs;
  22260. return vertexData;
  22261. };
  22262. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  22263. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22264. var indices = [];
  22265. var positions = [];
  22266. var normals = [];
  22267. var uvs = [];
  22268. diameter = diameter || 1;
  22269. thickness = thickness || 0.5;
  22270. tessellation = tessellation || 16;
  22271. var stride = tessellation + 1;
  22272. for (var i = 0; i <= tessellation; i++) {
  22273. var u = i / tessellation;
  22274. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  22275. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  22276. for (var j = 0; j <= tessellation; j++) {
  22277. var v = 1 - j / tessellation;
  22278. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  22279. var dx = Math.cos(innerAngle);
  22280. var dy = Math.sin(innerAngle);
  22281. // Create a vertex.
  22282. var normal = new BABYLON.Vector3(dx, dy, 0);
  22283. var position = normal.scale(thickness / 2);
  22284. var textureCoordinate = new BABYLON.Vector2(u, v);
  22285. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  22286. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  22287. positions.push(position.x, position.y, position.z);
  22288. normals.push(normal.x, normal.y, normal.z);
  22289. uvs.push(textureCoordinate.x, textureCoordinate.y);
  22290. // And create indices for two triangles.
  22291. var nextI = (i + 1) % stride;
  22292. var nextJ = (j + 1) % stride;
  22293. indices.push(i * stride + j);
  22294. indices.push(i * stride + nextJ);
  22295. indices.push(nextI * stride + j);
  22296. indices.push(i * stride + nextJ);
  22297. indices.push(nextI * stride + nextJ);
  22298. indices.push(nextI * stride + j);
  22299. }
  22300. }
  22301. // Sides
  22302. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22303. // Result
  22304. var vertexData = new VertexData();
  22305. vertexData.indices = indices;
  22306. vertexData.positions = positions;
  22307. vertexData.normals = normals;
  22308. vertexData.uvs = uvs;
  22309. return vertexData;
  22310. };
  22311. VertexData.CreateLines = function (points) {
  22312. var indices = [];
  22313. var positions = [];
  22314. for (var index = 0; index < points.length; index++) {
  22315. positions.push(points[index].x, points[index].y, points[index].z);
  22316. if (index > 0) {
  22317. indices.push(index - 1);
  22318. indices.push(index);
  22319. }
  22320. }
  22321. // Result
  22322. var vertexData = new VertexData();
  22323. vertexData.indices = indices;
  22324. vertexData.positions = positions;
  22325. return vertexData;
  22326. };
  22327. VertexData.CreateGround = function (width, height, subdivisions) {
  22328. var indices = [];
  22329. var positions = [];
  22330. var normals = [];
  22331. var uvs = [];
  22332. var row, col;
  22333. width = width || 1;
  22334. height = height || 1;
  22335. subdivisions = subdivisions || 1;
  22336. for (row = 0; row <= subdivisions; row++) {
  22337. for (col = 0; col <= subdivisions; col++) {
  22338. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22339. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22340. positions.push(position.x, position.y, position.z);
  22341. normals.push(normal.x, normal.y, normal.z);
  22342. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22343. }
  22344. }
  22345. for (row = 0; row < subdivisions; row++) {
  22346. for (col = 0; col < subdivisions; col++) {
  22347. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22348. indices.push(col + 1 + row * (subdivisions + 1));
  22349. indices.push(col + row * (subdivisions + 1));
  22350. indices.push(col + (row + 1) * (subdivisions + 1));
  22351. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22352. indices.push(col + row * (subdivisions + 1));
  22353. }
  22354. }
  22355. // Result
  22356. var vertexData = new VertexData();
  22357. vertexData.indices = indices;
  22358. vertexData.positions = positions;
  22359. vertexData.normals = normals;
  22360. vertexData.uvs = uvs;
  22361. return vertexData;
  22362. };
  22363. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22364. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22365. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22366. var indices = [];
  22367. var positions = [];
  22368. var normals = [];
  22369. var uvs = [];
  22370. var row, col, tileRow, tileCol;
  22371. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22372. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22373. precision.w = (precision.w < 1) ? 1 : precision.w;
  22374. precision.h = (precision.h < 1) ? 1 : precision.h;
  22375. var tileSize = {
  22376. 'w': (xmax - xmin) / subdivisions.w,
  22377. 'h': (zmax - zmin) / subdivisions.h
  22378. };
  22379. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22380. // Indices
  22381. var base = positions.length / 3;
  22382. var rowLength = precision.w + 1;
  22383. for (row = 0; row < precision.h; row++) {
  22384. for (col = 0; col < precision.w; col++) {
  22385. var square = [
  22386. base + col + row * rowLength,
  22387. base + (col + 1) + row * rowLength,
  22388. base + (col + 1) + (row + 1) * rowLength,
  22389. base + col + (row + 1) * rowLength
  22390. ];
  22391. indices.push(square[1]);
  22392. indices.push(square[2]);
  22393. indices.push(square[3]);
  22394. indices.push(square[0]);
  22395. indices.push(square[1]);
  22396. indices.push(square[3]);
  22397. }
  22398. }
  22399. // Position, normals and uvs
  22400. var position = BABYLON.Vector3.Zero();
  22401. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22402. for (row = 0; row <= precision.h; row++) {
  22403. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22404. for (col = 0; col <= precision.w; col++) {
  22405. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22406. position.y = 0;
  22407. positions.push(position.x, position.y, position.z);
  22408. normals.push(normal.x, normal.y, normal.z);
  22409. uvs.push(col / precision.w, row / precision.h);
  22410. }
  22411. }
  22412. }
  22413. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22414. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22415. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22416. }
  22417. }
  22418. // Result
  22419. var vertexData = new VertexData();
  22420. vertexData.indices = indices;
  22421. vertexData.positions = positions;
  22422. vertexData.normals = normals;
  22423. vertexData.uvs = uvs;
  22424. return vertexData;
  22425. };
  22426. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22427. var indices = [];
  22428. var positions = [];
  22429. var normals = [];
  22430. var uvs = [];
  22431. var row, col;
  22432. for (row = 0; row <= subdivisions; row++) {
  22433. for (col = 0; col <= subdivisions; col++) {
  22434. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22435. // Compute height
  22436. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22437. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22438. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22439. var r = buffer[pos] / 255.0;
  22440. var g = buffer[pos + 1] / 255.0;
  22441. var b = buffer[pos + 2] / 255.0;
  22442. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22443. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22444. // Add vertex
  22445. positions.push(position.x, position.y, position.z);
  22446. normals.push(0, 0, 0);
  22447. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22448. }
  22449. }
  22450. for (row = 0; row < subdivisions; row++) {
  22451. for (col = 0; col < subdivisions; col++) {
  22452. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22453. indices.push(col + 1 + row * (subdivisions + 1));
  22454. indices.push(col + row * (subdivisions + 1));
  22455. indices.push(col + (row + 1) * (subdivisions + 1));
  22456. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22457. indices.push(col + row * (subdivisions + 1));
  22458. }
  22459. }
  22460. // Normals
  22461. VertexData.ComputeNormals(positions, indices, normals);
  22462. // Result
  22463. var vertexData = new VertexData();
  22464. vertexData.indices = indices;
  22465. vertexData.positions = positions;
  22466. vertexData.normals = normals;
  22467. vertexData.uvs = uvs;
  22468. return vertexData;
  22469. };
  22470. VertexData.CreatePlane = function (size, sideOrientation) {
  22471. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22472. var indices = [];
  22473. var positions = [];
  22474. var normals = [];
  22475. var uvs = [];
  22476. size = size || 1;
  22477. // Vertices
  22478. var halfSize = size / 2.0;
  22479. positions.push(-halfSize, -halfSize, 0);
  22480. normals.push(0, 0, -1.0);
  22481. uvs.push(0.0, 0.0);
  22482. positions.push(halfSize, -halfSize, 0);
  22483. normals.push(0, 0, -1.0);
  22484. uvs.push(1.0, 0.0);
  22485. positions.push(halfSize, halfSize, 0);
  22486. normals.push(0, 0, -1.0);
  22487. uvs.push(1.0, 1.0);
  22488. positions.push(-halfSize, halfSize, 0);
  22489. normals.push(0, 0, -1.0);
  22490. uvs.push(0.0, 1.0);
  22491. // Indices
  22492. indices.push(0);
  22493. indices.push(1);
  22494. indices.push(2);
  22495. indices.push(0);
  22496. indices.push(2);
  22497. indices.push(3);
  22498. // Sides
  22499. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22500. // Result
  22501. var vertexData = new VertexData();
  22502. vertexData.indices = indices;
  22503. vertexData.positions = positions;
  22504. vertexData.normals = normals;
  22505. vertexData.uvs = uvs;
  22506. return vertexData;
  22507. };
  22508. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22509. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22510. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22511. var indices = [];
  22512. var positions = [];
  22513. var normals = [];
  22514. var uvs = [];
  22515. radius = radius || 2;
  22516. tube = tube || 0.5;
  22517. radialSegments = radialSegments || 32;
  22518. tubularSegments = tubularSegments || 32;
  22519. p = p || 2;
  22520. q = q || 3;
  22521. // Helper
  22522. var getPos = function (angle) {
  22523. var cu = Math.cos(angle);
  22524. var su = Math.sin(angle);
  22525. var quOverP = q / p * angle;
  22526. var cs = Math.cos(quOverP);
  22527. var tx = radius * (2 + cs) * 0.5 * cu;
  22528. var ty = radius * (2 + cs) * su * 0.5;
  22529. var tz = radius * Math.sin(quOverP) * 0.5;
  22530. return new BABYLON.Vector3(tx, ty, tz);
  22531. };
  22532. for (var i = 0; i <= radialSegments; i++) {
  22533. var modI = i % radialSegments;
  22534. var u = modI / radialSegments * 2 * p * Math.PI;
  22535. var p1 = getPos(u);
  22536. var p2 = getPos(u + 0.01);
  22537. var tang = p2.subtract(p1);
  22538. var n = p2.add(p1);
  22539. var bitan = BABYLON.Vector3.Cross(tang, n);
  22540. n = BABYLON.Vector3.Cross(bitan, tang);
  22541. bitan.normalize();
  22542. n.normalize();
  22543. for (var j = 0; j < tubularSegments; j++) {
  22544. var modJ = j % tubularSegments;
  22545. var v = modJ / tubularSegments * 2 * Math.PI;
  22546. var cx = -tube * Math.cos(v);
  22547. var cy = tube * Math.sin(v);
  22548. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22549. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22550. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22551. uvs.push(i / radialSegments);
  22552. uvs.push(j / tubularSegments);
  22553. }
  22554. }
  22555. for (i = 0; i < radialSegments; i++) {
  22556. for (j = 0; j < tubularSegments; j++) {
  22557. var jNext = (j + 1) % tubularSegments;
  22558. var a = i * tubularSegments + j;
  22559. var b = (i + 1) * tubularSegments + j;
  22560. var c = (i + 1) * tubularSegments + jNext;
  22561. var d = i * tubularSegments + jNext;
  22562. indices.push(d);
  22563. indices.push(b);
  22564. indices.push(a);
  22565. indices.push(d);
  22566. indices.push(c);
  22567. indices.push(b);
  22568. }
  22569. }
  22570. // Normals
  22571. VertexData.ComputeNormals(positions, indices, normals);
  22572. // Sides
  22573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22574. // Result
  22575. var vertexData = new VertexData();
  22576. vertexData.indices = indices;
  22577. vertexData.positions = positions;
  22578. vertexData.normals = normals;
  22579. vertexData.uvs = uvs;
  22580. return vertexData;
  22581. };
  22582. // Tools
  22583. VertexData.ComputeNormals = function (positions, indices, normals) {
  22584. var positionVectors = [];
  22585. var facesOfVertices = [];
  22586. var index;
  22587. for (index = 0; index < positions.length; index += 3) {
  22588. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22589. positionVectors.push(vector3);
  22590. facesOfVertices.push([]);
  22591. }
  22592. // Compute normals
  22593. var facesNormals = [];
  22594. for (index = 0; index < indices.length / 3; index++) {
  22595. var i1 = indices[index * 3];
  22596. var i2 = indices[index * 3 + 1];
  22597. var i3 = indices[index * 3 + 2];
  22598. var p1 = positionVectors[i1];
  22599. var p2 = positionVectors[i2];
  22600. var p3 = positionVectors[i3];
  22601. var p1p2 = p1.subtract(p2);
  22602. var p3p2 = p3.subtract(p2);
  22603. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22604. facesOfVertices[i1].push(index);
  22605. facesOfVertices[i2].push(index);
  22606. facesOfVertices[i3].push(index);
  22607. }
  22608. for (index = 0; index < positionVectors.length; index++) {
  22609. var faces = facesOfVertices[index];
  22610. var normal = BABYLON.Vector3.Zero();
  22611. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22612. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22613. }
  22614. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22615. normals[index * 3] = normal.x;
  22616. normals[index * 3 + 1] = normal.y;
  22617. normals[index * 3 + 2] = normal.z;
  22618. }
  22619. };
  22620. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22621. var li = indices.length;
  22622. var ln = normals.length;
  22623. var i;
  22624. var n;
  22625. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22626. switch (sideOrientation) {
  22627. case BABYLON.Mesh.FRONTSIDE:
  22628. break;
  22629. case BABYLON.Mesh.BACKSIDE:
  22630. var tmp;
  22631. for (i = 0; i < li; i += 3) {
  22632. tmp = indices[i];
  22633. indices[i] = indices[i + 2];
  22634. indices[i + 2] = tmp;
  22635. }
  22636. for (n = 0; n < ln; n++) {
  22637. normals[n] = -normals[n];
  22638. }
  22639. break;
  22640. case BABYLON.Mesh.DOUBLESIDE:
  22641. // positions
  22642. var lp = positions.length;
  22643. var l = lp / 3;
  22644. for (var p = 0; p < lp; p++) {
  22645. positions[lp + p] = positions[p];
  22646. }
  22647. for (i = 0; i < li; i += 3) {
  22648. indices[i + li] = indices[i + 2] + l;
  22649. indices[i + 1 + li] = indices[i + 1] + l;
  22650. indices[i + 2 + li] = indices[i] + l;
  22651. }
  22652. for (n = 0; n < ln; n++) {
  22653. normals[ln + n] = -normals[n];
  22654. }
  22655. // uvs
  22656. var lu = uvs.length;
  22657. for (var u = 0; u < lu; u++) {
  22658. uvs[u + lu] = uvs[u];
  22659. }
  22660. break;
  22661. }
  22662. };
  22663. return VertexData;
  22664. })();
  22665. BABYLON.VertexData = VertexData;
  22666. })(BABYLON || (BABYLON = {}));
  22667. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22668. var BABYLON;
  22669. (function (BABYLON) {
  22670. var buildCamera = function (that, name) {
  22671. that._leftCamera.isIntermediate = true;
  22672. that.subCameras.push(that._leftCamera);
  22673. that.subCameras.push(that._rightCamera);
  22674. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22675. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22676. that._anaglyphPostProcess.onApply = function (effect) {
  22677. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22678. };
  22679. that._update();
  22680. };
  22681. var AnaglyphArcRotateCamera = (function (_super) {
  22682. __extends(AnaglyphArcRotateCamera, _super);
  22683. // ANY
  22684. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22685. _super.call(this, name, alpha, beta, radius, target, scene);
  22686. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22687. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22688. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22689. buildCamera(this, name);
  22690. }
  22691. AnaglyphArcRotateCamera.prototype._update = function () {
  22692. this._updateCamera(this._leftCamera);
  22693. this._updateCamera(this._rightCamera);
  22694. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22695. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22696. _super.prototype._update.call(this);
  22697. };
  22698. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22699. camera.beta = this.beta;
  22700. camera.radius = this.radius;
  22701. camera.minZ = this.minZ;
  22702. camera.maxZ = this.maxZ;
  22703. camera.fov = this.fov;
  22704. camera.target = this.target;
  22705. };
  22706. return AnaglyphArcRotateCamera;
  22707. })(BABYLON.ArcRotateCamera);
  22708. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22709. var AnaglyphFreeCamera = (function (_super) {
  22710. __extends(AnaglyphFreeCamera, _super);
  22711. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22712. _super.call(this, name, position, scene);
  22713. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22714. this._transformMatrix = new BABYLON.Matrix();
  22715. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22716. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22717. buildCamera(this, name);
  22718. }
  22719. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22720. var target = this.getTarget();
  22721. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22722. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22723. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22724. };
  22725. AnaglyphFreeCamera.prototype._update = function () {
  22726. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22727. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22728. this._updateCamera(this._leftCamera);
  22729. this._updateCamera(this._rightCamera);
  22730. _super.prototype._update.call(this);
  22731. };
  22732. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22733. camera.minZ = this.minZ;
  22734. camera.maxZ = this.maxZ;
  22735. camera.fov = this.fov;
  22736. camera.viewport = this.viewport;
  22737. camera.setTarget(this.getTarget());
  22738. };
  22739. return AnaglyphFreeCamera;
  22740. })(BABYLON.FreeCamera);
  22741. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22742. })(BABYLON || (BABYLON = {}));
  22743. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22744. var BABYLON;
  22745. (function (BABYLON) {
  22746. var AnaglyphPostProcess = (function (_super) {
  22747. __extends(AnaglyphPostProcess, _super);
  22748. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22749. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22750. }
  22751. return AnaglyphPostProcess;
  22752. })(BABYLON.PostProcess);
  22753. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22754. })(BABYLON || (BABYLON = {}));
  22755. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22756. (function (BABYLON) {
  22757. var Tags = (function () {
  22758. function Tags() {
  22759. }
  22760. Tags.EnableFor = function (obj) {
  22761. obj._tags = obj._tags || {};
  22762. obj.hasTags = function () {
  22763. return Tags.HasTags(obj);
  22764. };
  22765. obj.addTags = function (tagsString) {
  22766. return Tags.AddTagsTo(obj, tagsString);
  22767. };
  22768. obj.removeTags = function (tagsString) {
  22769. return Tags.RemoveTagsFrom(obj, tagsString);
  22770. };
  22771. obj.matchesTagsQuery = function (tagsQuery) {
  22772. return Tags.MatchesQuery(obj, tagsQuery);
  22773. };
  22774. };
  22775. Tags.DisableFor = function (obj) {
  22776. delete obj._tags;
  22777. delete obj.hasTags;
  22778. delete obj.addTags;
  22779. delete obj.removeTags;
  22780. delete obj.matchesTagsQuery;
  22781. };
  22782. Tags.HasTags = function (obj) {
  22783. if (!obj._tags) {
  22784. return false;
  22785. }
  22786. return !BABYLON.Tools.IsEmpty(obj._tags);
  22787. };
  22788. Tags.GetTags = function (obj) {
  22789. if (!obj._tags) {
  22790. return null;
  22791. }
  22792. return obj._tags;
  22793. };
  22794. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22795. // a tag cannot start with '||', '&&', and '!'
  22796. // it cannot contain whitespaces
  22797. Tags.AddTagsTo = function (obj, tagsString) {
  22798. if (!tagsString) {
  22799. return;
  22800. }
  22801. var tags = tagsString.split(" ");
  22802. for (var t in tags) {
  22803. Tags._AddTagTo(obj, tags[t]);
  22804. }
  22805. };
  22806. Tags._AddTagTo = function (obj, tag) {
  22807. tag = tag.trim();
  22808. if (tag === "" || tag === "true" || tag === "false") {
  22809. return;
  22810. }
  22811. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22812. return;
  22813. }
  22814. Tags.EnableFor(obj);
  22815. obj._tags[tag] = true;
  22816. };
  22817. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22818. if (!Tags.HasTags(obj)) {
  22819. return;
  22820. }
  22821. var tags = tagsString.split(" ");
  22822. for (var t in tags) {
  22823. Tags._RemoveTagFrom(obj, tags[t]);
  22824. }
  22825. };
  22826. Tags._RemoveTagFrom = function (obj, tag) {
  22827. delete obj._tags[tag];
  22828. };
  22829. Tags.MatchesQuery = function (obj, tagsQuery) {
  22830. if (tagsQuery === undefined) {
  22831. return true;
  22832. }
  22833. if (tagsQuery === "") {
  22834. return Tags.HasTags(obj);
  22835. }
  22836. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22837. };
  22838. return Tags;
  22839. })();
  22840. BABYLON.Tags = Tags;
  22841. })(BABYLON || (BABYLON = {}));
  22842. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22843. (function (BABYLON) {
  22844. var Internals;
  22845. (function (Internals) {
  22846. var AndOrNotEvaluator = (function () {
  22847. function AndOrNotEvaluator() {
  22848. }
  22849. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22850. if (!query.match(/\([^\(\)]*\)/g)) {
  22851. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22852. }
  22853. else {
  22854. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22855. // remove parenthesis
  22856. r = r.slice(1, r.length - 1);
  22857. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22858. });
  22859. }
  22860. if (query === "true") {
  22861. return true;
  22862. }
  22863. if (query === "false") {
  22864. return false;
  22865. }
  22866. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22867. };
  22868. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22869. evaluateCallback = evaluateCallback || (function (r) {
  22870. return r === "true" ? true : false;
  22871. });
  22872. var result;
  22873. var or = parenthesisContent.split("||");
  22874. for (var i in or) {
  22875. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22876. var and = ori.split("&&");
  22877. if (and.length > 1) {
  22878. for (var j = 0; j < and.length; ++j) {
  22879. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22880. if (andj !== "true" && andj !== "false") {
  22881. if (andj[0] === "!") {
  22882. result = !evaluateCallback(andj.substring(1));
  22883. }
  22884. else {
  22885. result = evaluateCallback(andj);
  22886. }
  22887. }
  22888. else {
  22889. result = andj === "true" ? true : false;
  22890. }
  22891. if (!result) {
  22892. ori = "false";
  22893. break;
  22894. }
  22895. }
  22896. }
  22897. if (result || ori === "true") {
  22898. result = true;
  22899. break;
  22900. }
  22901. // result equals false (or undefined)
  22902. if (ori !== "true" && ori !== "false") {
  22903. if (ori[0] === "!") {
  22904. result = !evaluateCallback(ori.substring(1));
  22905. }
  22906. else {
  22907. result = evaluateCallback(ori);
  22908. }
  22909. }
  22910. else {
  22911. result = ori === "true" ? true : false;
  22912. }
  22913. }
  22914. // the whole parenthesis scope is replaced by 'true' or 'false'
  22915. return result ? "true" : "false";
  22916. };
  22917. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22918. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22919. // remove whitespaces
  22920. r = r.replace(/[\s]/g, function () { return ""; });
  22921. return r.length % 2 ? "!" : "";
  22922. });
  22923. booleanString = booleanString.trim();
  22924. if (booleanString === "!true") {
  22925. booleanString = "false";
  22926. }
  22927. else if (booleanString === "!false") {
  22928. booleanString = "true";
  22929. }
  22930. return booleanString;
  22931. };
  22932. return AndOrNotEvaluator;
  22933. })();
  22934. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22935. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22936. })(BABYLON || (BABYLON = {}));
  22937. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22938. (function (BABYLON) {
  22939. var PostProcessRenderPass = (function () {
  22940. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22941. this._enabled = true;
  22942. this._refCount = 0;
  22943. this._name = name;
  22944. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22945. this.setRenderList(renderList);
  22946. this._renderTexture.onBeforeRender = beforeRender;
  22947. this._renderTexture.onAfterRender = afterRender;
  22948. this._scene = scene;
  22949. this._renderList = renderList;
  22950. }
  22951. // private
  22952. PostProcessRenderPass.prototype._incRefCount = function () {
  22953. if (this._refCount === 0) {
  22954. this._scene.customRenderTargets.push(this._renderTexture);
  22955. }
  22956. return ++this._refCount;
  22957. };
  22958. PostProcessRenderPass.prototype._decRefCount = function () {
  22959. this._refCount--;
  22960. if (this._refCount <= 0) {
  22961. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22962. }
  22963. return this._refCount;
  22964. };
  22965. PostProcessRenderPass.prototype._update = function () {
  22966. this.setRenderList(this._renderList);
  22967. };
  22968. // public
  22969. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22970. this._renderTexture.renderList = renderList;
  22971. };
  22972. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22973. return this._renderTexture;
  22974. };
  22975. return PostProcessRenderPass;
  22976. })();
  22977. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22978. })(BABYLON || (BABYLON = {}));
  22979. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22980. (function (BABYLON) {
  22981. var PostProcessRenderEffect = (function () {
  22982. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22983. this._engine = engine;
  22984. this._name = name;
  22985. this._singleInstance = singleInstance || true;
  22986. this._getPostProcess = getPostProcess;
  22987. this._cameras = [];
  22988. this._indicesForCamera = [];
  22989. this._postProcesses = {};
  22990. this._renderPasses = {};
  22991. this._renderEffectAsPasses = {};
  22992. }
  22993. PostProcessRenderEffect.prototype._update = function () {
  22994. for (var renderPassName in this._renderPasses) {
  22995. this._renderPasses[renderPassName]._update();
  22996. }
  22997. };
  22998. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22999. this._renderPasses[renderPass._name] = renderPass;
  23000. this._linkParameters();
  23001. };
  23002. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  23003. delete this._renderPasses[renderPass._name];
  23004. this._linkParameters();
  23005. };
  23006. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  23007. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  23008. this._linkParameters();
  23009. };
  23010. PostProcessRenderEffect.prototype.getPass = function (passName) {
  23011. for (var renderPassName in this._renderPasses) {
  23012. if (renderPassName === passName) {
  23013. return this._renderPasses[passName];
  23014. }
  23015. }
  23016. };
  23017. PostProcessRenderEffect.prototype.emptyPasses = function () {
  23018. this._renderPasses = {};
  23019. this._linkParameters();
  23020. };
  23021. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  23022. var cameraKey;
  23023. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23024. for (var i = 0; i < _cam.length; i++) {
  23025. var camera = _cam[i];
  23026. var cameraName = camera.name;
  23027. if (this._singleInstance) {
  23028. cameraKey = 0;
  23029. }
  23030. else {
  23031. cameraKey = cameraName;
  23032. }
  23033. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  23034. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  23035. if (!this._indicesForCamera[cameraName]) {
  23036. this._indicesForCamera[cameraName] = [];
  23037. }
  23038. this._indicesForCamera[cameraName].push(index);
  23039. if (this._cameras.indexOf(camera) === -1) {
  23040. this._cameras[cameraName] = camera;
  23041. }
  23042. for (var passName in this._renderPasses) {
  23043. this._renderPasses[passName]._incRefCount();
  23044. }
  23045. }
  23046. this._linkParameters();
  23047. };
  23048. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  23049. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23050. for (var i = 0; i < _cam.length; i++) {
  23051. var camera = _cam[i];
  23052. var cameraName = camera.name;
  23053. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23054. var index = this._cameras.indexOf(cameraName);
  23055. this._indicesForCamera.splice(index, 1);
  23056. this._cameras.splice(index, 1);
  23057. for (var passName in this._renderPasses) {
  23058. this._renderPasses[passName]._decRefCount();
  23059. }
  23060. }
  23061. };
  23062. PostProcessRenderEffect.prototype._enable = function (cameras) {
  23063. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23064. for (var i = 0; i < _cam.length; i++) {
  23065. var camera = _cam[i];
  23066. var cameraName = camera.name;
  23067. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  23068. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  23069. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  23070. }
  23071. }
  23072. for (var passName in this._renderPasses) {
  23073. this._renderPasses[passName]._incRefCount();
  23074. }
  23075. }
  23076. };
  23077. PostProcessRenderEffect.prototype._disable = function (cameras) {
  23078. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23079. for (var i = 0; i < _cam.length; i++) {
  23080. var camera = _cam[i];
  23081. var cameraName = camera.Name;
  23082. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  23083. for (var passName in this._renderPasses) {
  23084. this._renderPasses[passName]._decRefCount();
  23085. }
  23086. }
  23087. };
  23088. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  23089. if (this._singleInstance) {
  23090. return this._postProcesses[0];
  23091. }
  23092. else {
  23093. return this._postProcesses[camera.name];
  23094. }
  23095. };
  23096. PostProcessRenderEffect.prototype._linkParameters = function () {
  23097. var _this = this;
  23098. for (var index in this._postProcesses) {
  23099. if (this.applyParameters) {
  23100. this.applyParameters(this._postProcesses[index]);
  23101. }
  23102. this._postProcesses[index].onBeforeRender = function (effect) {
  23103. _this._linkTextures(effect);
  23104. };
  23105. }
  23106. };
  23107. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  23108. for (var renderPassName in this._renderPasses) {
  23109. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  23110. }
  23111. for (var renderEffectName in this._renderEffectAsPasses) {
  23112. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  23113. }
  23114. };
  23115. return PostProcessRenderEffect;
  23116. })();
  23117. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  23118. })(BABYLON || (BABYLON = {}));
  23119. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  23120. (function (BABYLON) {
  23121. var PostProcessRenderPipeline = (function () {
  23122. function PostProcessRenderPipeline(engine, name) {
  23123. this._engine = engine;
  23124. this._name = name;
  23125. this._renderEffects = {};
  23126. this._renderEffectsForIsolatedPass = {};
  23127. this._cameras = [];
  23128. }
  23129. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  23130. this._renderEffects[renderEffect._name] = renderEffect;
  23131. };
  23132. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  23133. var renderEffects = this._renderEffects[renderEffectName];
  23134. if (!renderEffects) {
  23135. return;
  23136. }
  23137. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23138. };
  23139. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  23140. var renderEffects = this._renderEffects[renderEffectName];
  23141. if (!renderEffects) {
  23142. return;
  23143. }
  23144. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  23145. };
  23146. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  23147. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23148. var indicesToDelete = [];
  23149. for (var i = 0; i < _cam.length; i++) {
  23150. var camera = _cam[i];
  23151. var cameraName = camera.name;
  23152. if (this._cameras.indexOf(camera) === -1) {
  23153. this._cameras[cameraName] = camera;
  23154. }
  23155. else if (unique) {
  23156. indicesToDelete.push(i);
  23157. }
  23158. }
  23159. for (var i = 0; i < indicesToDelete.length; i++) {
  23160. cameras.splice(indicesToDelete[i], 1);
  23161. }
  23162. for (var renderEffectName in this._renderEffects) {
  23163. this._renderEffects[renderEffectName]._attachCameras(_cam);
  23164. }
  23165. };
  23166. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  23167. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23168. for (var renderEffectName in this._renderEffects) {
  23169. this._renderEffects[renderEffectName]._detachCameras(_cam);
  23170. }
  23171. for (var i = 0; i < _cam.length; i++) {
  23172. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  23173. }
  23174. };
  23175. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  23176. var _this = this;
  23177. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23178. var pass = null;
  23179. for (var renderEffectName in this._renderEffects) {
  23180. pass = this._renderEffects[renderEffectName].getPass(passName);
  23181. if (pass != null) {
  23182. break;
  23183. }
  23184. }
  23185. if (pass === null) {
  23186. return;
  23187. }
  23188. for (var renderEffectName in this._renderEffects) {
  23189. this._renderEffects[renderEffectName]._disable(_cam);
  23190. }
  23191. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  23192. for (var i = 0; i < _cam.length; i++) {
  23193. var camera = _cam[i];
  23194. var cameraName = camera.name;
  23195. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23196. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23197. });
  23198. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  23199. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  23200. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  23201. }
  23202. };
  23203. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  23204. var _this = this;
  23205. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  23206. for (var i = 0; i < _cam.length; i++) {
  23207. var camera = _cam[i];
  23208. var cameraName = camera.name;
  23209. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  23210. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  23211. });
  23212. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  23213. }
  23214. for (var renderEffectName in this._renderEffects) {
  23215. this._renderEffects[renderEffectName]._enable(_cam);
  23216. }
  23217. };
  23218. PostProcessRenderPipeline.prototype._update = function () {
  23219. for (var renderEffectName in this._renderEffects) {
  23220. this._renderEffects[renderEffectName]._update();
  23221. }
  23222. for (var i = 0; i < this._cameras.length; i++) {
  23223. var cameraName = this._cameras[i].name;
  23224. if (this._renderEffectsForIsolatedPass[cameraName]) {
  23225. this._renderEffectsForIsolatedPass[cameraName]._update();
  23226. }
  23227. }
  23228. };
  23229. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  23230. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  23231. return PostProcessRenderPipeline;
  23232. })();
  23233. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  23234. })(BABYLON || (BABYLON = {}));
  23235. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  23236. (function (BABYLON) {
  23237. var PostProcessRenderPipelineManager = (function () {
  23238. function PostProcessRenderPipelineManager() {
  23239. this._renderPipelines = {};
  23240. }
  23241. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  23242. this._renderPipelines[renderPipeline._name] = renderPipeline;
  23243. };
  23244. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  23245. var renderPipeline = this._renderPipelines[renderPipelineName];
  23246. if (!renderPipeline) {
  23247. return;
  23248. }
  23249. renderPipeline._attachCameras(cameras, unique);
  23250. };
  23251. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  23252. var renderPipeline = this._renderPipelines[renderPipelineName];
  23253. if (!renderPipeline) {
  23254. return;
  23255. }
  23256. renderPipeline._detachCameras(cameras);
  23257. };
  23258. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23259. var renderPipeline = this._renderPipelines[renderPipelineName];
  23260. if (!renderPipeline) {
  23261. return;
  23262. }
  23263. renderPipeline._enableEffect(renderEffectName, cameras);
  23264. };
  23265. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  23266. var renderPipeline = this._renderPipelines[renderPipelineName];
  23267. if (!renderPipeline) {
  23268. return;
  23269. }
  23270. renderPipeline._disableEffect(renderEffectName, cameras);
  23271. };
  23272. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  23273. var renderPipeline = this._renderPipelines[renderPipelineName];
  23274. if (!renderPipeline) {
  23275. return;
  23276. }
  23277. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  23278. };
  23279. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  23280. var renderPipeline = this._renderPipelines[renderPipelineName];
  23281. if (!renderPipeline) {
  23282. return;
  23283. }
  23284. renderPipeline._disableDisplayOnlyPass(cameras);
  23285. };
  23286. PostProcessRenderPipelineManager.prototype.update = function () {
  23287. for (var renderPipelineName in this._renderPipelines) {
  23288. this._renderPipelines[renderPipelineName]._update();
  23289. }
  23290. };
  23291. return PostProcessRenderPipelineManager;
  23292. })();
  23293. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  23294. })(BABYLON || (BABYLON = {}));
  23295. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  23296. var BABYLON;
  23297. (function (BABYLON) {
  23298. var DisplayPassPostProcess = (function (_super) {
  23299. __extends(DisplayPassPostProcess, _super);
  23300. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  23301. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  23302. }
  23303. return DisplayPassPostProcess;
  23304. })(BABYLON.PostProcess);
  23305. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  23306. })(BABYLON || (BABYLON = {}));
  23307. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  23308. (function (BABYLON) {
  23309. var BoundingBoxRenderer = (function () {
  23310. function BoundingBoxRenderer(scene) {
  23311. this.frontColor = new BABYLON.Color3(1, 1, 1);
  23312. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  23313. this.showBackLines = true;
  23314. this.renderList = new BABYLON.SmartArray(32);
  23315. this._scene = scene;
  23316. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  23317. attributes: ["position"],
  23318. uniforms: ["worldViewProjection", "color"]
  23319. });
  23320. var engine = this._scene.getEngine();
  23321. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  23322. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  23323. 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]);
  23324. }
  23325. BoundingBoxRenderer.prototype.reset = function () {
  23326. this.renderList.reset();
  23327. };
  23328. BoundingBoxRenderer.prototype.render = function () {
  23329. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  23330. return;
  23331. }
  23332. var engine = this._scene.getEngine();
  23333. engine.setDepthWrite(false);
  23334. this._colorShader._preBind();
  23335. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  23336. var boundingBox = this.renderList.data[boundingBoxIndex];
  23337. var min = boundingBox.minimum;
  23338. var max = boundingBox.maximum;
  23339. var diff = max.subtract(min);
  23340. var median = min.add(diff.scale(0.5));
  23341. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  23342. // VBOs
  23343. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  23344. if (this.showBackLines) {
  23345. // Back
  23346. engine.setDepthFunctionToGreaterOrEqual();
  23347. this._scene.resetCachedMaterial();
  23348. this._colorShader.setColor4("color", this.backColor.toColor4());
  23349. this._colorShader.bind(worldMatrix);
  23350. // Draw order
  23351. engine.draw(false, 0, 24);
  23352. }
  23353. // Front
  23354. engine.setDepthFunctionToLess();
  23355. this._scene.resetCachedMaterial();
  23356. this._colorShader.setColor4("color", this.frontColor.toColor4());
  23357. this._colorShader.bind(worldMatrix);
  23358. // Draw order
  23359. engine.draw(false, 0, 24);
  23360. }
  23361. this._colorShader.unbind();
  23362. engine.setDepthFunctionToLessOrEqual();
  23363. engine.setDepthWrite(true);
  23364. };
  23365. BoundingBoxRenderer.prototype.dispose = function () {
  23366. this._colorShader.dispose();
  23367. this._vb.dispose();
  23368. this._scene.getEngine()._releaseBuffer(this._ib);
  23369. };
  23370. return BoundingBoxRenderer;
  23371. })();
  23372. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23373. })(BABYLON || (BABYLON = {}));
  23374. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23375. (function (BABYLON) {
  23376. var Internals;
  23377. (function (Internals) {
  23378. /*
  23379. * Based on jsTGALoader - Javascript loader for TGA file
  23380. * By Vincent Thibault
  23381. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23382. */
  23383. var TGATools = (function () {
  23384. function TGATools() {
  23385. }
  23386. TGATools.GetTGAHeader = function (data) {
  23387. var offset = 0;
  23388. var header = {
  23389. id_length: data[offset++],
  23390. colormap_type: data[offset++],
  23391. image_type: data[offset++],
  23392. colormap_index: data[offset++] | data[offset++] << 8,
  23393. colormap_length: data[offset++] | data[offset++] << 8,
  23394. colormap_size: data[offset++],
  23395. origin: [
  23396. data[offset++] | data[offset++] << 8,
  23397. data[offset++] | data[offset++] << 8
  23398. ],
  23399. width: data[offset++] | data[offset++] << 8,
  23400. height: data[offset++] | data[offset++] << 8,
  23401. pixel_size: data[offset++],
  23402. flags: data[offset++]
  23403. };
  23404. return header;
  23405. };
  23406. TGATools.UploadContent = function (gl, data) {
  23407. // Not enough data to contain header ?
  23408. if (data.length < 19) {
  23409. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23410. return;
  23411. }
  23412. // Read Header
  23413. var offset = 18;
  23414. var header = TGATools.GetTGAHeader(data);
  23415. // Assume it's a valid Targa file.
  23416. if (header.id_length + offset > data.length) {
  23417. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23418. return;
  23419. }
  23420. // Skip not needed data
  23421. offset += header.id_length;
  23422. var use_rle = false;
  23423. var use_pal = false;
  23424. var use_rgb = false;
  23425. var use_grey = false;
  23426. switch (header.image_type) {
  23427. case TGATools._TYPE_RLE_INDEXED:
  23428. use_rle = true;
  23429. case TGATools._TYPE_INDEXED:
  23430. use_pal = true;
  23431. break;
  23432. case TGATools._TYPE_RLE_RGB:
  23433. use_rle = true;
  23434. case TGATools._TYPE_RGB:
  23435. use_rgb = true;
  23436. break;
  23437. case TGATools._TYPE_RLE_GREY:
  23438. use_rle = true;
  23439. case TGATools._TYPE_GREY:
  23440. use_grey = true;
  23441. break;
  23442. }
  23443. var pixel_data;
  23444. var numAlphaBits = header.flags & 0xf;
  23445. var pixel_size = header.pixel_size >> 3;
  23446. var pixel_total = header.width * header.height * pixel_size;
  23447. // Read palettes
  23448. var palettes;
  23449. if (use_pal) {
  23450. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23451. }
  23452. // Read LRE
  23453. if (use_rle) {
  23454. pixel_data = new Uint8Array(pixel_total);
  23455. var c, count, i;
  23456. var localOffset = 0;
  23457. var pixels = new Uint8Array(pixel_size);
  23458. while (offset < pixel_total && localOffset < pixel_total) {
  23459. c = data[offset++];
  23460. count = (c & 0x7f) + 1;
  23461. // RLE pixels
  23462. if (c & 0x80) {
  23463. for (i = 0; i < pixel_size; ++i) {
  23464. pixels[i] = data[offset++];
  23465. }
  23466. for (i = 0; i < count; ++i) {
  23467. pixel_data.set(pixels, localOffset + i * pixel_size);
  23468. }
  23469. localOffset += pixel_size * count;
  23470. }
  23471. else {
  23472. count *= pixel_size;
  23473. for (i = 0; i < count; ++i) {
  23474. pixel_data[localOffset + i] = data[offset++];
  23475. }
  23476. localOffset += count;
  23477. }
  23478. }
  23479. }
  23480. else {
  23481. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23482. }
  23483. // Load to texture
  23484. var x_start, y_start, x_step, y_step, y_end, x_end;
  23485. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23486. default:
  23487. case TGATools._ORIGIN_UL:
  23488. x_start = 0;
  23489. x_step = 1;
  23490. x_end = header.width;
  23491. y_start = 0;
  23492. y_step = 1;
  23493. y_end = header.height;
  23494. break;
  23495. case TGATools._ORIGIN_BL:
  23496. x_start = 0;
  23497. x_step = 1;
  23498. x_end = header.width;
  23499. y_start = header.height - 1;
  23500. y_step = -1;
  23501. y_end = -1;
  23502. break;
  23503. case TGATools._ORIGIN_UR:
  23504. x_start = header.width - 1;
  23505. x_step = -1;
  23506. x_end = -1;
  23507. y_start = 0;
  23508. y_step = 1;
  23509. y_end = header.height;
  23510. break;
  23511. case TGATools._ORIGIN_BR:
  23512. x_start = header.width - 1;
  23513. x_step = -1;
  23514. x_end = -1;
  23515. y_start = header.height - 1;
  23516. y_step = -1;
  23517. y_end = -1;
  23518. break;
  23519. }
  23520. // Load the specify method
  23521. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23522. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23523. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23524. };
  23525. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23526. var image = pixel_data, colormap = palettes;
  23527. var width = header.width, height = header.height;
  23528. var color, i = 0, x, y;
  23529. var imageData = new Uint8Array(width * height * 4);
  23530. for (y = y_start; y !== y_end; y += y_step) {
  23531. for (x = x_start; x !== x_end; x += x_step, i++) {
  23532. color = image[i];
  23533. imageData[(x + width * y) * 4 + 3] = 255;
  23534. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23535. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23536. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23537. }
  23538. }
  23539. return imageData;
  23540. };
  23541. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23542. var image = pixel_data;
  23543. var width = header.width, height = header.height;
  23544. var color, i = 0, x, y;
  23545. var imageData = new Uint8Array(width * height * 4);
  23546. for (y = y_start; y !== y_end; y += y_step) {
  23547. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23548. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23549. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23550. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23551. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23552. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23553. }
  23554. }
  23555. return imageData;
  23556. };
  23557. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23558. var image = pixel_data;
  23559. var width = header.width, height = header.height;
  23560. var i = 0, x, y;
  23561. var imageData = new Uint8Array(width * height * 4);
  23562. for (y = y_start; y !== y_end; y += y_step) {
  23563. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23564. imageData[(x + width * y) * 4 + 3] = 255;
  23565. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23566. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23567. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23568. }
  23569. }
  23570. return imageData;
  23571. };
  23572. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23573. var image = pixel_data;
  23574. var width = header.width, height = header.height;
  23575. var i = 0, x, y;
  23576. var imageData = new Uint8Array(width * height * 4);
  23577. for (y = y_start; y !== y_end; y += y_step) {
  23578. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23579. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23580. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23581. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23582. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23583. }
  23584. }
  23585. return imageData;
  23586. };
  23587. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23588. var image = pixel_data;
  23589. var width = header.width, height = header.height;
  23590. var color, i = 0, x, y;
  23591. var imageData = new Uint8Array(width * height * 4);
  23592. for (y = y_start; y !== y_end; y += y_step) {
  23593. for (x = x_start; x !== x_end; x += x_step, i++) {
  23594. color = image[i];
  23595. imageData[(x + width * y) * 4 + 0] = color;
  23596. imageData[(x + width * y) * 4 + 1] = color;
  23597. imageData[(x + width * y) * 4 + 2] = color;
  23598. imageData[(x + width * y) * 4 + 3] = 255;
  23599. }
  23600. }
  23601. return imageData;
  23602. };
  23603. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23604. var image = pixel_data;
  23605. var width = header.width, height = header.height;
  23606. var i = 0, x, y;
  23607. var imageData = new Uint8Array(width * height * 4);
  23608. for (y = y_start; y !== y_end; y += y_step) {
  23609. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23610. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23611. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23612. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23613. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23614. }
  23615. }
  23616. return imageData;
  23617. };
  23618. TGATools._TYPE_NO_DATA = 0;
  23619. TGATools._TYPE_INDEXED = 1;
  23620. TGATools._TYPE_RGB = 2;
  23621. TGATools._TYPE_GREY = 3;
  23622. TGATools._TYPE_RLE_INDEXED = 9;
  23623. TGATools._TYPE_RLE_RGB = 10;
  23624. TGATools._TYPE_RLE_GREY = 11;
  23625. TGATools._ORIGIN_MASK = 0x30;
  23626. TGATools._ORIGIN_SHIFT = 0x04;
  23627. TGATools._ORIGIN_BL = 0x00;
  23628. TGATools._ORIGIN_BR = 0x01;
  23629. TGATools._ORIGIN_UL = 0x02;
  23630. TGATools._ORIGIN_UR = 0x03;
  23631. return TGATools;
  23632. })();
  23633. Internals.TGATools = TGATools;
  23634. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23635. })(BABYLON || (BABYLON = {}));
  23636. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23637. (function (BABYLON) {
  23638. var Internals;
  23639. (function (Internals) {
  23640. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23641. // All values and structures referenced from:
  23642. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23643. var DDS_MAGIC = 0x20534444;
  23644. 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;
  23645. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23646. 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;
  23647. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23648. function FourCCToInt32(value) {
  23649. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23650. }
  23651. function Int32ToFourCC(value) {
  23652. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23653. }
  23654. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23655. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23656. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23657. var headerLengthInt = 31; // The header length in 32 bit ints
  23658. // Offsets into the header array
  23659. var off_magic = 0;
  23660. var off_size = 1;
  23661. var off_flags = 2;
  23662. var off_height = 3;
  23663. var off_width = 4;
  23664. var off_mipmapCount = 7;
  23665. var off_pfFlags = 20;
  23666. var off_pfFourCC = 21;
  23667. var off_RGBbpp = 22;
  23668. var off_RMask = 23;
  23669. var off_GMask = 24;
  23670. var off_BMask = 25;
  23671. var off_AMask = 26;
  23672. var off_caps1 = 27;
  23673. var off_caps2 = 28;
  23674. ;
  23675. var DDSTools = (function () {
  23676. function DDSTools() {
  23677. }
  23678. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23679. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23680. var mipmapCount = 1;
  23681. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23682. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23683. }
  23684. return {
  23685. width: header[off_width],
  23686. height: header[off_height],
  23687. mipmapCount: mipmapCount,
  23688. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23689. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23690. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23691. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23692. };
  23693. };
  23694. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23695. var byteArray = new Uint8Array(dataLength);
  23696. var srcData = new Uint8Array(arrayBuffer);
  23697. var index = 0;
  23698. for (var y = height - 1; y >= 0; y--) {
  23699. for (var x = 0; x < width; x++) {
  23700. var srcPos = dataOffset + (x + y * width) * 4;
  23701. byteArray[index + 2] = srcData[srcPos];
  23702. byteArray[index + 1] = srcData[srcPos + 1];
  23703. byteArray[index] = srcData[srcPos + 2];
  23704. byteArray[index + 3] = srcData[srcPos + 3];
  23705. index += 4;
  23706. }
  23707. }
  23708. return byteArray;
  23709. };
  23710. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23711. var byteArray = new Uint8Array(dataLength);
  23712. var srcData = new Uint8Array(arrayBuffer);
  23713. var index = 0;
  23714. for (var y = height - 1; y >= 0; y--) {
  23715. for (var x = 0; x < width; x++) {
  23716. var srcPos = dataOffset + (x + y * width) * 3;
  23717. byteArray[index + 2] = srcData[srcPos];
  23718. byteArray[index + 1] = srcData[srcPos + 1];
  23719. byteArray[index] = srcData[srcPos + 2];
  23720. index += 3;
  23721. }
  23722. }
  23723. return byteArray;
  23724. };
  23725. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23726. var byteArray = new Uint8Array(dataLength);
  23727. var srcData = new Uint8Array(arrayBuffer);
  23728. var index = 0;
  23729. for (var y = height - 1; y >= 0; y--) {
  23730. for (var x = 0; x < width; x++) {
  23731. var srcPos = dataOffset + (x + y * width);
  23732. byteArray[index] = srcData[srcPos];
  23733. index++;
  23734. }
  23735. }
  23736. return byteArray;
  23737. };
  23738. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23739. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23740. if (header[off_magic] != DDS_MAGIC) {
  23741. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23742. return;
  23743. }
  23744. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23745. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23746. return;
  23747. }
  23748. if (info.isFourCC) {
  23749. fourCC = header[off_pfFourCC];
  23750. switch (fourCC) {
  23751. case FOURCC_DXT1:
  23752. blockBytes = 8;
  23753. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23754. break;
  23755. case FOURCC_DXT3:
  23756. blockBytes = 16;
  23757. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23758. break;
  23759. case FOURCC_DXT5:
  23760. blockBytes = 16;
  23761. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23762. break;
  23763. default:
  23764. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23765. return;
  23766. }
  23767. }
  23768. mipmapCount = 1;
  23769. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23770. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23771. }
  23772. var bpp = header[off_RGBbpp];
  23773. for (var face = 0; face < faces; face++) {
  23774. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23775. width = header[off_width];
  23776. height = header[off_height];
  23777. dataOffset = header[off_size] + 4;
  23778. for (i = 0; i < mipmapCount; ++i) {
  23779. if (info.isRGB) {
  23780. if (bpp == 24) {
  23781. dataLength = width * height * 3;
  23782. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23783. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23784. }
  23785. else {
  23786. dataLength = width * height * 4;
  23787. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23788. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23789. }
  23790. }
  23791. else if (info.isLuminance) {
  23792. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23793. var unpaddedRowSize = width;
  23794. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23795. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23796. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23797. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23798. }
  23799. else {
  23800. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23801. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23802. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23803. }
  23804. dataOffset += dataLength;
  23805. width *= 0.5;
  23806. height *= 0.5;
  23807. width = Math.max(1.0, width);
  23808. height = Math.max(1.0, height);
  23809. }
  23810. }
  23811. };
  23812. return DDSTools;
  23813. })();
  23814. Internals.DDSTools = DDSTools;
  23815. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23816. })(BABYLON || (BABYLON = {}));
  23817. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23818. (function (BABYLON) {
  23819. var SmartArray = (function () {
  23820. function SmartArray(capacity) {
  23821. this.length = 0;
  23822. this._duplicateId = 0;
  23823. this.data = new Array(capacity);
  23824. this._id = SmartArray._GlobalId++;
  23825. }
  23826. SmartArray.prototype.push = function (value) {
  23827. this.data[this.length++] = value;
  23828. if (this.length > this.data.length) {
  23829. this.data.length *= 2;
  23830. }
  23831. if (!value.__smartArrayFlags) {
  23832. value.__smartArrayFlags = {};
  23833. }
  23834. value.__smartArrayFlags[this._id] = this._duplicateId;
  23835. };
  23836. SmartArray.prototype.pushNoDuplicate = function (value) {
  23837. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23838. return;
  23839. }
  23840. this.push(value);
  23841. };
  23842. SmartArray.prototype.sort = function (compareFn) {
  23843. this.data.sort(compareFn);
  23844. };
  23845. SmartArray.prototype.reset = function () {
  23846. this.length = 0;
  23847. this._duplicateId++;
  23848. };
  23849. SmartArray.prototype.concat = function (array) {
  23850. if (array.length === 0) {
  23851. return;
  23852. }
  23853. if (this.length + array.length > this.data.length) {
  23854. this.data.length = (this.length + array.length) * 2;
  23855. }
  23856. for (var index = 0; index < array.length; index++) {
  23857. this.data[this.length++] = (array.data || array)[index];
  23858. }
  23859. };
  23860. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23861. if (array.length === 0) {
  23862. return;
  23863. }
  23864. if (this.length + array.length > this.data.length) {
  23865. this.data.length = (this.length + array.length) * 2;
  23866. }
  23867. for (var index = 0; index < array.length; index++) {
  23868. var item = (array.data || array)[index];
  23869. this.pushNoDuplicate(item);
  23870. }
  23871. };
  23872. SmartArray.prototype.indexOf = function (value) {
  23873. var position = this.data.indexOf(value);
  23874. if (position >= this.length) {
  23875. return -1;
  23876. }
  23877. return position;
  23878. };
  23879. // Statics
  23880. SmartArray._GlobalId = 0;
  23881. return SmartArray;
  23882. })();
  23883. BABYLON.SmartArray = SmartArray;
  23884. })(BABYLON || (BABYLON = {}));
  23885. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23886. (function (BABYLON) {
  23887. var CannonJSPlugin = (function () {
  23888. function CannonJSPlugin() {
  23889. this._registeredMeshes = [];
  23890. this._physicsMaterials = [];
  23891. this.updateBodyPosition = function (mesh) {
  23892. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23893. var registeredMesh = this._registeredMeshes[index];
  23894. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23895. var body = registeredMesh.body;
  23896. var center = mesh.getBoundingInfo().boundingBox.center;
  23897. body.position.set(center.x, center.z, center.y);
  23898. body.quaternion.x = mesh.rotationQuaternion.x;
  23899. body.quaternion.z = mesh.rotationQuaternion.y;
  23900. body.quaternion.y = mesh.rotationQuaternion.z;
  23901. body.quaternion.w = -mesh.rotationQuaternion.w;
  23902. return;
  23903. }
  23904. }
  23905. };
  23906. }
  23907. CannonJSPlugin.prototype.initialize = function (iterations) {
  23908. if (iterations === void 0) { iterations = 10; }
  23909. this._world = new CANNON.World();
  23910. this._world.broadphase = new CANNON.NaiveBroadphase();
  23911. this._world.solver.iterations = iterations;
  23912. };
  23913. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23914. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23915. };
  23916. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23917. this._world.step(delta);
  23918. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23919. var registeredMesh = this._registeredMeshes[index];
  23920. if (registeredMesh.isChild) {
  23921. continue;
  23922. }
  23923. // Body position
  23924. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23925. var deltaPos = registeredMesh.delta;
  23926. if (deltaPos) {
  23927. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23928. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23929. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23930. }
  23931. else {
  23932. registeredMesh.mesh.position.x = bodyX;
  23933. registeredMesh.mesh.position.y = bodyZ;
  23934. registeredMesh.mesh.position.z = bodyY;
  23935. }
  23936. if (!registeredMesh.mesh.rotationQuaternion) {
  23937. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23938. }
  23939. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23940. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23941. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23942. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23943. }
  23944. };
  23945. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23946. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23947. };
  23948. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23949. this.unregisterMesh(mesh);
  23950. mesh.computeWorldMatrix(true);
  23951. switch (impostor) {
  23952. case BABYLON.PhysicsEngine.SphereImpostor:
  23953. var bbox = mesh.getBoundingInfo().boundingBox;
  23954. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23955. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23956. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23957. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23958. case BABYLON.PhysicsEngine.BoxImpostor:
  23959. bbox = mesh.getBoundingInfo().boundingBox;
  23960. var min = bbox.minimumWorld;
  23961. var max = bbox.maximumWorld;
  23962. var box = max.subtract(min).scale(0.5);
  23963. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23964. case BABYLON.PhysicsEngine.PlaneImpostor:
  23965. return this._createPlane(mesh, options);
  23966. case BABYLON.PhysicsEngine.MeshImpostor:
  23967. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23968. var rawFaces = mesh.getIndices();
  23969. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23970. }
  23971. return null;
  23972. };
  23973. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23974. var shape = new CANNON.Sphere(radius);
  23975. if (!options) {
  23976. return shape;
  23977. }
  23978. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23979. };
  23980. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23981. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23982. if (!options) {
  23983. return shape;
  23984. }
  23985. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23986. };
  23987. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23988. var shape = new CANNON.Plane();
  23989. if (!options) {
  23990. return shape;
  23991. }
  23992. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23993. };
  23994. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23995. var verts = [], faces = [];
  23996. mesh.computeWorldMatrix(true);
  23997. for (var i = 0; i < rawVerts.length; i += 3) {
  23998. var transformed = BABYLON.Vector3.Zero();
  23999. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  24000. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  24001. }
  24002. for (var j = 0; j < rawFaces.length; j += 3) {
  24003. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  24004. }
  24005. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  24006. if (!options) {
  24007. return shape;
  24008. }
  24009. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  24010. };
  24011. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  24012. var index;
  24013. var mat;
  24014. for (index = 0; index < this._physicsMaterials.length; index++) {
  24015. mat = this._physicsMaterials[index];
  24016. if (mat.friction === friction && mat.restitution === restitution) {
  24017. return mat;
  24018. }
  24019. }
  24020. var currentMat = new CANNON.Material();
  24021. currentMat.friction = friction;
  24022. currentMat.restitution = restitution;
  24023. this._physicsMaterials.push(currentMat);
  24024. for (index = 0; index < this._physicsMaterials.length; index++) {
  24025. mat = this._physicsMaterials[index];
  24026. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  24027. contactMaterial.contactEquationStiffness = 1e10;
  24028. contactMaterial.contactEquationRegularizationTime = 10;
  24029. this._world.addContactMaterial(contactMaterial);
  24030. }
  24031. return currentMat;
  24032. };
  24033. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  24034. var initialRotation = null;
  24035. if (mesh.rotationQuaternion) {
  24036. initialRotation = mesh.rotationQuaternion.clone();
  24037. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  24038. }
  24039. // The delta between the mesh position and the mesh bounding box center
  24040. var bbox = mesh.getBoundingInfo().boundingBox;
  24041. var deltaPosition = mesh.position.subtract(bbox.center);
  24042. var material = this._addMaterial(friction, restitution);
  24043. var body = new CANNON.RigidBody(mass, shape, material);
  24044. if (initialRotation) {
  24045. body.quaternion.x = initialRotation.x;
  24046. body.quaternion.z = initialRotation.y;
  24047. body.quaternion.y = initialRotation.z;
  24048. body.quaternion.w = -initialRotation.w;
  24049. }
  24050. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  24051. this._world.add(body);
  24052. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  24053. return body;
  24054. };
  24055. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  24056. var compoundShape = new CANNON.Compound();
  24057. for (var index = 0; index < parts.length; index++) {
  24058. var mesh = parts[index].mesh;
  24059. var shape = this.registerMesh(mesh, parts[index].impostor);
  24060. if (index == 0) {
  24061. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  24062. }
  24063. else {
  24064. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  24065. }
  24066. }
  24067. var initialMesh = parts[0].mesh;
  24068. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  24069. body.parts = parts;
  24070. return body;
  24071. };
  24072. CannonJSPlugin.prototype._unbindBody = function (body) {
  24073. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24074. var registeredMesh = this._registeredMeshes[index];
  24075. if (registeredMesh.body === body) {
  24076. registeredMesh.body = null;
  24077. registeredMesh.delta = 0;
  24078. }
  24079. }
  24080. };
  24081. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  24082. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24083. var registeredMesh = this._registeredMeshes[index];
  24084. if (registeredMesh.mesh === mesh) {
  24085. // Remove body
  24086. if (registeredMesh.body) {
  24087. this._world.remove(registeredMesh.body);
  24088. this._unbindBody(registeredMesh.body);
  24089. }
  24090. this._registeredMeshes.splice(index, 1);
  24091. return;
  24092. }
  24093. }
  24094. };
  24095. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  24096. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  24097. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  24098. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24099. var registeredMesh = this._registeredMeshes[index];
  24100. if (registeredMesh.mesh === mesh) {
  24101. registeredMesh.body.applyImpulse(impulse, worldPoint);
  24102. return;
  24103. }
  24104. }
  24105. };
  24106. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  24107. var body1 = null, body2 = null;
  24108. for (var index = 0; index < this._registeredMeshes.length; index++) {
  24109. var registeredMesh = this._registeredMeshes[index];
  24110. if (registeredMesh.mesh === mesh1) {
  24111. body1 = registeredMesh.body;
  24112. }
  24113. else if (registeredMesh.mesh === mesh2) {
  24114. body2 = registeredMesh.body;
  24115. }
  24116. }
  24117. if (!body1 || !body2) {
  24118. return false;
  24119. }
  24120. 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));
  24121. this._world.addConstraint(constraint);
  24122. return true;
  24123. };
  24124. CannonJSPlugin.prototype.dispose = function () {
  24125. while (this._registeredMeshes.length) {
  24126. this.unregisterMesh(this._registeredMeshes[0].mesh);
  24127. }
  24128. };
  24129. CannonJSPlugin.prototype.isSupported = function () {
  24130. return window.CANNON !== undefined;
  24131. };
  24132. return CannonJSPlugin;
  24133. })();
  24134. BABYLON.CannonJSPlugin = CannonJSPlugin;
  24135. })(BABYLON || (BABYLON = {}));
  24136. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  24137. var BABYLON;
  24138. (function (BABYLON) {
  24139. var Condition = (function () {
  24140. function Condition(actionManager) {
  24141. this._actionManager = actionManager;
  24142. }
  24143. Condition.prototype.isValid = function () {
  24144. return true;
  24145. };
  24146. Condition.prototype._getProperty = function (propertyPath) {
  24147. return this._actionManager._getProperty(propertyPath);
  24148. };
  24149. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  24150. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24151. };
  24152. return Condition;
  24153. })();
  24154. BABYLON.Condition = Condition;
  24155. var ValueCondition = (function (_super) {
  24156. __extends(ValueCondition, _super);
  24157. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  24158. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  24159. _super.call(this, actionManager);
  24160. this.propertyPath = propertyPath;
  24161. this.value = value;
  24162. this.operator = operator;
  24163. this._target = this._getEffectiveTarget(target, this.propertyPath);
  24164. this._property = this._getProperty(this.propertyPath);
  24165. }
  24166. Object.defineProperty(ValueCondition, "IsEqual", {
  24167. get: function () {
  24168. return ValueCondition._IsEqual;
  24169. },
  24170. enumerable: true,
  24171. configurable: true
  24172. });
  24173. Object.defineProperty(ValueCondition, "IsDifferent", {
  24174. get: function () {
  24175. return ValueCondition._IsDifferent;
  24176. },
  24177. enumerable: true,
  24178. configurable: true
  24179. });
  24180. Object.defineProperty(ValueCondition, "IsGreater", {
  24181. get: function () {
  24182. return ValueCondition._IsGreater;
  24183. },
  24184. enumerable: true,
  24185. configurable: true
  24186. });
  24187. Object.defineProperty(ValueCondition, "IsLesser", {
  24188. get: function () {
  24189. return ValueCondition._IsLesser;
  24190. },
  24191. enumerable: true,
  24192. configurable: true
  24193. });
  24194. // Methods
  24195. ValueCondition.prototype.isValid = function () {
  24196. switch (this.operator) {
  24197. case ValueCondition.IsGreater:
  24198. return this._target[this._property] > this.value;
  24199. case ValueCondition.IsLesser:
  24200. return this._target[this._property] < this.value;
  24201. case ValueCondition.IsEqual:
  24202. case ValueCondition.IsDifferent:
  24203. var check;
  24204. if (this.value.equals) {
  24205. check = this.value.equals(this._target[this._property]);
  24206. }
  24207. else {
  24208. check = this.value === this._target[this._property];
  24209. }
  24210. return this.operator === ValueCondition.IsEqual ? check : !check;
  24211. }
  24212. return false;
  24213. };
  24214. // Statics
  24215. ValueCondition._IsEqual = 0;
  24216. ValueCondition._IsDifferent = 1;
  24217. ValueCondition._IsGreater = 2;
  24218. ValueCondition._IsLesser = 3;
  24219. return ValueCondition;
  24220. })(Condition);
  24221. BABYLON.ValueCondition = ValueCondition;
  24222. var PredicateCondition = (function (_super) {
  24223. __extends(PredicateCondition, _super);
  24224. function PredicateCondition(actionManager, predicate) {
  24225. _super.call(this, actionManager);
  24226. this.predicate = predicate;
  24227. }
  24228. PredicateCondition.prototype.isValid = function () {
  24229. return this.predicate();
  24230. };
  24231. return PredicateCondition;
  24232. })(Condition);
  24233. BABYLON.PredicateCondition = PredicateCondition;
  24234. var StateCondition = (function (_super) {
  24235. __extends(StateCondition, _super);
  24236. function StateCondition(actionManager, target, value) {
  24237. _super.call(this, actionManager);
  24238. this.value = value;
  24239. this._target = target;
  24240. }
  24241. // Methods
  24242. StateCondition.prototype.isValid = function () {
  24243. return this._target.state === this.value;
  24244. };
  24245. return StateCondition;
  24246. })(Condition);
  24247. BABYLON.StateCondition = StateCondition;
  24248. })(BABYLON || (BABYLON = {}));
  24249. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  24250. (function (BABYLON) {
  24251. var Action = (function () {
  24252. function Action(triggerOptions, condition) {
  24253. this.triggerOptions = triggerOptions;
  24254. if (triggerOptions.parameter) {
  24255. this.trigger = triggerOptions.trigger;
  24256. this._triggerParameter = triggerOptions.parameter;
  24257. }
  24258. else {
  24259. this.trigger = triggerOptions;
  24260. }
  24261. this._nextActiveAction = this;
  24262. this._condition = condition;
  24263. }
  24264. // Methods
  24265. Action.prototype._prepare = function () {
  24266. };
  24267. Action.prototype.getTriggerParameter = function () {
  24268. return this._triggerParameter;
  24269. };
  24270. Action.prototype._executeCurrent = function (evt) {
  24271. if (this._nextActiveAction._condition) {
  24272. var condition = this._nextActiveAction._condition;
  24273. var currentRenderId = this._actionManager.getScene().getRenderId();
  24274. // We cache the current evaluation for the current frame
  24275. if (condition._evaluationId === currentRenderId) {
  24276. if (!condition._currentResult) {
  24277. return;
  24278. }
  24279. }
  24280. else {
  24281. condition._evaluationId = currentRenderId;
  24282. if (!condition.isValid()) {
  24283. condition._currentResult = false;
  24284. return;
  24285. }
  24286. condition._currentResult = true;
  24287. }
  24288. }
  24289. this._nextActiveAction.execute(evt);
  24290. if (this._nextActiveAction._child) {
  24291. if (!this._nextActiveAction._child._actionManager) {
  24292. this._nextActiveAction._child._actionManager = this._actionManager;
  24293. }
  24294. this._nextActiveAction = this._nextActiveAction._child;
  24295. }
  24296. else {
  24297. this._nextActiveAction = this;
  24298. }
  24299. };
  24300. Action.prototype.execute = function (evt) {
  24301. };
  24302. Action.prototype.then = function (action) {
  24303. this._child = action;
  24304. action._actionManager = this._actionManager;
  24305. action._prepare();
  24306. return action;
  24307. };
  24308. Action.prototype._getProperty = function (propertyPath) {
  24309. return this._actionManager._getProperty(propertyPath);
  24310. };
  24311. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  24312. return this._actionManager._getEffectiveTarget(target, propertyPath);
  24313. };
  24314. return Action;
  24315. })();
  24316. BABYLON.Action = Action;
  24317. })(BABYLON || (BABYLON = {}));
  24318. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  24319. (function (BABYLON) {
  24320. /**
  24321. * ActionEvent is the event beint sent when an action is triggered.
  24322. */
  24323. var ActionEvent = (function () {
  24324. /**
  24325. * @constructor
  24326. * @param source The mesh that triggered the action.
  24327. * @param pointerX the X mouse cursor position at the time of the event
  24328. * @param pointerY the Y mouse cursor position at the time of the event
  24329. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  24330. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  24331. */
  24332. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  24333. this.source = source;
  24334. this.pointerX = pointerX;
  24335. this.pointerY = pointerY;
  24336. this.meshUnderPointer = meshUnderPointer;
  24337. this.sourceEvent = sourceEvent;
  24338. }
  24339. /**
  24340. * Helper function to auto-create an ActionEvent from a source mesh.
  24341. * @param source the source mesh that triggered the event
  24342. * @param evt {Event} The original (browser) event
  24343. */
  24344. ActionEvent.CreateNew = function (source, evt) {
  24345. var scene = source.getScene();
  24346. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24347. };
  24348. /**
  24349. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  24350. * @param scene the scene where the event occurred
  24351. * @param evt {Event} The original (browser) event
  24352. */
  24353. ActionEvent.CreateNewFromScene = function (scene, evt) {
  24354. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  24355. };
  24356. return ActionEvent;
  24357. })();
  24358. BABYLON.ActionEvent = ActionEvent;
  24359. /**
  24360. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24361. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24362. */
  24363. var ActionManager = (function () {
  24364. function ActionManager(scene) {
  24365. // Members
  24366. this.actions = new Array();
  24367. this._scene = scene;
  24368. scene._actionManagers.push(this);
  24369. }
  24370. Object.defineProperty(ActionManager, "NothingTrigger", {
  24371. get: function () {
  24372. return ActionManager._NothingTrigger;
  24373. },
  24374. enumerable: true,
  24375. configurable: true
  24376. });
  24377. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24378. get: function () {
  24379. return ActionManager._OnPickTrigger;
  24380. },
  24381. enumerable: true,
  24382. configurable: true
  24383. });
  24384. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24385. get: function () {
  24386. return ActionManager._OnLeftPickTrigger;
  24387. },
  24388. enumerable: true,
  24389. configurable: true
  24390. });
  24391. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24392. get: function () {
  24393. return ActionManager._OnRightPickTrigger;
  24394. },
  24395. enumerable: true,
  24396. configurable: true
  24397. });
  24398. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24399. get: function () {
  24400. return ActionManager._OnCenterPickTrigger;
  24401. },
  24402. enumerable: true,
  24403. configurable: true
  24404. });
  24405. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24406. get: function () {
  24407. return ActionManager._OnPointerOverTrigger;
  24408. },
  24409. enumerable: true,
  24410. configurable: true
  24411. });
  24412. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24413. get: function () {
  24414. return ActionManager._OnPointerOutTrigger;
  24415. },
  24416. enumerable: true,
  24417. configurable: true
  24418. });
  24419. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24420. get: function () {
  24421. return ActionManager._OnEveryFrameTrigger;
  24422. },
  24423. enumerable: true,
  24424. configurable: true
  24425. });
  24426. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24427. get: function () {
  24428. return ActionManager._OnIntersectionEnterTrigger;
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24434. get: function () {
  24435. return ActionManager._OnIntersectionExitTrigger;
  24436. },
  24437. enumerable: true,
  24438. configurable: true
  24439. });
  24440. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24441. get: function () {
  24442. return ActionManager._OnKeyDownTrigger;
  24443. },
  24444. enumerable: true,
  24445. configurable: true
  24446. });
  24447. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24448. get: function () {
  24449. return ActionManager._OnKeyUpTrigger;
  24450. },
  24451. enumerable: true,
  24452. configurable: true
  24453. });
  24454. // Methods
  24455. ActionManager.prototype.dispose = function () {
  24456. var index = this._scene._actionManagers.indexOf(this);
  24457. if (index > -1) {
  24458. this._scene._actionManagers.splice(index, 1);
  24459. }
  24460. };
  24461. ActionManager.prototype.getScene = function () {
  24462. return this._scene;
  24463. };
  24464. /**
  24465. * Does this action manager handles actions of any of the given triggers
  24466. * @param {number[]} triggers - the triggers to be tested
  24467. * @return {boolean} whether one (or more) of the triggers is handeled
  24468. */
  24469. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24470. for (var index = 0; index < this.actions.length; index++) {
  24471. var action = this.actions[index];
  24472. if (triggers.indexOf(action.trigger) > -1) {
  24473. return true;
  24474. }
  24475. }
  24476. return false;
  24477. };
  24478. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24479. /**
  24480. * Does this action manager has pointer triggers
  24481. * @return {boolean} whether or not it has pointer triggers
  24482. */
  24483. get: function () {
  24484. for (var index = 0; index < this.actions.length; index++) {
  24485. var action = this.actions[index];
  24486. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24487. return true;
  24488. }
  24489. }
  24490. return false;
  24491. },
  24492. enumerable: true,
  24493. configurable: true
  24494. });
  24495. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24496. /**
  24497. * Does this action manager has pick triggers
  24498. * @return {boolean} whether or not it has pick triggers
  24499. */
  24500. get: function () {
  24501. for (var index = 0; index < this.actions.length; index++) {
  24502. var action = this.actions[index];
  24503. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24504. return true;
  24505. }
  24506. }
  24507. return false;
  24508. },
  24509. enumerable: true,
  24510. configurable: true
  24511. });
  24512. /**
  24513. * Registers an action to this action manager
  24514. * @param {BABYLON.Action} action - the action to be registered
  24515. * @return {BABYLON.Action} the action amended (prepared) after registration
  24516. */
  24517. ActionManager.prototype.registerAction = function (action) {
  24518. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24519. if (this.getScene().actionManager !== this) {
  24520. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24521. return null;
  24522. }
  24523. }
  24524. this.actions.push(action);
  24525. action._actionManager = this;
  24526. action._prepare();
  24527. return action;
  24528. };
  24529. /**
  24530. * Process a specific trigger
  24531. * @param {number} trigger - the trigger to process
  24532. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24533. */
  24534. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24535. for (var index = 0; index < this.actions.length; index++) {
  24536. var action = this.actions[index];
  24537. if (action.trigger === trigger) {
  24538. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24539. var parameter = action.getTriggerParameter();
  24540. if (parameter) {
  24541. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24542. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24543. if (actualkey !== parameter.toLowerCase()) {
  24544. continue;
  24545. }
  24546. }
  24547. }
  24548. action._executeCurrent(evt);
  24549. }
  24550. }
  24551. };
  24552. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24553. var properties = propertyPath.split(".");
  24554. for (var index = 0; index < properties.length - 1; index++) {
  24555. target = target[properties[index]];
  24556. }
  24557. return target;
  24558. };
  24559. ActionManager.prototype._getProperty = function (propertyPath) {
  24560. var properties = propertyPath.split(".");
  24561. return properties[properties.length - 1];
  24562. };
  24563. // Statics
  24564. ActionManager._NothingTrigger = 0;
  24565. ActionManager._OnPickTrigger = 1;
  24566. ActionManager._OnLeftPickTrigger = 2;
  24567. ActionManager._OnRightPickTrigger = 3;
  24568. ActionManager._OnCenterPickTrigger = 4;
  24569. ActionManager._OnPointerOverTrigger = 5;
  24570. ActionManager._OnPointerOutTrigger = 6;
  24571. ActionManager._OnEveryFrameTrigger = 7;
  24572. ActionManager._OnIntersectionEnterTrigger = 8;
  24573. ActionManager._OnIntersectionExitTrigger = 9;
  24574. ActionManager._OnKeyDownTrigger = 10;
  24575. ActionManager._OnKeyUpTrigger = 11;
  24576. return ActionManager;
  24577. })();
  24578. BABYLON.ActionManager = ActionManager;
  24579. })(BABYLON || (BABYLON = {}));
  24580. //# sourceMappingURL=babylon.actionManager.js.map
  24581. var BABYLON;
  24582. (function (BABYLON) {
  24583. var InterpolateValueAction = (function (_super) {
  24584. __extends(InterpolateValueAction, _super);
  24585. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24586. if (duration === void 0) { duration = 1000; }
  24587. _super.call(this, triggerOptions, condition);
  24588. this.propertyPath = propertyPath;
  24589. this.value = value;
  24590. this.duration = duration;
  24591. this.stopOtherAnimations = stopOtherAnimations;
  24592. this._target = target;
  24593. }
  24594. InterpolateValueAction.prototype._prepare = function () {
  24595. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24596. this._property = this._getProperty(this.propertyPath);
  24597. };
  24598. InterpolateValueAction.prototype.execute = function () {
  24599. var scene = this._actionManager.getScene();
  24600. var keys = [
  24601. {
  24602. frame: 0,
  24603. value: this._target[this._property]
  24604. },
  24605. {
  24606. frame: 100,
  24607. value: this.value
  24608. }
  24609. ];
  24610. var dataType;
  24611. if (typeof this.value === "number") {
  24612. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24613. }
  24614. else if (this.value instanceof BABYLON.Color3) {
  24615. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24616. }
  24617. else if (this.value instanceof BABYLON.Vector3) {
  24618. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24619. }
  24620. else if (this.value instanceof BABYLON.Matrix) {
  24621. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24622. }
  24623. else if (this.value instanceof BABYLON.Quaternion) {
  24624. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24625. }
  24626. else {
  24627. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24628. return;
  24629. }
  24630. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24631. animation.setKeys(keys);
  24632. if (this.stopOtherAnimations) {
  24633. scene.stopAnimation(this._target);
  24634. }
  24635. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24636. };
  24637. return InterpolateValueAction;
  24638. })(BABYLON.Action);
  24639. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24640. })(BABYLON || (BABYLON = {}));
  24641. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24642. var BABYLON;
  24643. (function (BABYLON) {
  24644. var SwitchBooleanAction = (function (_super) {
  24645. __extends(SwitchBooleanAction, _super);
  24646. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24647. _super.call(this, triggerOptions, condition);
  24648. this.propertyPath = propertyPath;
  24649. this._target = target;
  24650. }
  24651. SwitchBooleanAction.prototype._prepare = function () {
  24652. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24653. this._property = this._getProperty(this.propertyPath);
  24654. };
  24655. SwitchBooleanAction.prototype.execute = function () {
  24656. this._target[this._property] = !this._target[this._property];
  24657. };
  24658. return SwitchBooleanAction;
  24659. })(BABYLON.Action);
  24660. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24661. var SetStateAction = (function (_super) {
  24662. __extends(SetStateAction, _super);
  24663. function SetStateAction(triggerOptions, target, value, condition) {
  24664. _super.call(this, triggerOptions, condition);
  24665. this.value = value;
  24666. this._target = target;
  24667. }
  24668. SetStateAction.prototype.execute = function () {
  24669. this._target.state = this.value;
  24670. };
  24671. return SetStateAction;
  24672. })(BABYLON.Action);
  24673. BABYLON.SetStateAction = SetStateAction;
  24674. var SetValueAction = (function (_super) {
  24675. __extends(SetValueAction, _super);
  24676. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24677. _super.call(this, triggerOptions, condition);
  24678. this.propertyPath = propertyPath;
  24679. this.value = value;
  24680. this._target = target;
  24681. }
  24682. SetValueAction.prototype._prepare = function () {
  24683. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24684. this._property = this._getProperty(this.propertyPath);
  24685. };
  24686. SetValueAction.prototype.execute = function () {
  24687. this._target[this._property] = this.value;
  24688. };
  24689. return SetValueAction;
  24690. })(BABYLON.Action);
  24691. BABYLON.SetValueAction = SetValueAction;
  24692. var IncrementValueAction = (function (_super) {
  24693. __extends(IncrementValueAction, _super);
  24694. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24695. _super.call(this, triggerOptions, condition);
  24696. this.propertyPath = propertyPath;
  24697. this.value = value;
  24698. this._target = target;
  24699. }
  24700. IncrementValueAction.prototype._prepare = function () {
  24701. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24702. this._property = this._getProperty(this.propertyPath);
  24703. if (typeof this._target[this._property] !== "number") {
  24704. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24705. }
  24706. };
  24707. IncrementValueAction.prototype.execute = function () {
  24708. this._target[this._property] += this.value;
  24709. };
  24710. return IncrementValueAction;
  24711. })(BABYLON.Action);
  24712. BABYLON.IncrementValueAction = IncrementValueAction;
  24713. var PlayAnimationAction = (function (_super) {
  24714. __extends(PlayAnimationAction, _super);
  24715. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24716. _super.call(this, triggerOptions, condition);
  24717. this.from = from;
  24718. this.to = to;
  24719. this.loop = loop;
  24720. this._target = target;
  24721. }
  24722. PlayAnimationAction.prototype._prepare = function () {
  24723. };
  24724. PlayAnimationAction.prototype.execute = function () {
  24725. var scene = this._actionManager.getScene();
  24726. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24727. };
  24728. return PlayAnimationAction;
  24729. })(BABYLON.Action);
  24730. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24731. var StopAnimationAction = (function (_super) {
  24732. __extends(StopAnimationAction, _super);
  24733. function StopAnimationAction(triggerOptions, target, condition) {
  24734. _super.call(this, triggerOptions, condition);
  24735. this._target = target;
  24736. }
  24737. StopAnimationAction.prototype._prepare = function () {
  24738. };
  24739. StopAnimationAction.prototype.execute = function () {
  24740. var scene = this._actionManager.getScene();
  24741. scene.stopAnimation(this._target);
  24742. };
  24743. return StopAnimationAction;
  24744. })(BABYLON.Action);
  24745. BABYLON.StopAnimationAction = StopAnimationAction;
  24746. var DoNothingAction = (function (_super) {
  24747. __extends(DoNothingAction, _super);
  24748. function DoNothingAction(triggerOptions, condition) {
  24749. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24750. _super.call(this, triggerOptions, condition);
  24751. }
  24752. DoNothingAction.prototype.execute = function () {
  24753. };
  24754. return DoNothingAction;
  24755. })(BABYLON.Action);
  24756. BABYLON.DoNothingAction = DoNothingAction;
  24757. var CombineAction = (function (_super) {
  24758. __extends(CombineAction, _super);
  24759. function CombineAction(triggerOptions, children, condition) {
  24760. _super.call(this, triggerOptions, condition);
  24761. this.children = children;
  24762. }
  24763. CombineAction.prototype._prepare = function () {
  24764. for (var index = 0; index < this.children.length; index++) {
  24765. this.children[index]._actionManager = this._actionManager;
  24766. this.children[index]._prepare();
  24767. }
  24768. };
  24769. CombineAction.prototype.execute = function (evt) {
  24770. for (var index = 0; index < this.children.length; index++) {
  24771. this.children[index].execute(evt);
  24772. }
  24773. };
  24774. return CombineAction;
  24775. })(BABYLON.Action);
  24776. BABYLON.CombineAction = CombineAction;
  24777. var ExecuteCodeAction = (function (_super) {
  24778. __extends(ExecuteCodeAction, _super);
  24779. function ExecuteCodeAction(triggerOptions, func, condition) {
  24780. _super.call(this, triggerOptions, condition);
  24781. this.func = func;
  24782. }
  24783. ExecuteCodeAction.prototype.execute = function (evt) {
  24784. this.func(evt);
  24785. };
  24786. return ExecuteCodeAction;
  24787. })(BABYLON.Action);
  24788. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24789. var SetParentAction = (function (_super) {
  24790. __extends(SetParentAction, _super);
  24791. function SetParentAction(triggerOptions, target, parent, condition) {
  24792. _super.call(this, triggerOptions, condition);
  24793. this._target = target;
  24794. this._parent = parent;
  24795. }
  24796. SetParentAction.prototype._prepare = function () {
  24797. };
  24798. SetParentAction.prototype.execute = function () {
  24799. if (this._target.parent === this._parent) {
  24800. return;
  24801. }
  24802. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24803. invertParentWorldMatrix.invert();
  24804. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24805. this._target.parent = this._parent;
  24806. };
  24807. return SetParentAction;
  24808. })(BABYLON.Action);
  24809. BABYLON.SetParentAction = SetParentAction;
  24810. var PlaySoundAction = (function (_super) {
  24811. __extends(PlaySoundAction, _super);
  24812. function PlaySoundAction(triggerOptions, sound, condition) {
  24813. _super.call(this, triggerOptions, condition);
  24814. this._sound = sound;
  24815. }
  24816. PlaySoundAction.prototype._prepare = function () {
  24817. };
  24818. PlaySoundAction.prototype.execute = function () {
  24819. if (this._sound !== undefined)
  24820. this._sound.play();
  24821. };
  24822. return PlaySoundAction;
  24823. })(BABYLON.Action);
  24824. BABYLON.PlaySoundAction = PlaySoundAction;
  24825. var StopSoundAction = (function (_super) {
  24826. __extends(StopSoundAction, _super);
  24827. function StopSoundAction(triggerOptions, sound, condition) {
  24828. _super.call(this, triggerOptions, condition);
  24829. this._sound = sound;
  24830. }
  24831. StopSoundAction.prototype._prepare = function () {
  24832. };
  24833. StopSoundAction.prototype.execute = function () {
  24834. if (this._sound !== undefined)
  24835. this._sound.stop();
  24836. };
  24837. return StopSoundAction;
  24838. })(BABYLON.Action);
  24839. BABYLON.StopSoundAction = StopSoundAction;
  24840. })(BABYLON || (BABYLON = {}));
  24841. //# sourceMappingURL=babylon.directActions.js.map
  24842. var BABYLON;
  24843. (function (BABYLON) {
  24844. var Geometry = (function () {
  24845. function Geometry(id, scene, vertexData, updatable, mesh) {
  24846. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24847. this._totalVertices = 0;
  24848. this._indices = [];
  24849. this.id = id;
  24850. this._engine = scene.getEngine();
  24851. this._meshes = [];
  24852. this._scene = scene;
  24853. // vertexData
  24854. if (vertexData) {
  24855. this.setAllVerticesData(vertexData, updatable);
  24856. }
  24857. else {
  24858. this._totalVertices = 0;
  24859. this._indices = [];
  24860. }
  24861. // applyToMesh
  24862. if (mesh) {
  24863. this.applyToMesh(mesh);
  24864. mesh.computeWorldMatrix(true);
  24865. }
  24866. }
  24867. Geometry.prototype.getScene = function () {
  24868. return this._scene;
  24869. };
  24870. Geometry.prototype.getEngine = function () {
  24871. return this._engine;
  24872. };
  24873. Geometry.prototype.isReady = function () {
  24874. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24875. };
  24876. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24877. vertexData.applyToGeometry(this, updatable);
  24878. };
  24879. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24880. this._vertexBuffers = this._vertexBuffers || {};
  24881. if (this._vertexBuffers[kind]) {
  24882. this._vertexBuffers[kind].dispose();
  24883. }
  24884. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24885. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24886. stride = this._vertexBuffers[kind].getStrideSize();
  24887. this._totalVertices = data.length / stride;
  24888. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24889. var meshes = this._meshes;
  24890. var numOfMeshes = meshes.length;
  24891. for (var index = 0; index < numOfMeshes; index++) {
  24892. var mesh = meshes[index];
  24893. mesh._resetPointsArrayCache();
  24894. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24895. mesh._createGlobalSubMesh();
  24896. mesh.computeWorldMatrix(true);
  24897. }
  24898. }
  24899. };
  24900. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24901. var vertexBuffer = this.getVertexBuffer(kind);
  24902. if (!vertexBuffer) {
  24903. return;
  24904. }
  24905. vertexBuffer.updateDirectly(data, offset);
  24906. };
  24907. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24908. var vertexBuffer = this.getVertexBuffer(kind);
  24909. if (!vertexBuffer) {
  24910. return;
  24911. }
  24912. vertexBuffer.update(data);
  24913. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24914. var extend;
  24915. var stride = vertexBuffer.getStrideSize();
  24916. this._totalVertices = data.length / stride;
  24917. if (updateExtends) {
  24918. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24919. }
  24920. var meshes = this._meshes;
  24921. var numOfMeshes = meshes.length;
  24922. for (var index = 0; index < numOfMeshes; index++) {
  24923. var mesh = meshes[index];
  24924. mesh._resetPointsArrayCache();
  24925. if (updateExtends) {
  24926. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24927. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24928. var subMesh = mesh.subMeshes[subIndex];
  24929. subMesh.refreshBoundingInfo();
  24930. }
  24931. }
  24932. }
  24933. }
  24934. };
  24935. Geometry.prototype.getTotalVertices = function () {
  24936. if (!this.isReady()) {
  24937. return 0;
  24938. }
  24939. return this._totalVertices;
  24940. };
  24941. Geometry.prototype.getVerticesData = function (kind) {
  24942. var vertexBuffer = this.getVertexBuffer(kind);
  24943. if (!vertexBuffer) {
  24944. return null;
  24945. }
  24946. return vertexBuffer.getData();
  24947. };
  24948. Geometry.prototype.getVertexBuffer = function (kind) {
  24949. if (!this.isReady()) {
  24950. return null;
  24951. }
  24952. return this._vertexBuffers[kind];
  24953. };
  24954. Geometry.prototype.getVertexBuffers = function () {
  24955. if (!this.isReady()) {
  24956. return null;
  24957. }
  24958. return this._vertexBuffers;
  24959. };
  24960. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24961. if (!this._vertexBuffers) {
  24962. if (this._delayInfo) {
  24963. return this._delayInfo.indexOf(kind) !== -1;
  24964. }
  24965. return false;
  24966. }
  24967. return this._vertexBuffers[kind] !== undefined;
  24968. };
  24969. Geometry.prototype.getVerticesDataKinds = function () {
  24970. var result = [];
  24971. if (!this._vertexBuffers && this._delayInfo) {
  24972. for (var kind in this._delayInfo) {
  24973. result.push(kind);
  24974. }
  24975. }
  24976. else {
  24977. for (kind in this._vertexBuffers) {
  24978. result.push(kind);
  24979. }
  24980. }
  24981. return result;
  24982. };
  24983. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24984. if (this._indexBuffer) {
  24985. this._engine._releaseBuffer(this._indexBuffer);
  24986. }
  24987. this._indices = indices;
  24988. if (this._meshes.length !== 0 && this._indices) {
  24989. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24990. }
  24991. if (totalVertices !== undefined) {
  24992. this._totalVertices = totalVertices;
  24993. }
  24994. var meshes = this._meshes;
  24995. var numOfMeshes = meshes.length;
  24996. for (var index = 0; index < numOfMeshes; index++) {
  24997. meshes[index]._createGlobalSubMesh();
  24998. }
  24999. };
  25000. Geometry.prototype.getTotalIndices = function () {
  25001. if (!this.isReady()) {
  25002. return 0;
  25003. }
  25004. return this._indices.length;
  25005. };
  25006. Geometry.prototype.getIndices = function () {
  25007. if (!this.isReady()) {
  25008. return null;
  25009. }
  25010. return this._indices;
  25011. };
  25012. Geometry.prototype.getIndexBuffer = function () {
  25013. if (!this.isReady()) {
  25014. return null;
  25015. }
  25016. return this._indexBuffer;
  25017. };
  25018. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  25019. var meshes = this._meshes;
  25020. var index = meshes.indexOf(mesh);
  25021. if (index === -1) {
  25022. return;
  25023. }
  25024. for (var kind in this._vertexBuffers) {
  25025. this._vertexBuffers[kind].dispose();
  25026. }
  25027. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  25028. this._indexBuffer = null;
  25029. }
  25030. meshes.splice(index, 1);
  25031. mesh._geometry = null;
  25032. if (meshes.length === 0 && shouldDispose) {
  25033. this.dispose();
  25034. }
  25035. };
  25036. Geometry.prototype.applyToMesh = function (mesh) {
  25037. if (mesh._geometry === this) {
  25038. return;
  25039. }
  25040. var previousGeometry = mesh._geometry;
  25041. if (previousGeometry) {
  25042. previousGeometry.releaseForMesh(mesh);
  25043. }
  25044. var meshes = this._meshes;
  25045. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  25046. mesh._geometry = this;
  25047. this._scene.pushGeometry(this);
  25048. meshes.push(mesh);
  25049. if (this.isReady()) {
  25050. this._applyToMesh(mesh);
  25051. }
  25052. else {
  25053. mesh._boundingInfo = this._boundingInfo;
  25054. }
  25055. };
  25056. Geometry.prototype._applyToMesh = function (mesh) {
  25057. var numOfMeshes = this._meshes.length;
  25058. for (var kind in this._vertexBuffers) {
  25059. if (numOfMeshes === 1) {
  25060. this._vertexBuffers[kind].create();
  25061. }
  25062. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  25063. if (kind === BABYLON.VertexBuffer.PositionKind) {
  25064. mesh._resetPointsArrayCache();
  25065. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  25066. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25067. mesh._createGlobalSubMesh();
  25068. //bounding info was just created again, world matrix should be applied again.
  25069. mesh._updateBoundingInfo();
  25070. }
  25071. }
  25072. // indexBuffer
  25073. if (numOfMeshes === 1 && this._indices) {
  25074. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  25075. }
  25076. if (this._indexBuffer) {
  25077. this._indexBuffer.references = numOfMeshes;
  25078. }
  25079. };
  25080. Geometry.prototype.load = function (scene, onLoaded) {
  25081. var _this = this;
  25082. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25083. return;
  25084. }
  25085. if (this.isReady()) {
  25086. if (onLoaded) {
  25087. onLoaded();
  25088. }
  25089. return;
  25090. }
  25091. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  25092. scene._addPendingData(this);
  25093. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  25094. _this._delayLoadingFunction(JSON.parse(data), _this);
  25095. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  25096. _this._delayInfo = [];
  25097. scene._removePendingData(_this);
  25098. var meshes = _this._meshes;
  25099. var numOfMeshes = meshes.length;
  25100. for (var index = 0; index < numOfMeshes; index++) {
  25101. _this._applyToMesh(meshes[index]);
  25102. }
  25103. if (onLoaded) {
  25104. onLoaded();
  25105. }
  25106. }, function () {
  25107. }, scene.database);
  25108. };
  25109. Geometry.prototype.dispose = function () {
  25110. var meshes = this._meshes;
  25111. var numOfMeshes = meshes.length;
  25112. var index;
  25113. for (index = 0; index < numOfMeshes; index++) {
  25114. this.releaseForMesh(meshes[index]);
  25115. }
  25116. this._meshes = [];
  25117. for (var kind in this._vertexBuffers) {
  25118. this._vertexBuffers[kind].dispose();
  25119. }
  25120. this._vertexBuffers = [];
  25121. this._totalVertices = 0;
  25122. if (this._indexBuffer) {
  25123. this._engine._releaseBuffer(this._indexBuffer);
  25124. }
  25125. this._indexBuffer = null;
  25126. this._indices = [];
  25127. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  25128. this.delayLoadingFile = null;
  25129. this._delayLoadingFunction = null;
  25130. this._delayInfo = [];
  25131. this._boundingInfo = null; // todo: .dispose()
  25132. var geometries = this._scene.getGeometries();
  25133. index = geometries.indexOf(this);
  25134. if (index > -1) {
  25135. geometries.splice(index, 1);
  25136. }
  25137. };
  25138. Geometry.prototype.copy = function (id) {
  25139. var vertexData = new BABYLON.VertexData();
  25140. vertexData.indices = [];
  25141. var indices = this.getIndices();
  25142. for (var index = 0; index < indices.length; index++) {
  25143. vertexData.indices.push(indices[index]);
  25144. }
  25145. var updatable = false;
  25146. var stopChecking = false;
  25147. for (var kind in this._vertexBuffers) {
  25148. // using slice() to make a copy of the array and not just reference it
  25149. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  25150. if (!stopChecking) {
  25151. updatable = this.getVertexBuffer(kind).isUpdatable();
  25152. stopChecking = !updatable;
  25153. }
  25154. }
  25155. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  25156. geometry.delayLoadState = this.delayLoadState;
  25157. geometry.delayLoadingFile = this.delayLoadingFile;
  25158. geometry._delayLoadingFunction = this._delayLoadingFunction;
  25159. for (kind in this._delayInfo) {
  25160. geometry._delayInfo = geometry._delayInfo || [];
  25161. geometry._delayInfo.push(kind);
  25162. }
  25163. // Bounding info
  25164. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  25165. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  25166. return geometry;
  25167. };
  25168. // Statics
  25169. Geometry.ExtractFromMesh = function (mesh, id) {
  25170. var geometry = mesh._geometry;
  25171. if (!geometry) {
  25172. return null;
  25173. }
  25174. return geometry.copy(id);
  25175. };
  25176. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  25177. // be aware Math.random() could cause collisions
  25178. Geometry.RandomId = function () {
  25179. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  25180. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  25181. return v.toString(16);
  25182. });
  25183. };
  25184. return Geometry;
  25185. })();
  25186. BABYLON.Geometry = Geometry;
  25187. /////// Primitives //////////////////////////////////////////////
  25188. var Geometry;
  25189. (function (Geometry) {
  25190. var Primitives;
  25191. (function (Primitives) {
  25192. /// Abstract class
  25193. var _Primitive = (function (_super) {
  25194. __extends(_Primitive, _super);
  25195. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  25196. this._beingRegenerated = true;
  25197. this._canBeRegenerated = canBeRegenerated;
  25198. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  25199. this._beingRegenerated = false;
  25200. }
  25201. _Primitive.prototype.canBeRegenerated = function () {
  25202. return this._canBeRegenerated;
  25203. };
  25204. _Primitive.prototype.regenerate = function () {
  25205. if (!this._canBeRegenerated) {
  25206. return;
  25207. }
  25208. this._beingRegenerated = true;
  25209. this.setAllVerticesData(this._regenerateVertexData(), false);
  25210. this._beingRegenerated = false;
  25211. };
  25212. _Primitive.prototype.asNewGeometry = function (id) {
  25213. return _super.prototype.copy.call(this, id);
  25214. };
  25215. // overrides
  25216. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  25217. if (!this._beingRegenerated) {
  25218. return;
  25219. }
  25220. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  25221. };
  25222. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  25223. if (!this._beingRegenerated) {
  25224. return;
  25225. }
  25226. _super.prototype.setVerticesData.call(this, kind, data, false);
  25227. };
  25228. // to override
  25229. // protected
  25230. _Primitive.prototype._regenerateVertexData = function () {
  25231. throw new Error("Abstract method");
  25232. };
  25233. _Primitive.prototype.copy = function (id) {
  25234. throw new Error("Must be overriden in sub-classes.");
  25235. };
  25236. return _Primitive;
  25237. })(Geometry);
  25238. Primitives._Primitive = _Primitive;
  25239. var Ribbon = (function (_super) {
  25240. __extends(Ribbon, _super);
  25241. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  25242. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25243. this.pathArray = pathArray;
  25244. this.closeArray = closeArray;
  25245. this.closePath = closePath;
  25246. this.offset = offset;
  25247. this.side = side;
  25248. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25249. }
  25250. Ribbon.prototype._regenerateVertexData = function () {
  25251. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  25252. };
  25253. Ribbon.prototype.copy = function (id) {
  25254. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  25255. };
  25256. return Ribbon;
  25257. })(_Primitive);
  25258. Primitives.Ribbon = Ribbon;
  25259. var Box = (function (_super) {
  25260. __extends(Box, _super);
  25261. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  25262. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25263. this.size = size;
  25264. this.side = side;
  25265. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25266. }
  25267. Box.prototype._regenerateVertexData = function () {
  25268. return BABYLON.VertexData.CreateBox(this.size, this.side);
  25269. };
  25270. Box.prototype.copy = function (id) {
  25271. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25272. };
  25273. return Box;
  25274. })(_Primitive);
  25275. Primitives.Box = Box;
  25276. var Sphere = (function (_super) {
  25277. __extends(Sphere, _super);
  25278. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  25279. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25280. this.segments = segments;
  25281. this.diameter = diameter;
  25282. this.side = side;
  25283. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25284. }
  25285. Sphere.prototype._regenerateVertexData = function () {
  25286. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  25287. };
  25288. Sphere.prototype.copy = function (id) {
  25289. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  25290. };
  25291. return Sphere;
  25292. })(_Primitive);
  25293. Primitives.Sphere = Sphere;
  25294. var Cylinder = (function (_super) {
  25295. __extends(Cylinder, _super);
  25296. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  25297. if (subdivisions === void 0) { subdivisions = 1; }
  25298. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25299. this.height = height;
  25300. this.diameterTop = diameterTop;
  25301. this.diameterBottom = diameterBottom;
  25302. this.tessellation = tessellation;
  25303. this.subdivisions = subdivisions;
  25304. this.side = side;
  25305. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25306. }
  25307. Cylinder.prototype._regenerateVertexData = function () {
  25308. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  25309. };
  25310. Cylinder.prototype.copy = function (id) {
  25311. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  25312. };
  25313. return Cylinder;
  25314. })(_Primitive);
  25315. Primitives.Cylinder = Cylinder;
  25316. var Torus = (function (_super) {
  25317. __extends(Torus, _super);
  25318. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  25319. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25320. this.diameter = diameter;
  25321. this.thickness = thickness;
  25322. this.tessellation = tessellation;
  25323. this.side = side;
  25324. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25325. }
  25326. Torus.prototype._regenerateVertexData = function () {
  25327. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  25328. };
  25329. Torus.prototype.copy = function (id) {
  25330. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  25331. };
  25332. return Torus;
  25333. })(_Primitive);
  25334. Primitives.Torus = Torus;
  25335. var Ground = (function (_super) {
  25336. __extends(Ground, _super);
  25337. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  25338. this.width = width;
  25339. this.height = height;
  25340. this.subdivisions = subdivisions;
  25341. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25342. }
  25343. Ground.prototype._regenerateVertexData = function () {
  25344. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  25345. };
  25346. Ground.prototype.copy = function (id) {
  25347. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  25348. };
  25349. return Ground;
  25350. })(_Primitive);
  25351. Primitives.Ground = Ground;
  25352. var TiledGround = (function (_super) {
  25353. __extends(TiledGround, _super);
  25354. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  25355. this.xmin = xmin;
  25356. this.zmin = zmin;
  25357. this.xmax = xmax;
  25358. this.zmax = zmax;
  25359. this.subdivisions = subdivisions;
  25360. this.precision = precision;
  25361. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25362. }
  25363. TiledGround.prototype._regenerateVertexData = function () {
  25364. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25365. };
  25366. TiledGround.prototype.copy = function (id) {
  25367. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25368. };
  25369. return TiledGround;
  25370. })(_Primitive);
  25371. Primitives.TiledGround = TiledGround;
  25372. var Plane = (function (_super) {
  25373. __extends(Plane, _super);
  25374. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25375. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25376. this.size = size;
  25377. this.side = side;
  25378. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25379. }
  25380. Plane.prototype._regenerateVertexData = function () {
  25381. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25382. };
  25383. Plane.prototype.copy = function (id) {
  25384. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25385. };
  25386. return Plane;
  25387. })(_Primitive);
  25388. Primitives.Plane = Plane;
  25389. var TorusKnot = (function (_super) {
  25390. __extends(TorusKnot, _super);
  25391. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25392. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25393. this.radius = radius;
  25394. this.tube = tube;
  25395. this.radialSegments = radialSegments;
  25396. this.tubularSegments = tubularSegments;
  25397. this.p = p;
  25398. this.q = q;
  25399. this.side = side;
  25400. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25401. }
  25402. TorusKnot.prototype._regenerateVertexData = function () {
  25403. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25404. };
  25405. TorusKnot.prototype.copy = function (id) {
  25406. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25407. };
  25408. return TorusKnot;
  25409. })(_Primitive);
  25410. Primitives.TorusKnot = TorusKnot;
  25411. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25412. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25413. })(BABYLON || (BABYLON = {}));
  25414. //# sourceMappingURL=babylon.geometry.js.map
  25415. var BABYLON;
  25416. (function (BABYLON) {
  25417. var Gamepads = (function () {
  25418. function Gamepads(ongamedpadconnected) {
  25419. var _this = this;
  25420. this.babylonGamepads = [];
  25421. this.oneGamepadConnected = false;
  25422. this.isMonitoring = false;
  25423. this.gamepadEventSupported = 'GamepadEvent' in window;
  25424. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25425. 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=";
  25426. this._callbackGamepadConnected = ongamedpadconnected;
  25427. if (this.gamepadSupportAvailable) {
  25428. // Checking if the gamepad connected event is supported (like in Firefox)
  25429. if (this.gamepadEventSupported) {
  25430. window.addEventListener('gamepadconnected', function (evt) {
  25431. _this._onGamepadConnected(evt);
  25432. }, false);
  25433. window.addEventListener('gamepaddisconnected', function (evt) {
  25434. _this._onGamepadDisconnected(evt);
  25435. }, false);
  25436. }
  25437. else {
  25438. this._startMonitoringGamepads();
  25439. }
  25440. if (!this.oneGamepadConnected) {
  25441. this._insertGamepadDOMInstructions();
  25442. }
  25443. }
  25444. else {
  25445. this._insertGamepadDOMNotSupported();
  25446. }
  25447. }
  25448. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25449. Gamepads.gamepadDOMInfo = document.createElement("div");
  25450. var buttonAImage = document.createElement("img");
  25451. buttonAImage.src = this.buttonADataURL;
  25452. var spanMessage = document.createElement("span");
  25453. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25454. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25455. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25456. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25457. Gamepads.gamepadDOMInfo.style.width = "100%";
  25458. Gamepads.gamepadDOMInfo.style.height = "48px";
  25459. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25460. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25461. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25462. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25463. buttonAImage.style.position = "relative";
  25464. buttonAImage.style.bottom = "8px";
  25465. spanMessage.style.position = "relative";
  25466. spanMessage.style.fontSize = "32px";
  25467. spanMessage.style.bottom = "32px";
  25468. spanMessage.style.color = "green";
  25469. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25470. };
  25471. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25472. Gamepads.gamepadDOMInfo = document.createElement("div");
  25473. var spanMessage = document.createElement("span");
  25474. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25475. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25476. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25477. Gamepads.gamepadDOMInfo.style.width = "100%";
  25478. Gamepads.gamepadDOMInfo.style.height = "40px";
  25479. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25480. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25481. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25482. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25483. spanMessage.style.position = "relative";
  25484. spanMessage.style.fontSize = "32px";
  25485. spanMessage.style.color = "red";
  25486. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25487. };
  25488. Gamepads.prototype.dispose = function () {
  25489. if (Gamepads.gamepadDOMInfo) {
  25490. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25491. }
  25492. };
  25493. Gamepads.prototype._onGamepadConnected = function (evt) {
  25494. var newGamepad = this._addNewGamepad(evt.gamepad);
  25495. if (this._callbackGamepadConnected)
  25496. this._callbackGamepadConnected(newGamepad);
  25497. this._startMonitoringGamepads();
  25498. };
  25499. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25500. if (!this.oneGamepadConnected) {
  25501. this.oneGamepadConnected = true;
  25502. if (Gamepads.gamepadDOMInfo) {
  25503. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25504. Gamepads.gamepadDOMInfo = null;
  25505. }
  25506. }
  25507. var newGamepad;
  25508. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25509. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25510. }
  25511. else {
  25512. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25513. }
  25514. this.babylonGamepads.push(newGamepad);
  25515. return newGamepad;
  25516. };
  25517. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25518. for (var i in this.babylonGamepads) {
  25519. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25520. this.babylonGamepads.splice(i, 1);
  25521. break;
  25522. }
  25523. }
  25524. // If no gamepads are left, stop the polling loop.
  25525. if (this.babylonGamepads.length == 0) {
  25526. this._stopMonitoringGamepads();
  25527. }
  25528. };
  25529. Gamepads.prototype._startMonitoringGamepads = function () {
  25530. if (!this.isMonitoring) {
  25531. this.isMonitoring = true;
  25532. this._checkGamepadsStatus();
  25533. }
  25534. };
  25535. Gamepads.prototype._stopMonitoringGamepads = function () {
  25536. this.isMonitoring = false;
  25537. };
  25538. Gamepads.prototype._checkGamepadsStatus = function () {
  25539. var _this = this;
  25540. // updating gamepad objects
  25541. this._updateGamepadObjects();
  25542. for (var i in this.babylonGamepads) {
  25543. this.babylonGamepads[i].update();
  25544. }
  25545. if (this.isMonitoring) {
  25546. if (window.requestAnimationFrame) {
  25547. window.requestAnimationFrame(function () {
  25548. _this._checkGamepadsStatus();
  25549. });
  25550. }
  25551. else if (window.mozRequestAnimationFrame) {
  25552. window.mozRequestAnimationFrame(function () {
  25553. _this._checkGamepadsStatus();
  25554. });
  25555. }
  25556. else if (window.webkitRequestAnimationFrame) {
  25557. window.webkitRequestAnimationFrame(function () {
  25558. _this._checkGamepadsStatus();
  25559. });
  25560. }
  25561. }
  25562. };
  25563. // This function is called only on Chrome, which does not yet support
  25564. // connection/disconnection events, but requires you to monitor
  25565. // an array for changes.
  25566. Gamepads.prototype._updateGamepadObjects = function () {
  25567. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25568. for (var i = 0; i < gamepads.length; i++) {
  25569. if (gamepads[i]) {
  25570. if (!(gamepads[i].index in this.babylonGamepads)) {
  25571. var newGamepad = this._addNewGamepad(gamepads[i]);
  25572. if (this._callbackGamepadConnected) {
  25573. this._callbackGamepadConnected(newGamepad);
  25574. }
  25575. }
  25576. else {
  25577. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25578. }
  25579. }
  25580. }
  25581. };
  25582. return Gamepads;
  25583. })();
  25584. BABYLON.Gamepads = Gamepads;
  25585. var StickValues = (function () {
  25586. function StickValues(x, y) {
  25587. this.x = x;
  25588. this.y = y;
  25589. }
  25590. return StickValues;
  25591. })();
  25592. BABYLON.StickValues = StickValues;
  25593. var Gamepad = (function () {
  25594. function Gamepad(id, index, browserGamepad) {
  25595. this.id = id;
  25596. this.index = index;
  25597. this.browserGamepad = browserGamepad;
  25598. if (this.browserGamepad.axes.length >= 2) {
  25599. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25600. }
  25601. if (this.browserGamepad.axes.length >= 4) {
  25602. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25603. }
  25604. }
  25605. Gamepad.prototype.onleftstickchanged = function (callback) {
  25606. this._onleftstickchanged = callback;
  25607. };
  25608. Gamepad.prototype.onrightstickchanged = function (callback) {
  25609. this._onrightstickchanged = callback;
  25610. };
  25611. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25612. get: function () {
  25613. return this._leftStick;
  25614. },
  25615. set: function (newValues) {
  25616. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25617. this._onleftstickchanged(newValues);
  25618. }
  25619. this._leftStick = newValues;
  25620. },
  25621. enumerable: true,
  25622. configurable: true
  25623. });
  25624. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25625. get: function () {
  25626. return this._rightStick;
  25627. },
  25628. set: function (newValues) {
  25629. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25630. this._onrightstickchanged(newValues);
  25631. }
  25632. this._rightStick = newValues;
  25633. },
  25634. enumerable: true,
  25635. configurable: true
  25636. });
  25637. Gamepad.prototype.update = function () {
  25638. if (this._leftStick) {
  25639. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25640. }
  25641. if (this._rightStick) {
  25642. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25643. }
  25644. };
  25645. return Gamepad;
  25646. })();
  25647. BABYLON.Gamepad = Gamepad;
  25648. var GenericPad = (function (_super) {
  25649. __extends(GenericPad, _super);
  25650. function GenericPad(id, index, gamepad) {
  25651. _super.call(this, id, index, gamepad);
  25652. this.id = id;
  25653. this.index = index;
  25654. this.gamepad = gamepad;
  25655. this._buttons = new Array(gamepad.buttons.length);
  25656. }
  25657. GenericPad.prototype.onbuttondown = function (callback) {
  25658. this._onbuttondown = callback;
  25659. };
  25660. GenericPad.prototype.onbuttonup = function (callback) {
  25661. this._onbuttonup = callback;
  25662. };
  25663. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25664. if (newValue !== currentValue) {
  25665. if (this._onbuttondown && newValue === 1) {
  25666. this._onbuttondown(buttonIndex);
  25667. }
  25668. if (this._onbuttonup && newValue === 0) {
  25669. this._onbuttonup(buttonIndex);
  25670. }
  25671. }
  25672. return newValue;
  25673. };
  25674. GenericPad.prototype.update = function () {
  25675. _super.prototype.update.call(this);
  25676. for (var index = 0; index < this._buttons.length; index++) {
  25677. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25678. }
  25679. };
  25680. return GenericPad;
  25681. })(Gamepad);
  25682. BABYLON.GenericPad = GenericPad;
  25683. (function (Xbox360Button) {
  25684. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25685. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25686. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25687. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25688. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25689. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25690. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25691. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25692. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25693. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25694. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25695. var Xbox360Button = BABYLON.Xbox360Button;
  25696. (function (Xbox360Dpad) {
  25697. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25698. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25699. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25700. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25701. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25702. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25703. var Xbox360Pad = (function (_super) {
  25704. __extends(Xbox360Pad, _super);
  25705. function Xbox360Pad() {
  25706. _super.apply(this, arguments);
  25707. this._leftTrigger = 0;
  25708. this._rightTrigger = 0;
  25709. this._buttonA = 0;
  25710. this._buttonB = 0;
  25711. this._buttonX = 0;
  25712. this._buttonY = 0;
  25713. this._buttonBack = 0;
  25714. this._buttonStart = 0;
  25715. this._buttonLB = 0;
  25716. this._buttonRB = 0;
  25717. this._buttonLeftStick = 0;
  25718. this._buttonRightStick = 0;
  25719. this._dPadUp = 0;
  25720. this._dPadDown = 0;
  25721. this._dPadLeft = 0;
  25722. this._dPadRight = 0;
  25723. }
  25724. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25725. this._onlefttriggerchanged = callback;
  25726. };
  25727. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25728. this._onrighttriggerchanged = callback;
  25729. };
  25730. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25731. get: function () {
  25732. return this._leftTrigger;
  25733. },
  25734. set: function (newValue) {
  25735. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25736. this._onlefttriggerchanged(newValue);
  25737. }
  25738. this._leftTrigger = newValue;
  25739. },
  25740. enumerable: true,
  25741. configurable: true
  25742. });
  25743. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25744. get: function () {
  25745. return this._rightTrigger;
  25746. },
  25747. set: function (newValue) {
  25748. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25749. this._onrighttriggerchanged(newValue);
  25750. }
  25751. this._rightTrigger = newValue;
  25752. },
  25753. enumerable: true,
  25754. configurable: true
  25755. });
  25756. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25757. this._onbuttondown = callback;
  25758. };
  25759. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25760. this._onbuttonup = callback;
  25761. };
  25762. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25763. this._ondpaddown = callback;
  25764. };
  25765. Xbox360Pad.prototype.ondpadup = function (callback) {
  25766. this._ondpadup = callback;
  25767. };
  25768. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25769. if (newValue !== currentValue) {
  25770. if (this._onbuttondown && newValue === 1) {
  25771. this._onbuttondown(buttonType);
  25772. }
  25773. if (this._onbuttonup && newValue === 0) {
  25774. this._onbuttonup(buttonType);
  25775. }
  25776. }
  25777. return newValue;
  25778. };
  25779. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25780. if (newValue !== currentValue) {
  25781. if (this._ondpaddown && newValue === 1) {
  25782. this._ondpaddown(buttonType);
  25783. }
  25784. if (this._ondpadup && newValue === 0) {
  25785. this._ondpadup(buttonType);
  25786. }
  25787. }
  25788. return newValue;
  25789. };
  25790. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25791. get: function () {
  25792. return this._buttonA;
  25793. },
  25794. set: function (value) {
  25795. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25796. },
  25797. enumerable: true,
  25798. configurable: true
  25799. });
  25800. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25801. get: function () {
  25802. return this._buttonB;
  25803. },
  25804. set: function (value) {
  25805. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25806. },
  25807. enumerable: true,
  25808. configurable: true
  25809. });
  25810. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25811. get: function () {
  25812. return this._buttonX;
  25813. },
  25814. set: function (value) {
  25815. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25816. },
  25817. enumerable: true,
  25818. configurable: true
  25819. });
  25820. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25821. get: function () {
  25822. return this._buttonY;
  25823. },
  25824. set: function (value) {
  25825. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25826. },
  25827. enumerable: true,
  25828. configurable: true
  25829. });
  25830. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25831. get: function () {
  25832. return this._buttonStart;
  25833. },
  25834. set: function (value) {
  25835. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25836. },
  25837. enumerable: true,
  25838. configurable: true
  25839. });
  25840. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25841. get: function () {
  25842. return this._buttonBack;
  25843. },
  25844. set: function (value) {
  25845. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25846. },
  25847. enumerable: true,
  25848. configurable: true
  25849. });
  25850. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25851. get: function () {
  25852. return this._buttonLB;
  25853. },
  25854. set: function (value) {
  25855. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25856. },
  25857. enumerable: true,
  25858. configurable: true
  25859. });
  25860. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25861. get: function () {
  25862. return this._buttonRB;
  25863. },
  25864. set: function (value) {
  25865. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25866. },
  25867. enumerable: true,
  25868. configurable: true
  25869. });
  25870. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25871. get: function () {
  25872. return this._buttonLeftStick;
  25873. },
  25874. set: function (value) {
  25875. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25876. },
  25877. enumerable: true,
  25878. configurable: true
  25879. });
  25880. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25881. get: function () {
  25882. return this._buttonRightStick;
  25883. },
  25884. set: function (value) {
  25885. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25891. get: function () {
  25892. return this._dPadUp;
  25893. },
  25894. set: function (value) {
  25895. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25896. },
  25897. enumerable: true,
  25898. configurable: true
  25899. });
  25900. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25901. get: function () {
  25902. return this._dPadDown;
  25903. },
  25904. set: function (value) {
  25905. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25906. },
  25907. enumerable: true,
  25908. configurable: true
  25909. });
  25910. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25911. get: function () {
  25912. return this._dPadLeft;
  25913. },
  25914. set: function (value) {
  25915. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25916. },
  25917. enumerable: true,
  25918. configurable: true
  25919. });
  25920. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25921. get: function () {
  25922. return this._dPadRight;
  25923. },
  25924. set: function (value) {
  25925. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25926. },
  25927. enumerable: true,
  25928. configurable: true
  25929. });
  25930. Xbox360Pad.prototype.update = function () {
  25931. _super.prototype.update.call(this);
  25932. this.buttonA = this.browserGamepad.buttons[0].value;
  25933. this.buttonB = this.browserGamepad.buttons[1].value;
  25934. this.buttonX = this.browserGamepad.buttons[2].value;
  25935. this.buttonY = this.browserGamepad.buttons[3].value;
  25936. this.buttonLB = this.browserGamepad.buttons[4].value;
  25937. this.buttonRB = this.browserGamepad.buttons[5].value;
  25938. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25939. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25940. this.buttonBack = this.browserGamepad.buttons[8].value;
  25941. this.buttonStart = this.browserGamepad.buttons[9].value;
  25942. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25943. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25944. this.dPadUp = this.browserGamepad.buttons[12].value;
  25945. this.dPadDown = this.browserGamepad.buttons[13].value;
  25946. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25947. this.dPadRight = this.browserGamepad.buttons[15].value;
  25948. };
  25949. return Xbox360Pad;
  25950. })(Gamepad);
  25951. BABYLON.Xbox360Pad = Xbox360Pad;
  25952. })(BABYLON || (BABYLON = {}));
  25953. //# sourceMappingURL=babylon.gamepads.js.map
  25954. var BABYLON;
  25955. (function (BABYLON) {
  25956. // We're mainly based on the logic defined into the FreeCamera code
  25957. var GamepadCamera = (function (_super) {
  25958. __extends(GamepadCamera, _super);
  25959. function GamepadCamera(name, position, scene) {
  25960. var _this = this;
  25961. _super.call(this, name, position, scene);
  25962. this.angularSensibility = 200;
  25963. this.moveSensibility = 75;
  25964. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25965. _this._onNewGameConnected(gamepad);
  25966. });
  25967. }
  25968. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25969. // Only the first gamepad can control the camera
  25970. if (gamepad.index === 0) {
  25971. this._gamepad = gamepad;
  25972. }
  25973. };
  25974. GamepadCamera.prototype._checkInputs = function () {
  25975. if (!this._gamepad) {
  25976. return;
  25977. }
  25978. var LSValues = this._gamepad.leftStick;
  25979. var normalizedLX = LSValues.x / this.moveSensibility;
  25980. var normalizedLY = LSValues.y / this.moveSensibility;
  25981. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25982. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25983. var RSValues = this._gamepad.rightStick;
  25984. var normalizedRX = RSValues.x / this.angularSensibility;
  25985. var normalizedRY = RSValues.y / this.angularSensibility;
  25986. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25987. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25988. ;
  25989. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25990. var speed = this._computeLocalCameraSpeed() * 50.0;
  25991. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25992. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25993. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25994. };
  25995. GamepadCamera.prototype.dispose = function () {
  25996. this._gamepads.dispose();
  25997. _super.prototype.dispose.call(this);
  25998. };
  25999. return GamepadCamera;
  26000. })(BABYLON.FreeCamera);
  26001. BABYLON.GamepadCamera = GamepadCamera;
  26002. })(BABYLON || (BABYLON = {}));
  26003. //# sourceMappingURL=babylon.gamepadCamera.js.map
  26004. var BABYLON;
  26005. (function (BABYLON) {
  26006. var LinesMesh = (function (_super) {
  26007. __extends(LinesMesh, _super);
  26008. function LinesMesh(name, scene, updatable) {
  26009. if (updatable === void 0) { updatable = false; }
  26010. _super.call(this, name, scene);
  26011. this.color = new BABYLON.Color3(1, 1, 1);
  26012. this.alpha = 1;
  26013. this._indices = new Array();
  26014. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  26015. attributes: ["position"],
  26016. uniforms: ["worldViewProjection", "color"],
  26017. needAlphaBlending: true
  26018. });
  26019. }
  26020. Object.defineProperty(LinesMesh.prototype, "material", {
  26021. get: function () {
  26022. return this._colorShader;
  26023. },
  26024. enumerable: true,
  26025. configurable: true
  26026. });
  26027. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  26028. get: function () {
  26029. return false;
  26030. },
  26031. enumerable: true,
  26032. configurable: true
  26033. });
  26034. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  26035. get: function () {
  26036. return false;
  26037. },
  26038. enumerable: true,
  26039. configurable: true
  26040. });
  26041. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  26042. var engine = this.getScene().getEngine();
  26043. var indexToBind = this._geometry.getIndexBuffer();
  26044. // VBOs
  26045. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  26046. // Color
  26047. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  26048. };
  26049. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  26050. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  26051. return;
  26052. }
  26053. var engine = this.getScene().getEngine();
  26054. // Draw order
  26055. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  26056. };
  26057. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  26058. return null;
  26059. };
  26060. LinesMesh.prototype.dispose = function (doNotRecurse) {
  26061. this._colorShader.dispose();
  26062. _super.prototype.dispose.call(this, doNotRecurse);
  26063. };
  26064. return LinesMesh;
  26065. })(BABYLON.Mesh);
  26066. BABYLON.LinesMesh = LinesMesh;
  26067. })(BABYLON || (BABYLON = {}));
  26068. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  26069. (function (BABYLON) {
  26070. var OutlineRenderer = (function () {
  26071. function OutlineRenderer(scene) {
  26072. this._scene = scene;
  26073. }
  26074. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  26075. var _this = this;
  26076. if (useOverlay === void 0) { useOverlay = false; }
  26077. var scene = this._scene;
  26078. var engine = this._scene.getEngine();
  26079. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  26080. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  26081. return;
  26082. }
  26083. var mesh = subMesh.getRenderingMesh();
  26084. var material = subMesh.getMaterial();
  26085. engine.enableEffect(this._effect);
  26086. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  26087. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  26088. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26089. // Bones
  26090. if (mesh.useBones) {
  26091. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  26092. }
  26093. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  26094. // Alpha test
  26095. if (material && material.needAlphaTesting()) {
  26096. var alphaTexture = material.getAlphaTestTexture();
  26097. this._effect.setTexture("diffuseSampler", alphaTexture);
  26098. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  26099. }
  26100. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  26101. _this._effect.setMatrix("world", world);
  26102. });
  26103. };
  26104. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  26105. var defines = [];
  26106. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  26107. var mesh = subMesh.getMesh();
  26108. var material = subMesh.getMaterial();
  26109. // Alpha test
  26110. if (material && material.needAlphaTesting()) {
  26111. defines.push("#define ALPHATEST");
  26112. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26113. attribs.push(BABYLON.VertexBuffer.UVKind);
  26114. defines.push("#define UV1");
  26115. }
  26116. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26117. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26118. defines.push("#define UV2");
  26119. }
  26120. }
  26121. // Bones
  26122. if (mesh.useBones) {
  26123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26125. defines.push("#define BONES");
  26126. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  26127. }
  26128. // Instances
  26129. if (useInstances) {
  26130. defines.push("#define INSTANCES");
  26131. attribs.push("world0");
  26132. attribs.push("world1");
  26133. attribs.push("world2");
  26134. attribs.push("world3");
  26135. }
  26136. // Get correct effect
  26137. var join = defines.join("\n");
  26138. if (this._cachedDefines !== join) {
  26139. this._cachedDefines = join;
  26140. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  26141. }
  26142. return this._effect.isReady();
  26143. };
  26144. return OutlineRenderer;
  26145. })();
  26146. BABYLON.OutlineRenderer = OutlineRenderer;
  26147. })(BABYLON || (BABYLON = {}));
  26148. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  26149. (function (BABYLON) {
  26150. var MeshAssetTask = (function () {
  26151. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  26152. this.name = name;
  26153. this.meshesNames = meshesNames;
  26154. this.rootUrl = rootUrl;
  26155. this.sceneFilename = sceneFilename;
  26156. this.isCompleted = false;
  26157. }
  26158. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26159. var _this = this;
  26160. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  26161. _this.loadedMeshes = meshes;
  26162. _this.loadedParticleSystems = particleSystems;
  26163. _this.loadedSkeletons = skeletons;
  26164. _this.isCompleted = true;
  26165. if (_this.onSuccess) {
  26166. _this.onSuccess(_this);
  26167. }
  26168. onSuccess();
  26169. }, null, function () {
  26170. if (_this.onError) {
  26171. _this.onError(_this);
  26172. }
  26173. onError();
  26174. });
  26175. };
  26176. return MeshAssetTask;
  26177. })();
  26178. BABYLON.MeshAssetTask = MeshAssetTask;
  26179. var TextFileAssetTask = (function () {
  26180. function TextFileAssetTask(name, url) {
  26181. this.name = name;
  26182. this.url = url;
  26183. this.isCompleted = false;
  26184. }
  26185. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26186. var _this = this;
  26187. BABYLON.Tools.LoadFile(this.url, function (data) {
  26188. _this.text = data;
  26189. _this.isCompleted = true;
  26190. if (_this.onSuccess) {
  26191. _this.onSuccess(_this);
  26192. }
  26193. onSuccess();
  26194. }, null, scene.database, false, function () {
  26195. if (_this.onError) {
  26196. _this.onError(_this);
  26197. }
  26198. onError();
  26199. });
  26200. };
  26201. return TextFileAssetTask;
  26202. })();
  26203. BABYLON.TextFileAssetTask = TextFileAssetTask;
  26204. var BinaryFileAssetTask = (function () {
  26205. function BinaryFileAssetTask(name, url) {
  26206. this.name = name;
  26207. this.url = url;
  26208. this.isCompleted = false;
  26209. }
  26210. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26211. var _this = this;
  26212. BABYLON.Tools.LoadFile(this.url, function (data) {
  26213. _this.data = data;
  26214. _this.isCompleted = true;
  26215. if (_this.onSuccess) {
  26216. _this.onSuccess(_this);
  26217. }
  26218. onSuccess();
  26219. }, null, scene.database, true, function () {
  26220. if (_this.onError) {
  26221. _this.onError(_this);
  26222. }
  26223. onError();
  26224. });
  26225. };
  26226. return BinaryFileAssetTask;
  26227. })();
  26228. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  26229. var ImageAssetTask = (function () {
  26230. function ImageAssetTask(name, url) {
  26231. this.name = name;
  26232. this.url = url;
  26233. this.isCompleted = false;
  26234. }
  26235. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26236. var _this = this;
  26237. var img = new Image();
  26238. img.onload = function () {
  26239. _this.image = img;
  26240. _this.isCompleted = true;
  26241. if (_this.onSuccess) {
  26242. _this.onSuccess(_this);
  26243. }
  26244. onSuccess();
  26245. };
  26246. img.onerror = function () {
  26247. if (_this.onError) {
  26248. _this.onError(_this);
  26249. }
  26250. onError();
  26251. };
  26252. img.src = this.url;
  26253. };
  26254. return ImageAssetTask;
  26255. })();
  26256. BABYLON.ImageAssetTask = ImageAssetTask;
  26257. var TextureAssetTask = (function () {
  26258. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  26259. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26260. this.name = name;
  26261. this.url = url;
  26262. this.noMipmap = noMipmap;
  26263. this.invertY = invertY;
  26264. this.samplingMode = samplingMode;
  26265. this.isCompleted = false;
  26266. }
  26267. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  26268. var _this = this;
  26269. var onload = function () {
  26270. _this.isCompleted = true;
  26271. if (_this.onSuccess) {
  26272. _this.onSuccess(_this);
  26273. }
  26274. onSuccess();
  26275. };
  26276. var onerror = function () {
  26277. if (_this.onError) {
  26278. _this.onError(_this);
  26279. }
  26280. onError();
  26281. };
  26282. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  26283. };
  26284. return TextureAssetTask;
  26285. })();
  26286. BABYLON.TextureAssetTask = TextureAssetTask;
  26287. var AssetsManager = (function () {
  26288. function AssetsManager(scene) {
  26289. this._tasks = new Array();
  26290. this._waitingTasksCount = 0;
  26291. this.useDefaultLoadingScreen = true;
  26292. this._scene = scene;
  26293. }
  26294. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  26295. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  26296. this._tasks.push(task);
  26297. return task;
  26298. };
  26299. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  26300. var task = new TextFileAssetTask(taskName, url);
  26301. this._tasks.push(task);
  26302. return task;
  26303. };
  26304. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  26305. var task = new BinaryFileAssetTask(taskName, url);
  26306. this._tasks.push(task);
  26307. return task;
  26308. };
  26309. AssetsManager.prototype.addImageTask = function (taskName, url) {
  26310. var task = new ImageAssetTask(taskName, url);
  26311. this._tasks.push(task);
  26312. return task;
  26313. };
  26314. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  26315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  26316. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  26317. this._tasks.push(task);
  26318. return task;
  26319. };
  26320. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  26321. this._waitingTasksCount--;
  26322. if (this._waitingTasksCount === 0) {
  26323. if (this.onFinish) {
  26324. this.onFinish(this._tasks);
  26325. }
  26326. this._scene.getEngine().hideLoadingUI();
  26327. }
  26328. };
  26329. AssetsManager.prototype._runTask = function (task) {
  26330. var _this = this;
  26331. task.run(this._scene, function () {
  26332. if (_this.onTaskSuccess) {
  26333. _this.onTaskSuccess(task);
  26334. }
  26335. _this._decreaseWaitingTasksCount();
  26336. }, function () {
  26337. if (_this.onTaskError) {
  26338. _this.onTaskError(task);
  26339. }
  26340. _this._decreaseWaitingTasksCount();
  26341. });
  26342. };
  26343. AssetsManager.prototype.reset = function () {
  26344. this._tasks = new Array();
  26345. return this;
  26346. };
  26347. AssetsManager.prototype.load = function () {
  26348. this._waitingTasksCount = this._tasks.length;
  26349. if (this._waitingTasksCount === 0) {
  26350. if (this.onFinish) {
  26351. this.onFinish(this._tasks);
  26352. }
  26353. return this;
  26354. }
  26355. if (this.useDefaultLoadingScreen) {
  26356. this._scene.getEngine().displayLoadingUI();
  26357. }
  26358. for (var index = 0; index < this._tasks.length; index++) {
  26359. var task = this._tasks[index];
  26360. this._runTask(task);
  26361. }
  26362. return this;
  26363. };
  26364. return AssetsManager;
  26365. })();
  26366. BABYLON.AssetsManager = AssetsManager;
  26367. })(BABYLON || (BABYLON = {}));
  26368. //# sourceMappingURL=babylon.assetsManager.js.map
  26369. var BABYLON;
  26370. (function (BABYLON) {
  26371. var VRDeviceOrientationCamera = (function (_super) {
  26372. __extends(VRDeviceOrientationCamera, _super);
  26373. function VRDeviceOrientationCamera(name, position, scene) {
  26374. _super.call(this, name, position, scene);
  26375. this._alpha = 0;
  26376. this._beta = 0;
  26377. this._gamma = 0;
  26378. }
  26379. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26380. this._alpha = +evt.alpha | 0;
  26381. this._beta = +evt.beta | 0;
  26382. this._gamma = +evt.gamma | 0;
  26383. if (this._gamma < 0) {
  26384. this._gamma = 90 + this._gamma;
  26385. }
  26386. else {
  26387. // Incline it in the correct angle.
  26388. this._gamma = 270 - this._gamma;
  26389. }
  26390. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26391. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26392. this.rotation.z = this._beta / 180.0 * Math.PI;
  26393. };
  26394. return VRDeviceOrientationCamera;
  26395. })(BABYLON.OculusCamera);
  26396. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26397. })(BABYLON || (BABYLON = {}));
  26398. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26399. var BABYLON;
  26400. (function (BABYLON) {
  26401. var WebVRCamera = (function (_super) {
  26402. __extends(WebVRCamera, _super);
  26403. function WebVRCamera(name, position, scene) {
  26404. _super.call(this, name, position, scene);
  26405. this._hmdDevice = null;
  26406. this._sensorDevice = null;
  26407. this._cacheState = null;
  26408. this._cacheQuaternion = new BABYLON.Quaternion();
  26409. this._cacheRotation = BABYLON.Vector3.Zero();
  26410. this._vrEnabled = false;
  26411. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26412. }
  26413. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26414. var size = devices.length;
  26415. var i = 0;
  26416. // Reset devices.
  26417. this._sensorDevice = null;
  26418. this._hmdDevice = null;
  26419. while (i < size && this._hmdDevice === null) {
  26420. if (devices[i] instanceof HMDVRDevice) {
  26421. this._hmdDevice = devices[i];
  26422. }
  26423. i++;
  26424. }
  26425. i = 0;
  26426. while (i < size && this._sensorDevice === null) {
  26427. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26428. this._sensorDevice = devices[i];
  26429. }
  26430. i++;
  26431. }
  26432. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26433. };
  26434. WebVRCamera.prototype._update = function () {
  26435. if (this._vrEnabled) {
  26436. this._cacheState = this._sensorDevice.getState();
  26437. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26438. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26439. this.rotation.x = -this._cacheRotation.z;
  26440. this.rotation.y = -this._cacheRotation.y;
  26441. this.rotation.z = this._cacheRotation.x;
  26442. }
  26443. _super.prototype._update.call(this);
  26444. };
  26445. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26446. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26447. if (navigator.getVRDevices) {
  26448. navigator.getVRDevices().then(this._getWebVRDevices);
  26449. }
  26450. else if (navigator.mozGetVRDevices) {
  26451. navigator.mozGetVRDevices(this._getWebVRDevices);
  26452. }
  26453. };
  26454. WebVRCamera.prototype.detachControl = function (element) {
  26455. _super.prototype.detachControl.call(this, element);
  26456. this._vrEnabled = false;
  26457. };
  26458. return WebVRCamera;
  26459. })(BABYLON.OculusCamera);
  26460. BABYLON.WebVRCamera = WebVRCamera;
  26461. })(BABYLON || (BABYLON = {}));
  26462. //# sourceMappingURL=babylon.webVRCamera.js.map
  26463. var BABYLON;
  26464. (function (BABYLON) {
  26465. // Standard optimizations
  26466. var SceneOptimization = (function () {
  26467. function SceneOptimization(priority) {
  26468. if (priority === void 0) { priority = 0; }
  26469. this.priority = priority;
  26470. this.apply = function (scene) {
  26471. return true; // Return true if everything that can be done was applied
  26472. };
  26473. }
  26474. return SceneOptimization;
  26475. })();
  26476. BABYLON.SceneOptimization = SceneOptimization;
  26477. var TextureOptimization = (function (_super) {
  26478. __extends(TextureOptimization, _super);
  26479. function TextureOptimization(priority, maximumSize) {
  26480. var _this = this;
  26481. if (priority === void 0) { priority = 0; }
  26482. if (maximumSize === void 0) { maximumSize = 1024; }
  26483. _super.call(this, priority);
  26484. this.priority = priority;
  26485. this.maximumSize = maximumSize;
  26486. this.apply = function (scene) {
  26487. var allDone = true;
  26488. for (var index = 0; index < scene.textures.length; index++) {
  26489. var texture = scene.textures[index];
  26490. if (!texture.canRescale) {
  26491. continue;
  26492. }
  26493. var currentSize = texture.getSize();
  26494. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26495. if (maxDimension > _this.maximumSize) {
  26496. texture.scale(0.5);
  26497. allDone = false;
  26498. }
  26499. }
  26500. return allDone;
  26501. };
  26502. }
  26503. return TextureOptimization;
  26504. })(SceneOptimization);
  26505. BABYLON.TextureOptimization = TextureOptimization;
  26506. var HardwareScalingOptimization = (function (_super) {
  26507. __extends(HardwareScalingOptimization, _super);
  26508. function HardwareScalingOptimization(priority, maximumScale) {
  26509. var _this = this;
  26510. if (priority === void 0) { priority = 0; }
  26511. if (maximumScale === void 0) { maximumScale = 2; }
  26512. _super.call(this, priority);
  26513. this.priority = priority;
  26514. this.maximumScale = maximumScale;
  26515. this._currentScale = 1;
  26516. this.apply = function (scene) {
  26517. _this._currentScale++;
  26518. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26519. return _this._currentScale >= _this.maximumScale;
  26520. };
  26521. }
  26522. return HardwareScalingOptimization;
  26523. })(SceneOptimization);
  26524. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26525. var ShadowsOptimization = (function (_super) {
  26526. __extends(ShadowsOptimization, _super);
  26527. function ShadowsOptimization() {
  26528. _super.apply(this, arguments);
  26529. this.apply = function (scene) {
  26530. scene.shadowsEnabled = false;
  26531. return true;
  26532. };
  26533. }
  26534. return ShadowsOptimization;
  26535. })(SceneOptimization);
  26536. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26537. var PostProcessesOptimization = (function (_super) {
  26538. __extends(PostProcessesOptimization, _super);
  26539. function PostProcessesOptimization() {
  26540. _super.apply(this, arguments);
  26541. this.apply = function (scene) {
  26542. scene.postProcessesEnabled = false;
  26543. return true;
  26544. };
  26545. }
  26546. return PostProcessesOptimization;
  26547. })(SceneOptimization);
  26548. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26549. var LensFlaresOptimization = (function (_super) {
  26550. __extends(LensFlaresOptimization, _super);
  26551. function LensFlaresOptimization() {
  26552. _super.apply(this, arguments);
  26553. this.apply = function (scene) {
  26554. scene.lensFlaresEnabled = false;
  26555. return true;
  26556. };
  26557. }
  26558. return LensFlaresOptimization;
  26559. })(SceneOptimization);
  26560. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26561. var ParticlesOptimization = (function (_super) {
  26562. __extends(ParticlesOptimization, _super);
  26563. function ParticlesOptimization() {
  26564. _super.apply(this, arguments);
  26565. this.apply = function (scene) {
  26566. scene.particlesEnabled = false;
  26567. return true;
  26568. };
  26569. }
  26570. return ParticlesOptimization;
  26571. })(SceneOptimization);
  26572. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26573. var RenderTargetsOptimization = (function (_super) {
  26574. __extends(RenderTargetsOptimization, _super);
  26575. function RenderTargetsOptimization() {
  26576. _super.apply(this, arguments);
  26577. this.apply = function (scene) {
  26578. scene.renderTargetsEnabled = false;
  26579. return true;
  26580. };
  26581. }
  26582. return RenderTargetsOptimization;
  26583. })(SceneOptimization);
  26584. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26585. var MergeMeshesOptimization = (function (_super) {
  26586. __extends(MergeMeshesOptimization, _super);
  26587. function MergeMeshesOptimization() {
  26588. var _this = this;
  26589. _super.apply(this, arguments);
  26590. this._canBeMerged = function (abstractMesh) {
  26591. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26592. return false;
  26593. }
  26594. var mesh = abstractMesh;
  26595. if (!mesh.isVisible || !mesh.isEnabled()) {
  26596. return false;
  26597. }
  26598. if (mesh.instances.length > 0) {
  26599. return false;
  26600. }
  26601. if (mesh.skeleton || mesh.hasLODLevels) {
  26602. return false;
  26603. }
  26604. return true;
  26605. };
  26606. this.apply = function (scene) {
  26607. var globalPool = scene.meshes.slice(0);
  26608. var globalLength = globalPool.length;
  26609. for (var index = 0; index < globalLength; index++) {
  26610. var currentPool = new Array();
  26611. var current = globalPool[index];
  26612. // Checks
  26613. if (!_this._canBeMerged(current)) {
  26614. continue;
  26615. }
  26616. currentPool.push(current);
  26617. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26618. var otherMesh = globalPool[subIndex];
  26619. if (!_this._canBeMerged(otherMesh)) {
  26620. continue;
  26621. }
  26622. if (otherMesh.material !== current.material) {
  26623. continue;
  26624. }
  26625. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26626. continue;
  26627. }
  26628. currentPool.push(otherMesh);
  26629. globalLength--;
  26630. globalPool.splice(subIndex, 1);
  26631. subIndex--;
  26632. }
  26633. if (currentPool.length < 2) {
  26634. continue;
  26635. }
  26636. // Merge meshes
  26637. BABYLON.Mesh.MergeMeshes(currentPool);
  26638. }
  26639. return true;
  26640. };
  26641. }
  26642. return MergeMeshesOptimization;
  26643. })(SceneOptimization);
  26644. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26645. // Options
  26646. var SceneOptimizerOptions = (function () {
  26647. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26648. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26649. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26650. this.targetFrameRate = targetFrameRate;
  26651. this.trackerDuration = trackerDuration;
  26652. this.optimizations = new Array();
  26653. }
  26654. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26655. var result = new SceneOptimizerOptions(targetFrameRate);
  26656. var priority = 0;
  26657. result.optimizations.push(new MergeMeshesOptimization(priority));
  26658. result.optimizations.push(new ShadowsOptimization(priority));
  26659. result.optimizations.push(new LensFlaresOptimization(priority));
  26660. // Next priority
  26661. priority++;
  26662. result.optimizations.push(new PostProcessesOptimization(priority));
  26663. result.optimizations.push(new ParticlesOptimization(priority));
  26664. // Next priority
  26665. priority++;
  26666. result.optimizations.push(new TextureOptimization(priority, 1024));
  26667. return result;
  26668. };
  26669. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26670. var result = new SceneOptimizerOptions(targetFrameRate);
  26671. var priority = 0;
  26672. result.optimizations.push(new MergeMeshesOptimization(priority));
  26673. result.optimizations.push(new ShadowsOptimization(priority));
  26674. result.optimizations.push(new LensFlaresOptimization(priority));
  26675. // Next priority
  26676. priority++;
  26677. result.optimizations.push(new PostProcessesOptimization(priority));
  26678. result.optimizations.push(new ParticlesOptimization(priority));
  26679. // Next priority
  26680. priority++;
  26681. result.optimizations.push(new TextureOptimization(priority, 512));
  26682. // Next priority
  26683. priority++;
  26684. result.optimizations.push(new RenderTargetsOptimization(priority));
  26685. // Next priority
  26686. priority++;
  26687. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26688. return result;
  26689. };
  26690. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26691. var result = new SceneOptimizerOptions(targetFrameRate);
  26692. var priority = 0;
  26693. result.optimizations.push(new MergeMeshesOptimization(priority));
  26694. result.optimizations.push(new ShadowsOptimization(priority));
  26695. result.optimizations.push(new LensFlaresOptimization(priority));
  26696. // Next priority
  26697. priority++;
  26698. result.optimizations.push(new PostProcessesOptimization(priority));
  26699. result.optimizations.push(new ParticlesOptimization(priority));
  26700. // Next priority
  26701. priority++;
  26702. result.optimizations.push(new TextureOptimization(priority, 256));
  26703. // Next priority
  26704. priority++;
  26705. result.optimizations.push(new RenderTargetsOptimization(priority));
  26706. // Next priority
  26707. priority++;
  26708. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26709. return result;
  26710. };
  26711. return SceneOptimizerOptions;
  26712. })();
  26713. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26714. // Scene optimizer tool
  26715. var SceneOptimizer = (function () {
  26716. function SceneOptimizer() {
  26717. }
  26718. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26719. // TODO: add an epsilon
  26720. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26721. if (onSuccess) {
  26722. onSuccess();
  26723. }
  26724. return;
  26725. }
  26726. // Apply current level of optimizations
  26727. var allDone = true;
  26728. var noOptimizationApplied = true;
  26729. for (var index = 0; index < options.optimizations.length; index++) {
  26730. var optimization = options.optimizations[index];
  26731. if (optimization.priority === currentPriorityLevel) {
  26732. noOptimizationApplied = false;
  26733. allDone = allDone && optimization.apply(scene);
  26734. }
  26735. }
  26736. // If no optimization was applied, this is a failure :(
  26737. if (noOptimizationApplied) {
  26738. if (onFailure) {
  26739. onFailure();
  26740. }
  26741. return;
  26742. }
  26743. // If all optimizations were done, move to next level
  26744. if (allDone) {
  26745. currentPriorityLevel++;
  26746. }
  26747. // Let's the system running for a specific amount of time before checking FPS
  26748. scene.executeWhenReady(function () {
  26749. setTimeout(function () {
  26750. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26751. }, options.trackerDuration);
  26752. });
  26753. };
  26754. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26755. if (!options) {
  26756. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26757. }
  26758. // Let's the system running for a specific amount of time before checking FPS
  26759. scene.executeWhenReady(function () {
  26760. setTimeout(function () {
  26761. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26762. }, options.trackerDuration);
  26763. });
  26764. };
  26765. return SceneOptimizer;
  26766. })();
  26767. BABYLON.SceneOptimizer = SceneOptimizer;
  26768. })(BABYLON || (BABYLON = {}));
  26769. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26770. (function (BABYLON) {
  26771. var Internals;
  26772. (function (Internals) {
  26773. var MeshLODLevel = (function () {
  26774. function MeshLODLevel(distance, mesh) {
  26775. this.distance = distance;
  26776. this.mesh = mesh;
  26777. }
  26778. return MeshLODLevel;
  26779. })();
  26780. Internals.MeshLODLevel = MeshLODLevel;
  26781. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26782. })(BABYLON || (BABYLON = {}));
  26783. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26784. (function (BABYLON) {
  26785. var AudioEngine = (function () {
  26786. function AudioEngine() {
  26787. this.audioContext = null;
  26788. this.canUseWebAudio = false;
  26789. this.WarnedWebAudioUnsupported = false;
  26790. try {
  26791. if (typeof AudioContext !== 'undefined') {
  26792. this.audioContext = new AudioContext();
  26793. this.canUseWebAudio = true;
  26794. }
  26795. else if (typeof webkitAudioContext !== 'undefined') {
  26796. this.audioContext = new webkitAudioContext();
  26797. this.canUseWebAudio = true;
  26798. }
  26799. }
  26800. catch (e) {
  26801. this.canUseWebAudio = false;
  26802. BABYLON.Tools.Error("Web Audio: " + e.message);
  26803. }
  26804. // create a global volume gain node
  26805. if (this.canUseWebAudio) {
  26806. this.masterGain = this.audioContext.createGain();
  26807. this.masterGain.gain.value = 1;
  26808. this.masterGain.connect(this.audioContext.destination);
  26809. }
  26810. }
  26811. AudioEngine.prototype.dispose = function () {
  26812. if (this.canUseWebAudio) {
  26813. if (this._connectedAnalyser) {
  26814. this._connectedAnalyser.stopDebugCanvas();
  26815. this._connectedAnalyser.dispose();
  26816. this.masterGain.disconnect();
  26817. this.masterGain.connect(this.audioContext.destination);
  26818. this._connectedAnalyser = null;
  26819. }
  26820. this.masterGain.gain.value = 1;
  26821. }
  26822. this.WarnedWebAudioUnsupported = false;
  26823. };
  26824. AudioEngine.prototype.getGlobalVolume = function () {
  26825. if (this.canUseWebAudio) {
  26826. return this.masterGain.gain.value;
  26827. }
  26828. else {
  26829. return -1;
  26830. }
  26831. };
  26832. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26833. if (this.canUseWebAudio) {
  26834. this.masterGain.gain.value = newVolume;
  26835. }
  26836. };
  26837. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26838. if (this._connectedAnalyser) {
  26839. this._connectedAnalyser.stopDebugCanvas();
  26840. }
  26841. this._connectedAnalyser = analyser;
  26842. if (this.canUseWebAudio) {
  26843. this.masterGain.disconnect();
  26844. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26845. }
  26846. };
  26847. return AudioEngine;
  26848. })();
  26849. BABYLON.AudioEngine = AudioEngine;
  26850. })(BABYLON || (BABYLON = {}));
  26851. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26852. (function (BABYLON) {
  26853. var Sound = (function () {
  26854. /**
  26855. * Create a sound and attach it to a scene
  26856. * @param name Name of your sound
  26857. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26858. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26859. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26860. */
  26861. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26862. var _this = this;
  26863. this.autoplay = false;
  26864. this.loop = false;
  26865. this.useCustomAttenuation = false;
  26866. this.spatialSound = false;
  26867. this.refDistance = 1;
  26868. this.rolloffFactor = 1;
  26869. this.maxDistance = 100;
  26870. this.distanceModel = "linear";
  26871. this._panningModel = "equalpower";
  26872. this._playbackRate = 1;
  26873. this._startTime = 0;
  26874. this._startOffset = 0;
  26875. this._position = BABYLON.Vector3.Zero();
  26876. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26877. this._volume = 1;
  26878. this._isLoaded = false;
  26879. this._isReadyToPlay = false;
  26880. this.isPlaying = false;
  26881. this.isPaused = false;
  26882. this._isDirectional = false;
  26883. // Used if you'd like to create a directional sound.
  26884. // If not set, the sound will be omnidirectional
  26885. this._coneInnerAngle = 360;
  26886. this._coneOuterAngle = 360;
  26887. this._coneOuterGain = 0;
  26888. this.name = name;
  26889. this._scene = scene;
  26890. this._readyToPlayCallback = readyToPlayCallback;
  26891. // Default custom attenuation function is a linear attenuation
  26892. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26893. if (currentDistance < maxDistance) {
  26894. return currentVolume * (1 - currentDistance / maxDistance);
  26895. }
  26896. else {
  26897. return 0;
  26898. }
  26899. };
  26900. if (options) {
  26901. this.autoplay = options.autoplay || false;
  26902. this.loop = options.loop || false;
  26903. // if volume === 0, we need another way to check this option
  26904. if (options.volume !== undefined) {
  26905. this._volume = options.volume;
  26906. }
  26907. this.spatialSound = options.spatialSound || false;
  26908. this.maxDistance = options.maxDistance || 100;
  26909. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26910. this.rolloffFactor = options.rolloffFactor || 1;
  26911. this.refDistance = options.refDistance || 1;
  26912. this.distanceModel = options.distanceModel || "linear";
  26913. this._playbackRate = options.playbackRate || 1;
  26914. }
  26915. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26916. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26917. this._soundGain.gain.value = this._volume;
  26918. this._inputAudioNode = this._soundGain;
  26919. this._ouputAudioNode = this._soundGain;
  26920. if (this.spatialSound) {
  26921. this._createSpatialParameters();
  26922. }
  26923. this._scene.mainSoundTrack.AddSound(this);
  26924. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26925. if (urlOrArrayBuffer) {
  26926. // If it's an URL
  26927. if (typeof (urlOrArrayBuffer) === "string") {
  26928. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26929. _this._soundLoaded(data);
  26930. }, null, null, true);
  26931. }
  26932. else {
  26933. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26934. this._soundLoaded(urlOrArrayBuffer);
  26935. }
  26936. else {
  26937. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26938. }
  26939. }
  26940. }
  26941. }
  26942. else {
  26943. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26944. this._scene.mainSoundTrack.AddSound(this);
  26945. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26946. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26947. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26948. }
  26949. }
  26950. }
  26951. Sound.prototype.dispose = function () {
  26952. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26953. if (this.isPlaying) {
  26954. this.stop();
  26955. }
  26956. this._isReadyToPlay = false;
  26957. if (this.soundTrackId === -1) {
  26958. this._scene.mainSoundTrack.RemoveSound(this);
  26959. }
  26960. else {
  26961. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26962. }
  26963. if (this._soundGain) {
  26964. this._soundGain.disconnect();
  26965. this._soundGain = null;
  26966. }
  26967. if (this._soundPanner) {
  26968. this._soundPanner.disconnect();
  26969. this._soundPanner = null;
  26970. }
  26971. if (this._soundSource) {
  26972. this._soundSource.disconnect();
  26973. this._soundSource = null;
  26974. }
  26975. this._audioBuffer = null;
  26976. if (this._connectedMesh) {
  26977. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26978. this._connectedMesh = null;
  26979. }
  26980. }
  26981. };
  26982. Sound.prototype._soundLoaded = function (audioData) {
  26983. var _this = this;
  26984. this._isLoaded = true;
  26985. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26986. _this._audioBuffer = buffer;
  26987. _this._isReadyToPlay = true;
  26988. if (_this.autoplay) {
  26989. _this.play();
  26990. }
  26991. if (_this._readyToPlayCallback) {
  26992. _this._readyToPlayCallback();
  26993. }
  26994. }, function (error) {
  26995. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26996. });
  26997. };
  26998. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26999. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27000. this._audioBuffer = audioBuffer;
  27001. this._isReadyToPlay = true;
  27002. }
  27003. };
  27004. Sound.prototype.updateOptions = function (options) {
  27005. if (options) {
  27006. this.loop = options.loop || this.loop;
  27007. this.maxDistance = options.maxDistance || this.maxDistance;
  27008. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  27009. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  27010. this.refDistance = options.refDistance || this.refDistance;
  27011. this.distanceModel = options.distanceModel || this.distanceModel;
  27012. this._playbackRate = options.playbackRate || this._playbackRate;
  27013. }
  27014. };
  27015. Sound.prototype._createSpatialParameters = function () {
  27016. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27017. if (this._scene.headphone) {
  27018. this._panningModel = "HRTF";
  27019. }
  27020. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  27021. if (this.useCustomAttenuation) {
  27022. // Tricks to disable in a way embedded Web Audio attenuation
  27023. this._soundPanner.distanceModel = "linear";
  27024. this._soundPanner.maxDistance = Number.MAX_VALUE;
  27025. this._soundPanner.refDistance = 1;
  27026. this._soundPanner.rolloffFactor = 1;
  27027. this._soundPanner.panningModel = this._panningModel;
  27028. }
  27029. else {
  27030. this._soundPanner.distanceModel = this.distanceModel;
  27031. this._soundPanner.maxDistance = this.maxDistance;
  27032. this._soundPanner.refDistance = this.refDistance;
  27033. this._soundPanner.rolloffFactor = this.rolloffFactor;
  27034. this._soundPanner.panningModel = this._panningModel;
  27035. }
  27036. this._soundPanner.connect(this._ouputAudioNode);
  27037. this._inputAudioNode = this._soundPanner;
  27038. }
  27039. };
  27040. Sound.prototype.switchPanningModelToHRTF = function () {
  27041. this._panningModel = "HRTF";
  27042. this._switchPanningModel();
  27043. };
  27044. Sound.prototype.switchPanningModelToEqualPower = function () {
  27045. this._panningModel = "equalpower";
  27046. this._switchPanningModel();
  27047. };
  27048. Sound.prototype._switchPanningModel = function () {
  27049. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  27050. this._soundPanner.panningModel = this._panningModel;
  27051. }
  27052. };
  27053. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  27054. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27055. this._ouputAudioNode.disconnect();
  27056. this._ouputAudioNode.connect(soundTrackAudioNode);
  27057. }
  27058. };
  27059. /**
  27060. * Transform this sound into a directional source
  27061. * @param coneInnerAngle Size of the inner cone in degree
  27062. * @param coneOuterAngle Size of the outer cone in degree
  27063. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  27064. */
  27065. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  27066. if (coneOuterAngle < coneInnerAngle) {
  27067. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  27068. return;
  27069. }
  27070. this._coneInnerAngle = coneInnerAngle;
  27071. this._coneOuterAngle = coneOuterAngle;
  27072. this._coneOuterGain = coneOuterGain;
  27073. this._isDirectional = true;
  27074. if (this.isPlaying && this.loop) {
  27075. this.stop();
  27076. this.play();
  27077. }
  27078. };
  27079. Sound.prototype.setPosition = function (newPosition) {
  27080. this._position = newPosition;
  27081. if (this.isPlaying && this.spatialSound) {
  27082. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27083. }
  27084. };
  27085. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  27086. this._localDirection = newLocalDirection;
  27087. if (this._connectedMesh && this.isPlaying) {
  27088. this._updateDirection();
  27089. }
  27090. };
  27091. Sound.prototype._updateDirection = function () {
  27092. var mat = this._connectedMesh.getWorldMatrix();
  27093. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  27094. direction.normalize();
  27095. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  27096. };
  27097. Sound.prototype.updateDistanceFromListener = function () {
  27098. if (this._connectedMesh && this.useCustomAttenuation) {
  27099. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  27100. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  27101. }
  27102. };
  27103. Sound.prototype.setAttenuationFunction = function (callback) {
  27104. this._customAttenuationFunction = callback;
  27105. };
  27106. /**
  27107. * Play the sound
  27108. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  27109. */
  27110. Sound.prototype.play = function (time) {
  27111. var _this = this;
  27112. if (this._isReadyToPlay && this._scene.audioEnabled) {
  27113. try {
  27114. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27115. if (!this._soundSource) {
  27116. if (this.spatialSound) {
  27117. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  27118. if (this._isDirectional) {
  27119. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  27120. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  27121. this._soundPanner.coneOuterGain = this._coneOuterGain;
  27122. if (this._connectedMesh) {
  27123. this._updateDirection();
  27124. }
  27125. else {
  27126. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  27127. }
  27128. }
  27129. }
  27130. }
  27131. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  27132. this._soundSource.buffer = this._audioBuffer;
  27133. this._soundSource.connect(this._inputAudioNode);
  27134. this._soundSource.loop = this.loop;
  27135. this._soundSource.playbackRate.value = this._playbackRate;
  27136. this._startTime = startTime;
  27137. this._soundSource.onended = function () {
  27138. _this._onended();
  27139. };
  27140. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  27141. this.isPlaying = true;
  27142. this.isPaused = false;
  27143. }
  27144. catch (ex) {
  27145. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  27146. }
  27147. }
  27148. };
  27149. Sound.prototype._onended = function () {
  27150. this.isPlaying = false;
  27151. if (this.onended) {
  27152. this.onended();
  27153. }
  27154. };
  27155. /**
  27156. * Stop the sound
  27157. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  27158. */
  27159. Sound.prototype.stop = function (time) {
  27160. if (this.isPlaying) {
  27161. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  27162. this._soundSource.stop(stopTime);
  27163. this.isPlaying = false;
  27164. }
  27165. };
  27166. Sound.prototype.pause = function () {
  27167. if (this.isPlaying) {
  27168. this.stop(0);
  27169. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  27170. this.isPaused = true;
  27171. }
  27172. };
  27173. Sound.prototype.setVolume = function (newVolume, time) {
  27174. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27175. if (time) {
  27176. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  27177. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  27178. }
  27179. else {
  27180. this._soundGain.gain.value = newVolume;
  27181. }
  27182. }
  27183. this._volume = newVolume;
  27184. };
  27185. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  27186. this._playbackRate = newPlaybackRate;
  27187. if (this.isPlaying) {
  27188. this._soundSource.playbackRate.value = this._playbackRate;
  27189. }
  27190. };
  27191. Sound.prototype.getVolume = function () {
  27192. return this._volume;
  27193. };
  27194. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  27195. var _this = this;
  27196. this._connectedMesh = meshToConnectTo;
  27197. if (!this.spatialSound) {
  27198. this._createSpatialParameters();
  27199. this.spatialSound = true;
  27200. if (this.isPlaying && this.loop) {
  27201. this.stop();
  27202. this.play();
  27203. }
  27204. }
  27205. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  27206. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  27207. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  27208. };
  27209. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  27210. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  27211. if (this._isDirectional && this.isPlaying) {
  27212. this._updateDirection();
  27213. }
  27214. };
  27215. return Sound;
  27216. })();
  27217. BABYLON.Sound = Sound;
  27218. })(BABYLON || (BABYLON = {}));
  27219. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  27220. (function (BABYLON) {
  27221. var SoundTrack = (function () {
  27222. function SoundTrack(scene, options) {
  27223. this.id = -1;
  27224. this._isMainTrack = false;
  27225. this._scene = scene;
  27226. this._audioEngine = BABYLON.Engine.audioEngine;
  27227. this.soundCollection = new Array();
  27228. if (this._audioEngine.canUseWebAudio) {
  27229. this._trackGain = this._audioEngine.audioContext.createGain();
  27230. this._trackGain.connect(this._audioEngine.masterGain);
  27231. if (options) {
  27232. if (options.volume) {
  27233. this._trackGain.gain.value = options.volume;
  27234. }
  27235. if (options.mainTrack) {
  27236. this._isMainTrack = options.mainTrack;
  27237. }
  27238. }
  27239. }
  27240. if (!this._isMainTrack) {
  27241. this._scene.soundTracks.push(this);
  27242. this.id = this._scene.soundTracks.length - 1;
  27243. }
  27244. }
  27245. SoundTrack.prototype.dispose = function () {
  27246. if (this._audioEngine.canUseWebAudio) {
  27247. if (this._connectedAnalyser) {
  27248. this._connectedAnalyser.stopDebugCanvas();
  27249. }
  27250. while (this.soundCollection.length) {
  27251. this.soundCollection[0].dispose();
  27252. }
  27253. this._trackGain.disconnect();
  27254. this._trackGain = null;
  27255. }
  27256. };
  27257. SoundTrack.prototype.AddSound = function (sound) {
  27258. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27259. sound.connectToSoundTrackAudioNode(this._trackGain);
  27260. }
  27261. if (sound.soundTrackId) {
  27262. if (sound.soundTrackId === -1) {
  27263. this._scene.mainSoundTrack.RemoveSound(sound);
  27264. }
  27265. else {
  27266. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  27267. }
  27268. }
  27269. this.soundCollection.push(sound);
  27270. sound.soundTrackId = this.id;
  27271. };
  27272. SoundTrack.prototype.RemoveSound = function (sound) {
  27273. var index = this.soundCollection.indexOf(sound);
  27274. if (index !== -1) {
  27275. this.soundCollection.splice(index, 1);
  27276. }
  27277. };
  27278. SoundTrack.prototype.setVolume = function (newVolume) {
  27279. if (this._audioEngine.canUseWebAudio) {
  27280. this._trackGain.gain.value = newVolume;
  27281. }
  27282. };
  27283. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  27284. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27285. for (var i = 0; i < this.soundCollection.length; i++) {
  27286. this.soundCollection[i].switchPanningModelToHRTF();
  27287. }
  27288. }
  27289. };
  27290. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  27291. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27292. for (var i = 0; i < this.soundCollection.length; i++) {
  27293. this.soundCollection[i].switchPanningModelToEqualPower();
  27294. }
  27295. }
  27296. };
  27297. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  27298. if (this._connectedAnalyser) {
  27299. this._connectedAnalyser.stopDebugCanvas();
  27300. }
  27301. this._connectedAnalyser = analyser;
  27302. if (this._audioEngine.canUseWebAudio) {
  27303. this._trackGain.disconnect();
  27304. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  27305. }
  27306. };
  27307. return SoundTrack;
  27308. })();
  27309. BABYLON.SoundTrack = SoundTrack;
  27310. })(BABYLON || (BABYLON = {}));
  27311. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  27312. (function (BABYLON) {
  27313. var DebugLayer = (function () {
  27314. function DebugLayer(scene) {
  27315. var _this = this;
  27316. this._transformationMatrix = BABYLON.Matrix.Identity();
  27317. this._enabled = false;
  27318. this._labelsEnabled = false;
  27319. this._displayStatistics = true;
  27320. this._displayTree = false;
  27321. this._displayLogs = false;
  27322. this._identityMatrix = BABYLON.Matrix.Identity();
  27323. this.axisRatio = 0.02;
  27324. this.accentColor = "orange";
  27325. this._scene = scene;
  27326. this._syncPositions = function () {
  27327. var engine = _this._scene.getEngine();
  27328. var canvasRect = engine.getRenderingCanvasClientRect();
  27329. if (_this._showUI) {
  27330. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  27331. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  27332. _this._statsDiv.style.width = "400px";
  27333. _this._statsDiv.style.height = "auto";
  27334. _this._statsSubsetDiv.style.maxHeight = "240px";
  27335. _this._optionsDiv.style.left = "0px";
  27336. _this._optionsDiv.style.top = "10px";
  27337. _this._optionsDiv.style.width = "200px";
  27338. _this._optionsDiv.style.height = "auto";
  27339. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  27340. _this._logDiv.style.left = "0px";
  27341. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  27342. _this._logDiv.style.width = "600px";
  27343. _this._logDiv.style.height = "160px";
  27344. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  27345. _this._treeDiv.style.top = "10px";
  27346. _this._treeDiv.style.width = "300px";
  27347. _this._treeDiv.style.height = "auto";
  27348. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  27349. }
  27350. _this._globalDiv.style.left = canvasRect.left + "px";
  27351. _this._globalDiv.style.top = canvasRect.top + "px";
  27352. _this._drawingCanvas.style.left = "0px";
  27353. _this._drawingCanvas.style.top = "0px";
  27354. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  27355. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  27356. var devicePixelRatio = window.devicePixelRatio || 1;
  27357. var context = _this._drawingContext;
  27358. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  27359. _this._ratio = devicePixelRatio / backingStoreRatio;
  27360. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  27361. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  27362. };
  27363. this._onCanvasClick = function (evt) {
  27364. _this._clickPosition = {
  27365. x: evt.clientX * _this._ratio,
  27366. y: evt.clientY * _this._ratio
  27367. };
  27368. };
  27369. this._syncUI = function () {
  27370. if (_this._showUI) {
  27371. if (_this._displayStatistics) {
  27372. _this._displayStats();
  27373. _this._statsDiv.style.display = "";
  27374. }
  27375. else {
  27376. _this._statsDiv.style.display = "none";
  27377. }
  27378. if (_this._displayLogs) {
  27379. _this._logDiv.style.display = "";
  27380. }
  27381. else {
  27382. _this._logDiv.style.display = "none";
  27383. }
  27384. if (_this._displayTree) {
  27385. _this._treeDiv.style.display = "";
  27386. if (_this._needToRefreshMeshesTree) {
  27387. _this._needToRefreshMeshesTree = false;
  27388. _this._refreshMeshesTreeContent();
  27389. }
  27390. }
  27391. else {
  27392. _this._treeDiv.style.display = "none";
  27393. }
  27394. }
  27395. };
  27396. this._syncData = function () {
  27397. if (_this._labelsEnabled || !_this._showUI) {
  27398. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27399. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27400. var engine = _this._scene.getEngine();
  27401. var viewport = _this._camera.viewport;
  27402. var globalViewport = viewport.toGlobal(engine);
  27403. // Meshes
  27404. var meshes = _this._camera.getActiveMeshes();
  27405. for (var index = 0; index < meshes.length; index++) {
  27406. var mesh = meshes.data[index];
  27407. var position = mesh.getBoundingInfo().boundingSphere.center;
  27408. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27409. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27410. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27411. }
  27412. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27413. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27414. mesh.renderOverlay = !mesh.renderOverlay;
  27415. }, function () {
  27416. return mesh.renderOverlay ? 'red' : 'black';
  27417. });
  27418. }
  27419. }
  27420. // Cameras
  27421. var cameras = _this._scene.cameras;
  27422. for (index = 0; index < cameras.length; index++) {
  27423. var camera = cameras[index];
  27424. if (camera === _this._camera) {
  27425. continue;
  27426. }
  27427. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27428. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27429. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27430. _this._camera.detachControl(engine.getRenderingCanvas());
  27431. _this._camera = camera;
  27432. _this._camera.attachControl(engine.getRenderingCanvas());
  27433. }, function () {
  27434. return "purple";
  27435. });
  27436. }
  27437. }
  27438. // Lights
  27439. var lights = _this._scene.lights;
  27440. for (index = 0; index < lights.length; index++) {
  27441. var light = lights[index];
  27442. if (light.position) {
  27443. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27444. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27445. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27446. light.setEnabled(!light.isEnabled());
  27447. }, function () {
  27448. return light.isEnabled() ? "orange" : "gray";
  27449. });
  27450. }
  27451. }
  27452. }
  27453. }
  27454. _this._clickPosition = undefined;
  27455. };
  27456. }
  27457. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27458. while (this._treeSubsetDiv.hasChildNodes()) {
  27459. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27460. }
  27461. // Add meshes
  27462. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27463. sortedArray.sort(function (a, b) {
  27464. if (a.name === b.name) {
  27465. return 0;
  27466. }
  27467. return (a.name > b.name) ? 1 : -1;
  27468. });
  27469. for (var index = 0; index < sortedArray.length; index++) {
  27470. var mesh = sortedArray[index];
  27471. if (!mesh.isEnabled()) {
  27472. continue;
  27473. }
  27474. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27475. m.isVisible = element.checked;
  27476. }, mesh);
  27477. }
  27478. };
  27479. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27480. this._drawingContext.beginPath();
  27481. this._drawingContext.moveTo(zero.x, zero.y);
  27482. this._drawingContext.lineTo(unit.x, unit.y);
  27483. this._drawingContext.strokeStyle = color;
  27484. this._drawingContext.lineWidth = 4;
  27485. this._drawingContext.stroke();
  27486. this._drawingContext.font = "normal 14px Segoe UI";
  27487. this._drawingContext.fillStyle = color;
  27488. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27489. };
  27490. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27491. var position = mesh.getBoundingInfo().boundingSphere.center;
  27492. var worldMatrix = mesh.getWorldMatrix();
  27493. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27494. var unit = (unprojectedVector.subtract(position)).length();
  27495. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27496. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27497. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27498. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27499. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27500. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27501. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27502. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27503. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27504. };
  27505. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27506. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27507. this._drawingContext.font = "normal 12px Segoe UI";
  27508. var textMetrics = this._drawingContext.measureText(text);
  27509. var centerX = projectedPosition.x - textMetrics.width / 2;
  27510. var centerY = projectedPosition.y;
  27511. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27512. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27513. onClick();
  27514. }
  27515. this._drawingContext.beginPath();
  27516. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27517. this._drawingContext.fillStyle = getFillStyle();
  27518. this._drawingContext.globalAlpha = 0.5;
  27519. this._drawingContext.fill();
  27520. this._drawingContext.globalAlpha = 1.0;
  27521. this._drawingContext.strokeStyle = '#FFFFFF';
  27522. this._drawingContext.lineWidth = 1;
  27523. this._drawingContext.stroke();
  27524. this._drawingContext.fillStyle = "#FFFFFF";
  27525. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27526. this._drawingContext.beginPath();
  27527. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27528. this._drawingContext.fill();
  27529. }
  27530. };
  27531. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27532. if (!this._clickPosition) {
  27533. return false;
  27534. }
  27535. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27536. return false;
  27537. }
  27538. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27539. return false;
  27540. }
  27541. return true;
  27542. };
  27543. DebugLayer.prototype.isVisible = function () {
  27544. return this._enabled;
  27545. };
  27546. DebugLayer.prototype.hide = function () {
  27547. if (!this._enabled) {
  27548. return;
  27549. }
  27550. this._enabled = false;
  27551. var engine = this._scene.getEngine();
  27552. this._scene.unregisterBeforeRender(this._syncData);
  27553. this._scene.unregisterAfterRender(this._syncUI);
  27554. document.body.removeChild(this._globalDiv);
  27555. window.removeEventListener("resize", this._syncPositions);
  27556. this._scene.forceShowBoundingBoxes = false;
  27557. this._scene.forceWireframe = false;
  27558. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27559. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27560. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27561. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27562. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27563. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27564. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27565. this._scene.shadowsEnabled = true;
  27566. this._scene.particlesEnabled = true;
  27567. this._scene.postProcessesEnabled = true;
  27568. this._scene.collisionsEnabled = true;
  27569. this._scene.lightsEnabled = true;
  27570. this._scene.texturesEnabled = true;
  27571. this._scene.lensFlaresEnabled = true;
  27572. this._scene.proceduralTexturesEnabled = true;
  27573. this._scene.renderTargetsEnabled = true;
  27574. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27575. };
  27576. DebugLayer.prototype.show = function (showUI, camera) {
  27577. if (showUI === void 0) { showUI = true; }
  27578. if (camera === void 0) { camera = null; }
  27579. if (this._enabled) {
  27580. return;
  27581. }
  27582. if (camera) {
  27583. this._camera = camera;
  27584. }
  27585. else {
  27586. this._camera = this._scene.activeCamera;
  27587. }
  27588. this._enabled = true;
  27589. this._showUI = showUI;
  27590. var engine = this._scene.getEngine();
  27591. this._globalDiv = document.createElement("div");
  27592. document.body.appendChild(this._globalDiv);
  27593. this._generateDOMelements();
  27594. window.addEventListener("resize", this._syncPositions);
  27595. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27596. this._syncPositions();
  27597. this._scene.registerBeforeRender(this._syncData);
  27598. this._scene.registerAfterRender(this._syncUI);
  27599. };
  27600. DebugLayer.prototype._clearLabels = function () {
  27601. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27602. for (var index = 0; index < this._scene.meshes.length; index++) {
  27603. var mesh = this._scene.meshes[index];
  27604. mesh.renderOverlay = false;
  27605. }
  27606. };
  27607. DebugLayer.prototype._generateheader = function (root, text) {
  27608. var header = document.createElement("div");
  27609. header.innerHTML = text + "&nbsp;";
  27610. header.style.textAlign = "right";
  27611. header.style.width = "100%";
  27612. header.style.color = "white";
  27613. header.style.backgroundColor = "Black";
  27614. header.style.padding = "5px 5px 4px 0px";
  27615. header.style.marginLeft = "-5px";
  27616. header.style.fontWeight = "bold";
  27617. root.appendChild(header);
  27618. };
  27619. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27620. var label = document.createElement("label");
  27621. label.innerHTML = title;
  27622. label.style.color = color;
  27623. root.appendChild(label);
  27624. root.appendChild(document.createElement("br"));
  27625. };
  27626. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27627. if (tag === void 0) { tag = null; }
  27628. var label = document.createElement("label");
  27629. var boundingBoxesCheckbox = document.createElement("input");
  27630. boundingBoxesCheckbox.type = "checkbox";
  27631. boundingBoxesCheckbox.checked = initialState;
  27632. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27633. task(evt.target, tag);
  27634. });
  27635. label.appendChild(boundingBoxesCheckbox);
  27636. var container = document.createElement("span");
  27637. var leftPart = document.createElement("span");
  27638. var rightPart = document.createElement("span");
  27639. rightPart.style.cssFloat = "right";
  27640. leftPart.innerHTML = leftTitle;
  27641. rightPart.innerHTML = rightTitle;
  27642. rightPart.style.fontSize = "12px";
  27643. rightPart.style.maxWidth = "200px";
  27644. container.appendChild(leftPart);
  27645. container.appendChild(rightPart);
  27646. label.appendChild(container);
  27647. root.appendChild(label);
  27648. root.appendChild(document.createElement("br"));
  27649. };
  27650. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27651. if (tag === void 0) { tag = null; }
  27652. var label = document.createElement("label");
  27653. var checkBox = document.createElement("input");
  27654. checkBox.type = "checkbox";
  27655. checkBox.checked = initialState;
  27656. checkBox.addEventListener("change", function (evt) {
  27657. task(evt.target, tag);
  27658. });
  27659. label.appendChild(checkBox);
  27660. label.appendChild(document.createTextNode(title));
  27661. root.appendChild(label);
  27662. root.appendChild(document.createElement("br"));
  27663. };
  27664. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27665. if (tag === void 0) { tag = null; }
  27666. var button = document.createElement("button");
  27667. button.innerHTML = title;
  27668. button.style.height = "24px";
  27669. button.style.color = "#444444";
  27670. button.style.border = "1px solid white";
  27671. button.className = "debugLayerButton";
  27672. button.addEventListener("click", function (evt) {
  27673. task(evt.target, tag);
  27674. });
  27675. root.appendChild(button);
  27676. root.appendChild(document.createElement("br"));
  27677. };
  27678. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27679. if (tag === void 0) { tag = null; }
  27680. var label = document.createElement("label");
  27681. var boundingBoxesRadio = document.createElement("input");
  27682. boundingBoxesRadio.type = "radio";
  27683. boundingBoxesRadio.name = name;
  27684. boundingBoxesRadio.checked = initialState;
  27685. boundingBoxesRadio.addEventListener("change", function (evt) {
  27686. task(evt.target, tag);
  27687. });
  27688. label.appendChild(boundingBoxesRadio);
  27689. label.appendChild(document.createTextNode(title));
  27690. root.appendChild(label);
  27691. root.appendChild(document.createElement("br"));
  27692. };
  27693. DebugLayer.prototype._generateDOMelements = function () {
  27694. var _this = this;
  27695. this._globalDiv.id = "DebugLayer";
  27696. this._globalDiv.style.position = "absolute";
  27697. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27698. this._globalDiv.style.fontSize = "14px";
  27699. this._globalDiv.style.color = "white";
  27700. // Drawing canvas
  27701. this._drawingCanvas = document.createElement("canvas");
  27702. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27703. this._drawingCanvas.style.position = "absolute";
  27704. this._drawingCanvas.style.pointerEvents = "none";
  27705. this._drawingContext = this._drawingCanvas.getContext("2d");
  27706. this._globalDiv.appendChild(this._drawingCanvas);
  27707. if (this._showUI) {
  27708. var background = "rgba(128, 128, 128, 0.4)";
  27709. var border = "rgb(180, 180, 180) solid 1px";
  27710. // Stats
  27711. this._statsDiv = document.createElement("div");
  27712. this._statsDiv.id = "DebugLayerStats";
  27713. this._statsDiv.style.border = border;
  27714. this._statsDiv.style.position = "absolute";
  27715. this._statsDiv.style.background = background;
  27716. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27717. this._generateheader(this._statsDiv, "STATISTICS");
  27718. this._statsSubsetDiv = document.createElement("div");
  27719. this._statsSubsetDiv.style.paddingTop = "5px";
  27720. this._statsSubsetDiv.style.paddingBottom = "5px";
  27721. this._statsSubsetDiv.style.overflowY = "auto";
  27722. this._statsDiv.appendChild(this._statsSubsetDiv);
  27723. // Tree
  27724. this._treeDiv = document.createElement("div");
  27725. this._treeDiv.id = "DebugLayerTree";
  27726. this._treeDiv.style.border = border;
  27727. this._treeDiv.style.position = "absolute";
  27728. this._treeDiv.style.background = background;
  27729. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27730. this._treeDiv.style.display = "none";
  27731. this._generateheader(this._treeDiv, "MESHES TREE");
  27732. this._treeSubsetDiv = document.createElement("div");
  27733. this._treeSubsetDiv.style.paddingTop = "5px";
  27734. this._treeSubsetDiv.style.paddingRight = "5px";
  27735. this._treeSubsetDiv.style.overflowY = "auto";
  27736. this._treeSubsetDiv.style.maxHeight = "300px";
  27737. this._treeDiv.appendChild(this._treeSubsetDiv);
  27738. this._needToRefreshMeshesTree = true;
  27739. // Logs
  27740. this._logDiv = document.createElement("div");
  27741. this._logDiv.style.border = border;
  27742. this._logDiv.id = "DebugLayerLogs";
  27743. this._logDiv.style.position = "absolute";
  27744. this._logDiv.style.background = background;
  27745. this._logDiv.style.padding = "0px 0px 0px 5px";
  27746. this._logDiv.style.display = "none";
  27747. this._generateheader(this._logDiv, "LOGS");
  27748. this._logSubsetDiv = document.createElement("div");
  27749. this._logSubsetDiv.style.height = "127px";
  27750. this._logSubsetDiv.style.paddingTop = "5px";
  27751. this._logSubsetDiv.style.overflowY = "auto";
  27752. this._logSubsetDiv.style.fontSize = "12px";
  27753. this._logSubsetDiv.style.fontFamily = "consolas";
  27754. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27755. this._logDiv.appendChild(this._logSubsetDiv);
  27756. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27757. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27758. };
  27759. // Options
  27760. this._optionsDiv = document.createElement("div");
  27761. this._optionsDiv.id = "DebugLayerOptions";
  27762. this._optionsDiv.style.border = border;
  27763. this._optionsDiv.style.position = "absolute";
  27764. this._optionsDiv.style.background = background;
  27765. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27766. this._optionsDiv.style.overflowY = "auto";
  27767. this._generateheader(this._optionsDiv, "OPTIONS");
  27768. this._optionsSubsetDiv = document.createElement("div");
  27769. this._optionsSubsetDiv.style.paddingTop = "5px";
  27770. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27771. this._optionsSubsetDiv.style.overflowY = "auto";
  27772. this._optionsSubsetDiv.style.maxHeight = "200px";
  27773. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27774. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27775. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27776. _this._displayStatistics = element.checked;
  27777. });
  27778. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27779. _this._displayLogs = element.checked;
  27780. });
  27781. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27782. _this._displayTree = element.checked;
  27783. _this._needToRefreshMeshesTree = true;
  27784. });
  27785. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27786. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27787. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27788. _this._scene.forceShowBoundingBoxes = element.checked;
  27789. });
  27790. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27791. _this._labelsEnabled = element.checked;
  27792. if (!_this._labelsEnabled) {
  27793. _this._clearLabels();
  27794. }
  27795. });
  27796. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27797. if (element.checked) {
  27798. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27799. }
  27800. else {
  27801. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27802. }
  27803. });
  27804. ;
  27805. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27806. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27807. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27808. if (element.checked) {
  27809. _this._scene.forceWireframe = false;
  27810. _this._scene.forcePointsCloud = false;
  27811. }
  27812. });
  27813. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27814. if (element.checked) {
  27815. _this._scene.forceWireframe = true;
  27816. _this._scene.forcePointsCloud = false;
  27817. }
  27818. });
  27819. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27820. if (element.checked) {
  27821. _this._scene.forceWireframe = false;
  27822. _this._scene.forcePointsCloud = true;
  27823. }
  27824. });
  27825. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27826. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27827. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27828. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27829. });
  27830. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27831. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27832. });
  27833. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27834. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27835. });
  27836. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27837. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27838. });
  27839. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27840. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27841. });
  27842. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27843. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27844. });
  27845. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27846. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27847. });
  27848. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27849. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27850. });
  27851. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27852. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27853. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27854. _this._scene.animationsEnabled = element.checked;
  27855. });
  27856. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27857. _this._scene.collisionsEnabled = element.checked;
  27858. });
  27859. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27860. _this._scene.fogEnabled = element.checked;
  27861. });
  27862. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27863. _this._scene.lensFlaresEnabled = element.checked;
  27864. });
  27865. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27866. _this._scene.lightsEnabled = element.checked;
  27867. });
  27868. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27869. _this._scene.particlesEnabled = element.checked;
  27870. });
  27871. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27872. _this._scene.postProcessesEnabled = element.checked;
  27873. });
  27874. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27875. _this._scene.proceduralTexturesEnabled = element.checked;
  27876. });
  27877. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27878. _this._scene.renderTargetsEnabled = element.checked;
  27879. });
  27880. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27881. _this._scene.shadowsEnabled = element.checked;
  27882. });
  27883. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27884. _this._scene.skeletonsEnabled = element.checked;
  27885. });
  27886. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27887. _this._scene.spritesEnabled = element.checked;
  27888. });
  27889. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27890. _this._scene.texturesEnabled = element.checked;
  27891. });
  27892. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27893. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27894. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27895. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27896. if (element.checked) {
  27897. _this._scene.headphone = true;
  27898. }
  27899. });
  27900. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27901. if (element.checked) {
  27902. _this._scene.headphone = false;
  27903. }
  27904. });
  27905. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27906. _this._scene.audioEnabled = !element.checked;
  27907. });
  27908. }
  27909. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27910. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27911. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27912. _this._scene.dumpNextRenderTargets = true;
  27913. });
  27914. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27915. this._globalDiv.appendChild(this._statsDiv);
  27916. this._globalDiv.appendChild(this._logDiv);
  27917. this._globalDiv.appendChild(this._optionsDiv);
  27918. this._globalDiv.appendChild(this._treeDiv);
  27919. }
  27920. };
  27921. DebugLayer.prototype._displayStats = function () {
  27922. var scene = this._scene;
  27923. var engine = scene.getEngine();
  27924. var glInfo = engine.getGlInfo();
  27925. 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>";
  27926. if (this.customStatsFunction) {
  27927. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27928. }
  27929. };
  27930. return DebugLayer;
  27931. })();
  27932. BABYLON.DebugLayer = DebugLayer;
  27933. })(BABYLON || (BABYLON = {}));
  27934. //# sourceMappingURL=babylon.debugLayer.js.map
  27935. var BABYLON;
  27936. (function (BABYLON) {
  27937. var RawTexture = (function (_super) {
  27938. __extends(RawTexture, _super);
  27939. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27940. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27941. if (invertY === void 0) { invertY = false; }
  27942. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27943. _super.call(this, null, scene, !generateMipMaps, invertY);
  27944. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27945. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27946. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27947. }
  27948. // Statics
  27949. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27950. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27951. if (invertY === void 0) { invertY = false; }
  27952. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27953. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27954. };
  27955. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27956. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27957. if (invertY === void 0) { invertY = false; }
  27958. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27959. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27960. };
  27961. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27962. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27963. if (invertY === void 0) { invertY = false; }
  27964. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27965. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27966. };
  27967. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27968. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27969. if (invertY === void 0) { invertY = false; }
  27970. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27971. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27972. };
  27973. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27974. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27975. if (invertY === void 0) { invertY = false; }
  27976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27977. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27978. };
  27979. return RawTexture;
  27980. })(BABYLON.Texture);
  27981. BABYLON.RawTexture = RawTexture;
  27982. })(BABYLON || (BABYLON = {}));
  27983. //# sourceMappingURL=babylon.rawTexture.js.map
  27984. var BABYLON;
  27985. (function (BABYLON) {
  27986. var IndexedVector2 = (function (_super) {
  27987. __extends(IndexedVector2, _super);
  27988. function IndexedVector2(original, index) {
  27989. _super.call(this, original.x, original.y);
  27990. this.index = index;
  27991. }
  27992. return IndexedVector2;
  27993. })(BABYLON.Vector2);
  27994. var PolygonPoints = (function () {
  27995. function PolygonPoints() {
  27996. this.elements = new Array();
  27997. }
  27998. PolygonPoints.prototype.add = function (originalPoints) {
  27999. var _this = this;
  28000. var result = new Array();
  28001. originalPoints.forEach(function (point) {
  28002. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  28003. var newPoint = new IndexedVector2(point, _this.elements.length);
  28004. result.push(newPoint);
  28005. _this.elements.push(newPoint);
  28006. }
  28007. });
  28008. return result;
  28009. };
  28010. PolygonPoints.prototype.computeBounds = function () {
  28011. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28012. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  28013. this.elements.forEach(function (point) {
  28014. // x
  28015. if (point.x < lmin.x) {
  28016. lmin.x = point.x;
  28017. }
  28018. else if (point.x > lmax.x) {
  28019. lmax.x = point.x;
  28020. }
  28021. // y
  28022. if (point.y < lmin.y) {
  28023. lmin.y = point.y;
  28024. }
  28025. else if (point.y > lmax.y) {
  28026. lmax.y = point.y;
  28027. }
  28028. });
  28029. return {
  28030. min: lmin,
  28031. max: lmax,
  28032. width: lmax.x - lmin.x,
  28033. height: lmax.y - lmin.y
  28034. };
  28035. };
  28036. return PolygonPoints;
  28037. })();
  28038. var Polygon = (function () {
  28039. function Polygon() {
  28040. }
  28041. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  28042. return [
  28043. new BABYLON.Vector2(xmin, ymin),
  28044. new BABYLON.Vector2(xmax, ymin),
  28045. new BABYLON.Vector2(xmax, ymax),
  28046. new BABYLON.Vector2(xmin, ymax)
  28047. ];
  28048. };
  28049. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  28050. if (cx === void 0) { cx = 0; }
  28051. if (cy === void 0) { cy = 0; }
  28052. if (numberOfSides === void 0) { numberOfSides = 32; }
  28053. var result = new Array();
  28054. var angle = 0;
  28055. var increment = (Math.PI * 2) / numberOfSides;
  28056. for (var i = 0; i < numberOfSides; i++) {
  28057. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  28058. angle -= increment;
  28059. }
  28060. return result;
  28061. };
  28062. Polygon.Parse = function (input) {
  28063. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  28064. var i, result = [];
  28065. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  28066. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  28067. }
  28068. return result;
  28069. };
  28070. Polygon.StartingAt = function (x, y) {
  28071. return BABYLON.Path2.StartingAt(x, y);
  28072. };
  28073. return Polygon;
  28074. })();
  28075. BABYLON.Polygon = Polygon;
  28076. var PolygonMeshBuilder = (function () {
  28077. function PolygonMeshBuilder(name, contours, scene) {
  28078. this._points = new PolygonPoints();
  28079. if (!("poly2tri" in window)) {
  28080. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  28081. }
  28082. this._name = name;
  28083. this._scene = scene;
  28084. var points;
  28085. if (contours instanceof BABYLON.Path2) {
  28086. points = contours.getPoints();
  28087. }
  28088. else {
  28089. points = contours;
  28090. }
  28091. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  28092. }
  28093. PolygonMeshBuilder.prototype.addHole = function (hole) {
  28094. this._swctx.addHole(this._points.add(hole));
  28095. return this;
  28096. };
  28097. PolygonMeshBuilder.prototype.build = function (updatable) {
  28098. if (updatable === void 0) { updatable = false; }
  28099. var result = new BABYLON.Mesh(this._name, this._scene);
  28100. var normals = [];
  28101. var positions = [];
  28102. var uvs = [];
  28103. var bounds = this._points.computeBounds();
  28104. this._points.elements.forEach(function (p) {
  28105. normals.push(0, 1.0, 0);
  28106. positions.push(p.x, 0, p.y);
  28107. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  28108. });
  28109. var indices = [];
  28110. this._swctx.triangulate();
  28111. this._swctx.getTriangles().forEach(function (triangle) {
  28112. triangle.getPoints().forEach(function (point) {
  28113. indices.push(point.index);
  28114. });
  28115. });
  28116. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  28117. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  28118. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  28119. result.setIndices(indices);
  28120. return result;
  28121. };
  28122. return PolygonMeshBuilder;
  28123. })();
  28124. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  28125. })(BABYLON || (BABYLON = {}));
  28126. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  28127. (function (BABYLON) {
  28128. var SimplificationSettings = (function () {
  28129. function SimplificationSettings(quality, distance) {
  28130. this.quality = quality;
  28131. this.distance = distance;
  28132. }
  28133. return SimplificationSettings;
  28134. })();
  28135. BABYLON.SimplificationSettings = SimplificationSettings;
  28136. var SimplificationQueue = (function () {
  28137. function SimplificationQueue() {
  28138. this.running = false;
  28139. this._simplificationArray = [];
  28140. }
  28141. SimplificationQueue.prototype.addTask = function (task) {
  28142. this._simplificationArray.push(task);
  28143. };
  28144. SimplificationQueue.prototype.executeNext = function () {
  28145. var task = this._simplificationArray.pop();
  28146. if (task) {
  28147. this.running = true;
  28148. this.runSimplification(task);
  28149. }
  28150. else {
  28151. this.running = false;
  28152. }
  28153. };
  28154. SimplificationQueue.prototype.runSimplification = function (task) {
  28155. var _this = this;
  28156. if (task.parallelProcessing) {
  28157. //parallel simplifier
  28158. task.settings.forEach(function (setting) {
  28159. var simplifier = _this.getSimplifier(task);
  28160. simplifier.simplify(setting, function (newMesh) {
  28161. task.mesh.addLODLevel(setting.distance, newMesh);
  28162. newMesh.isVisible = true;
  28163. //check if it is the last
  28164. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  28165. //all done, run the success callback.
  28166. task.successCallback();
  28167. }
  28168. _this.executeNext();
  28169. });
  28170. });
  28171. }
  28172. else {
  28173. //single simplifier.
  28174. var simplifier = this.getSimplifier(task);
  28175. var runDecimation = function (setting, callback) {
  28176. simplifier.simplify(setting, function (newMesh) {
  28177. task.mesh.addLODLevel(setting.distance, newMesh);
  28178. newMesh.isVisible = true;
  28179. //run the next quality level
  28180. callback();
  28181. });
  28182. };
  28183. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  28184. runDecimation(task.settings[loop.index], function () {
  28185. loop.executeNext();
  28186. });
  28187. }, function () {
  28188. //execution ended, run the success callback.
  28189. if (task.successCallback) {
  28190. task.successCallback();
  28191. }
  28192. _this.executeNext();
  28193. });
  28194. }
  28195. };
  28196. SimplificationQueue.prototype.getSimplifier = function (task) {
  28197. switch (task.simplificationType) {
  28198. case 0 /* QUADRATIC */:
  28199. default:
  28200. return new QuadraticErrorSimplification(task.mesh);
  28201. }
  28202. };
  28203. return SimplificationQueue;
  28204. })();
  28205. BABYLON.SimplificationQueue = SimplificationQueue;
  28206. /**
  28207. * The implemented types of simplification.
  28208. * At the moment only Quadratic Error Decimation is implemented.
  28209. */
  28210. (function (SimplificationType) {
  28211. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  28212. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  28213. var SimplificationType = BABYLON.SimplificationType;
  28214. var DecimationTriangle = (function () {
  28215. function DecimationTriangle(vertices) {
  28216. this.vertices = vertices;
  28217. this.error = new Array(4);
  28218. this.deleted = false;
  28219. this.isDirty = false;
  28220. this.deletePending = false;
  28221. this.borderFactor = 0;
  28222. }
  28223. return DecimationTriangle;
  28224. })();
  28225. BABYLON.DecimationTriangle = DecimationTriangle;
  28226. var DecimationVertex = (function () {
  28227. function DecimationVertex(position, normal, uv, id) {
  28228. this.position = position;
  28229. this.normal = normal;
  28230. this.uv = uv;
  28231. this.id = id;
  28232. this.isBorder = true;
  28233. this.q = new QuadraticMatrix();
  28234. this.triangleCount = 0;
  28235. this.triangleStart = 0;
  28236. }
  28237. return DecimationVertex;
  28238. })();
  28239. BABYLON.DecimationVertex = DecimationVertex;
  28240. var QuadraticMatrix = (function () {
  28241. function QuadraticMatrix(data) {
  28242. this.data = new Array(10);
  28243. for (var i = 0; i < 10; ++i) {
  28244. if (data && data[i]) {
  28245. this.data[i] = data[i];
  28246. }
  28247. else {
  28248. this.data[i] = 0;
  28249. }
  28250. }
  28251. }
  28252. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  28253. 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];
  28254. return det;
  28255. };
  28256. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  28257. for (var i = 0; i < 10; ++i) {
  28258. this.data[i] += matrix.data[i];
  28259. }
  28260. };
  28261. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  28262. for (var i = 0; i < 10; ++i) {
  28263. this.data[i] += data[i];
  28264. }
  28265. };
  28266. QuadraticMatrix.prototype.add = function (matrix) {
  28267. var m = new QuadraticMatrix();
  28268. for (var i = 0; i < 10; ++i) {
  28269. m.data[i] = this.data[i] + matrix.data[i];
  28270. }
  28271. return m;
  28272. };
  28273. QuadraticMatrix.FromData = function (a, b, c, d) {
  28274. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  28275. };
  28276. //returning an array to avoid garbage collection
  28277. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  28278. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  28279. };
  28280. return QuadraticMatrix;
  28281. })();
  28282. BABYLON.QuadraticMatrix = QuadraticMatrix;
  28283. var Reference = (function () {
  28284. function Reference(vertexId, triangleId) {
  28285. this.vertexId = vertexId;
  28286. this.triangleId = triangleId;
  28287. }
  28288. return Reference;
  28289. })();
  28290. BABYLON.Reference = Reference;
  28291. /**
  28292. * An implementation of the Quadratic Error simplification algorithm.
  28293. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  28294. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  28295. * @author RaananW
  28296. */
  28297. var QuadraticErrorSimplification = (function () {
  28298. function QuadraticErrorSimplification(_mesh) {
  28299. this._mesh = _mesh;
  28300. this.initialised = false;
  28301. this.syncIterations = 5000;
  28302. this.aggressiveness = 7;
  28303. this.decimationIterations = 100;
  28304. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  28305. }
  28306. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  28307. var _this = this;
  28308. this.initDecimatedMesh();
  28309. //iterating through the submeshes array, one after the other.
  28310. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  28311. _this.initWithMesh(_this._mesh, loop.index, function () {
  28312. _this.runDecimation(settings, loop.index, function () {
  28313. loop.executeNext();
  28314. });
  28315. });
  28316. }, function () {
  28317. setTimeout(function () {
  28318. successCallback(_this._reconstructedMesh);
  28319. }, 0);
  28320. });
  28321. };
  28322. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  28323. var _this = this;
  28324. var gCount = 0;
  28325. triangle.vertices.forEach(function (vId) {
  28326. var count = 0;
  28327. var vPos = _this.vertices[vId].position;
  28328. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  28329. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  28330. ++count;
  28331. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  28332. ++count;
  28333. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  28334. ++count;
  28335. if (count > 1) {
  28336. ++gCount;
  28337. }
  28338. ;
  28339. });
  28340. if (gCount > 1) {
  28341. console.log(triangle, gCount);
  28342. }
  28343. return gCount > 1;
  28344. };
  28345. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  28346. var _this = this;
  28347. var targetCount = ~~(this.triangles.length * settings.quality);
  28348. var deletedTriangles = 0;
  28349. var triangleCount = this.triangles.length;
  28350. var iterationFunction = function (iteration, callback) {
  28351. setTimeout(function () {
  28352. if (iteration % 5 === 0) {
  28353. _this.updateMesh(iteration === 0);
  28354. }
  28355. for (var i = 0; i < _this.triangles.length; ++i) {
  28356. _this.triangles[i].isDirty = false;
  28357. }
  28358. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  28359. var trianglesIterator = function (i) {
  28360. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  28361. var t = _this.triangles[tIdx];
  28362. if (!t)
  28363. return;
  28364. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28365. return;
  28366. }
  28367. for (var j = 0; j < 3; ++j) {
  28368. if (t.error[j] < threshold) {
  28369. var deleted0 = [];
  28370. var deleted1 = [];
  28371. var i0 = t.vertices[j];
  28372. var i1 = t.vertices[(j + 1) % 3];
  28373. var v0 = _this.vertices[i0];
  28374. var v1 = _this.vertices[i1];
  28375. if (v0.isBorder !== v1.isBorder)
  28376. continue;
  28377. var p = BABYLON.Vector3.Zero();
  28378. var n = BABYLON.Vector3.Zero();
  28379. var uv = BABYLON.Vector2.Zero();
  28380. var color = new BABYLON.Color4(0, 0, 0, 1);
  28381. _this.calculateError(v0, v1, p, n, uv, color);
  28382. var delTr = [];
  28383. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28384. continue;
  28385. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28386. continue;
  28387. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28388. continue;
  28389. var uniqueArray = [];
  28390. delTr.forEach(function (deletedT) {
  28391. if (uniqueArray.indexOf(deletedT) === -1) {
  28392. deletedT.deletePending = true;
  28393. uniqueArray.push(deletedT);
  28394. }
  28395. });
  28396. if (uniqueArray.length % 2 != 0) {
  28397. continue;
  28398. }
  28399. v0.normal = n;
  28400. if (v0.uv)
  28401. v0.uv = uv;
  28402. else if (v0.color)
  28403. v0.color = color;
  28404. v0.q = v1.q.add(v0.q);
  28405. v0.position = p;
  28406. var tStart = _this.references.length;
  28407. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28408. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28409. var tCount = _this.references.length - tStart;
  28410. if (tCount <= v0.triangleCount) {
  28411. if (tCount) {
  28412. for (var c = 0; c < tCount; c++) {
  28413. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28414. }
  28415. }
  28416. }
  28417. else {
  28418. v0.triangleStart = tStart;
  28419. }
  28420. v0.triangleCount = tCount;
  28421. break;
  28422. }
  28423. }
  28424. };
  28425. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28426. return (triangleCount - deletedTriangles <= targetCount);
  28427. });
  28428. }, 0);
  28429. };
  28430. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28431. if (triangleCount - deletedTriangles <= targetCount)
  28432. loop.breakLoop();
  28433. else {
  28434. iterationFunction(loop.index, function () {
  28435. loop.executeNext();
  28436. });
  28437. }
  28438. }, function () {
  28439. setTimeout(function () {
  28440. //reconstruct this part of the mesh
  28441. _this.reconstructMesh(submeshIndex);
  28442. successCallback();
  28443. }, 0);
  28444. });
  28445. };
  28446. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28447. var _this = this;
  28448. if (!mesh)
  28449. return;
  28450. this.vertices = [];
  28451. this.triangles = [];
  28452. this._mesh = mesh;
  28453. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28454. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28455. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28456. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28457. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28458. var indices = mesh.getIndices();
  28459. var submesh = mesh.subMeshes[submeshIndex];
  28460. var vertexInit = function (i) {
  28461. var offset = i + submesh.verticesStart;
  28462. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28463. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28464. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28465. }
  28466. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28467. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28468. }
  28469. _this.vertices.push(vertex);
  28470. };
  28471. //var totalVertices = mesh.getTotalVertices();
  28472. var totalVertices = submesh.verticesCount;
  28473. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28474. var indicesInit = function (i) {
  28475. var offset = (submesh.indexStart / 3) + i;
  28476. var pos = (offset * 3);
  28477. var i0 = indices[pos + 0] - submesh.verticesStart;
  28478. var i1 = indices[pos + 1] - submesh.verticesStart;
  28479. var i2 = indices[pos + 2] - submesh.verticesStart;
  28480. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28481. _this.triangles.push(triangle);
  28482. };
  28483. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28484. _this.init(callback);
  28485. });
  28486. });
  28487. };
  28488. QuadraticErrorSimplification.prototype.init = function (callback) {
  28489. var _this = this;
  28490. var triangleInit1 = function (i) {
  28491. var t = _this.triangles[i];
  28492. 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();
  28493. for (var j = 0; j < 3; j++) {
  28494. _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))));
  28495. }
  28496. };
  28497. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28498. var triangleInit2 = function (i) {
  28499. var t = _this.triangles[i];
  28500. for (var j = 0; j < 3; ++j) {
  28501. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28502. }
  28503. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28504. };
  28505. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28506. _this.initialised = true;
  28507. callback();
  28508. });
  28509. });
  28510. };
  28511. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28512. var newTriangles = [];
  28513. var i;
  28514. for (i = 0; i < this.vertices.length; ++i) {
  28515. this.vertices[i].triangleCount = 0;
  28516. }
  28517. var t;
  28518. var j;
  28519. for (i = 0; i < this.triangles.length; ++i) {
  28520. if (!this.triangles[i].deleted) {
  28521. t = this.triangles[i];
  28522. for (j = 0; j < 3; ++j) {
  28523. this.vertices[t.vertices[j]].triangleCount = 1;
  28524. }
  28525. newTriangles.push(t);
  28526. }
  28527. }
  28528. var newVerticesOrder = [];
  28529. //compact vertices, get the IDs of the vertices used.
  28530. var dst = 0;
  28531. for (i = 0; i < this.vertices.length; ++i) {
  28532. if (this.vertices[i].triangleCount) {
  28533. this.vertices[i].triangleStart = dst;
  28534. this.vertices[dst].position = this.vertices[i].position;
  28535. this.vertices[dst].normal = this.vertices[i].normal;
  28536. this.vertices[dst].uv = this.vertices[i].uv;
  28537. this.vertices[dst].color = this.vertices[i].color;
  28538. newVerticesOrder.push(dst);
  28539. dst++;
  28540. }
  28541. }
  28542. for (i = 0; i < newTriangles.length; ++i) {
  28543. t = newTriangles[i];
  28544. for (j = 0; j < 3; ++j) {
  28545. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28546. }
  28547. }
  28548. this.vertices = this.vertices.slice(0, dst);
  28549. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28550. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28551. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28552. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28553. for (i = 0; i < newVerticesOrder.length; ++i) {
  28554. newPositionData.push(this.vertices[i].position.x);
  28555. newPositionData.push(this.vertices[i].position.y);
  28556. newPositionData.push(this.vertices[i].position.z);
  28557. newNormalData.push(this.vertices[i].normal.x);
  28558. newNormalData.push(this.vertices[i].normal.y);
  28559. newNormalData.push(this.vertices[i].normal.z);
  28560. if (this.vertices[i].uv) {
  28561. newUVsData.push(this.vertices[i].uv.x);
  28562. newUVsData.push(this.vertices[i].uv.y);
  28563. }
  28564. else if (this.vertices[i].color) {
  28565. newColorsData.push(this.vertices[i].color.r);
  28566. newColorsData.push(this.vertices[i].color.g);
  28567. newColorsData.push(this.vertices[i].color.b);
  28568. newColorsData.push(this.vertices[i].color.a);
  28569. }
  28570. }
  28571. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28572. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28573. var submeshesArray = this._reconstructedMesh.subMeshes;
  28574. this._reconstructedMesh.subMeshes = [];
  28575. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28576. for (i = 0; i < newTriangles.length; ++i) {
  28577. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28578. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28579. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28580. }
  28581. //overwriting the old vertex buffers and indices.
  28582. this._reconstructedMesh.setIndices(newIndicesArray);
  28583. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28584. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28585. if (newUVsData.length > 0)
  28586. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28587. if (newColorsData.length > 0)
  28588. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28589. //create submesh
  28590. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28591. if (submeshIndex > 0) {
  28592. this._reconstructedMesh.subMeshes = [];
  28593. submeshesArray.forEach(function (submesh) {
  28594. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28595. });
  28596. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28597. }
  28598. };
  28599. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28600. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28601. this._reconstructedMesh.material = this._mesh.material;
  28602. this._reconstructedMesh.parent = this._mesh.parent;
  28603. this._reconstructedMesh.isVisible = false;
  28604. };
  28605. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28606. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28607. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28608. if (t.deleted)
  28609. continue;
  28610. var s = this.references[vertex1.triangleStart + i].vertexId;
  28611. var id1 = t.vertices[(s + 1) % 3];
  28612. var id2 = t.vertices[(s + 2) % 3];
  28613. if ((id1 === index2 || id2 === index2)) {
  28614. deletedArray[i] = true;
  28615. delTr.push(t);
  28616. continue;
  28617. }
  28618. var d1 = this.vertices[id1].position.subtract(point);
  28619. d1 = d1.normalize();
  28620. var d2 = this.vertices[id2].position.subtract(point);
  28621. d2 = d2.normalize();
  28622. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28623. return true;
  28624. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28625. deletedArray[i] = false;
  28626. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28627. return true;
  28628. }
  28629. return false;
  28630. };
  28631. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28632. var newDeleted = deletedTriangles;
  28633. for (var i = 0; i < vertex.triangleCount; ++i) {
  28634. var ref = this.references[vertex.triangleStart + i];
  28635. var t = this.triangles[ref.triangleId];
  28636. if (t.deleted)
  28637. continue;
  28638. if (deletedArray[i] && t.deletePending) {
  28639. t.deleted = true;
  28640. newDeleted++;
  28641. continue;
  28642. }
  28643. t.vertices[ref.vertexId] = vertexId;
  28644. t.isDirty = true;
  28645. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28646. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28647. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28648. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28649. this.references.push(ref);
  28650. }
  28651. return newDeleted;
  28652. };
  28653. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28654. for (var i = 0; i < this.vertices.length; ++i) {
  28655. var vCount = [];
  28656. var vId = [];
  28657. var v = this.vertices[i];
  28658. var j;
  28659. for (j = 0; j < v.triangleCount; ++j) {
  28660. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28661. for (var ii = 0; ii < 3; ii++) {
  28662. var ofs = 0;
  28663. var id = triangle.vertices[ii];
  28664. while (ofs < vCount.length) {
  28665. if (vId[ofs] === id)
  28666. break;
  28667. ++ofs;
  28668. }
  28669. if (ofs === vCount.length) {
  28670. vCount.push(1);
  28671. vId.push(id);
  28672. }
  28673. else {
  28674. vCount[ofs]++;
  28675. }
  28676. }
  28677. }
  28678. for (j = 0; j < vCount.length; ++j) {
  28679. if (vCount[j] === 1) {
  28680. this.vertices[vId[j]].isBorder = true;
  28681. }
  28682. else {
  28683. this.vertices[vId[j]].isBorder = false;
  28684. }
  28685. }
  28686. }
  28687. };
  28688. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28689. if (identifyBorders === void 0) { identifyBorders = false; }
  28690. var i;
  28691. if (!identifyBorders) {
  28692. var newTrianglesVector = [];
  28693. for (i = 0; i < this.triangles.length; ++i) {
  28694. if (!this.triangles[i].deleted) {
  28695. newTrianglesVector.push(this.triangles[i]);
  28696. }
  28697. }
  28698. this.triangles = newTrianglesVector;
  28699. }
  28700. for (i = 0; i < this.vertices.length; ++i) {
  28701. this.vertices[i].triangleCount = 0;
  28702. this.vertices[i].triangleStart = 0;
  28703. }
  28704. var t;
  28705. var j;
  28706. var v;
  28707. for (i = 0; i < this.triangles.length; ++i) {
  28708. t = this.triangles[i];
  28709. for (j = 0; j < 3; ++j) {
  28710. v = this.vertices[t.vertices[j]];
  28711. v.triangleCount++;
  28712. }
  28713. }
  28714. var tStart = 0;
  28715. for (i = 0; i < this.vertices.length; ++i) {
  28716. this.vertices[i].triangleStart = tStart;
  28717. tStart += this.vertices[i].triangleCount;
  28718. this.vertices[i].triangleCount = 0;
  28719. }
  28720. var newReferences = new Array(this.triangles.length * 3);
  28721. for (i = 0; i < this.triangles.length; ++i) {
  28722. t = this.triangles[i];
  28723. for (j = 0; j < 3; ++j) {
  28724. v = this.vertices[t.vertices[j]];
  28725. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28726. v.triangleCount++;
  28727. }
  28728. }
  28729. this.references = newReferences;
  28730. if (identifyBorders) {
  28731. this.identifyBorder();
  28732. }
  28733. };
  28734. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28735. var x = point.x;
  28736. var y = point.y;
  28737. var z = point.z;
  28738. 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];
  28739. };
  28740. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28741. var q = vertex1.q.add(vertex2.q);
  28742. var border = vertex1.isBorder && vertex2.isBorder;
  28743. var error = 0;
  28744. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28745. if (qDet !== 0 && !border) {
  28746. if (!pointResult) {
  28747. pointResult = BABYLON.Vector3.Zero();
  28748. }
  28749. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28750. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28751. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28752. error = this.vertexError(q, pointResult);
  28753. //TODO this should be correctly calculated
  28754. if (normalResult) {
  28755. normalResult.copyFrom(vertex1.normal);
  28756. if (vertex1.uv)
  28757. uvResult.copyFrom(vertex1.uv);
  28758. else if (vertex1.color)
  28759. colorResult.copyFrom(vertex1.color);
  28760. }
  28761. }
  28762. else {
  28763. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28764. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28765. var error1 = this.vertexError(q, vertex1.position);
  28766. var error2 = this.vertexError(q, vertex2.position);
  28767. var error3 = this.vertexError(q, p3);
  28768. error = Math.min(error1, error2, error3);
  28769. if (error === error1) {
  28770. if (pointResult) {
  28771. pointResult.copyFrom(vertex1.position);
  28772. normalResult.copyFrom(vertex1.normal);
  28773. if (vertex1.uv)
  28774. uvResult.copyFrom(vertex1.uv);
  28775. else if (vertex1.color)
  28776. colorResult.copyFrom(vertex1.color);
  28777. }
  28778. }
  28779. else if (error === error2) {
  28780. if (pointResult) {
  28781. pointResult.copyFrom(vertex2.position);
  28782. normalResult.copyFrom(vertex2.normal);
  28783. if (vertex2.uv)
  28784. uvResult.copyFrom(vertex2.uv);
  28785. else if (vertex2.color)
  28786. colorResult.copyFrom(vertex2.color);
  28787. }
  28788. }
  28789. else {
  28790. if (pointResult) {
  28791. pointResult.copyFrom(p3);
  28792. normalResult.copyFrom(vertex1.normal);
  28793. if (vertex1.uv)
  28794. uvResult.copyFrom(vertex1.uv);
  28795. else if (vertex1.color)
  28796. colorResult.copyFrom(vertex1.color);
  28797. }
  28798. }
  28799. }
  28800. return error;
  28801. };
  28802. return QuadraticErrorSimplification;
  28803. })();
  28804. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28805. })(BABYLON || (BABYLON = {}));
  28806. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28807. (function (BABYLON) {
  28808. var Analyser = (function () {
  28809. function Analyser(scene) {
  28810. this.SMOOTHING = 0.75;
  28811. this.FFT_SIZE = 512;
  28812. this.BARGRAPHAMPLITUDE = 256;
  28813. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28814. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28815. this._scene = scene;
  28816. this._audioEngine = BABYLON.Engine.audioEngine;
  28817. if (this._audioEngine.canUseWebAudio) {
  28818. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28819. this._webAudioAnalyser.minDecibels = -140;
  28820. this._webAudioAnalyser.maxDecibels = 0;
  28821. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28822. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28823. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28824. }
  28825. }
  28826. Analyser.prototype.getFrequencyBinCount = function () {
  28827. if (this._audioEngine.canUseWebAudio) {
  28828. return this._webAudioAnalyser.frequencyBinCount;
  28829. }
  28830. else {
  28831. return 0;
  28832. }
  28833. };
  28834. Analyser.prototype.getByteFrequencyData = function () {
  28835. if (this._audioEngine.canUseWebAudio) {
  28836. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28837. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28838. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28839. }
  28840. return this._byteFreqs;
  28841. };
  28842. Analyser.prototype.getByteTimeDomainData = function () {
  28843. if (this._audioEngine.canUseWebAudio) {
  28844. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28845. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28846. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28847. }
  28848. return this._byteTime;
  28849. };
  28850. Analyser.prototype.getFloatFrequencyData = function () {
  28851. if (this._audioEngine.canUseWebAudio) {
  28852. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28853. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28854. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28855. }
  28856. return this._floatFreqs;
  28857. };
  28858. Analyser.prototype.drawDebugCanvas = function () {
  28859. var _this = this;
  28860. if (this._audioEngine.canUseWebAudio) {
  28861. if (!this._debugCanvas) {
  28862. this._debugCanvas = document.createElement("canvas");
  28863. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28864. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28865. this._debugCanvas.style.position = "absolute";
  28866. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28867. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28868. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28869. document.body.appendChild(this._debugCanvas);
  28870. this._registerFunc = function () {
  28871. _this.drawDebugCanvas();
  28872. };
  28873. this._scene.registerBeforeRender(this._registerFunc);
  28874. }
  28875. if (this._registerFunc) {
  28876. var workingArray = this.getByteFrequencyData();
  28877. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28878. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28879. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28880. var value = workingArray[i];
  28881. var percent = value / this.BARGRAPHAMPLITUDE;
  28882. var height = this.DEBUGCANVASSIZE.height * percent;
  28883. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28884. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28885. var hue = i / this.getFrequencyBinCount() * 360;
  28886. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28887. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28888. }
  28889. }
  28890. }
  28891. };
  28892. Analyser.prototype.stopDebugCanvas = function () {
  28893. if (this._debugCanvas) {
  28894. this._scene.unregisterBeforeRender(this._registerFunc);
  28895. this._registerFunc = null;
  28896. document.body.removeChild(this._debugCanvas);
  28897. this._debugCanvas = null;
  28898. this._debugCanvasContext = null;
  28899. }
  28900. };
  28901. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28902. if (this._audioEngine.canUseWebAudio) {
  28903. inputAudioNode.connect(this._webAudioAnalyser);
  28904. this._webAudioAnalyser.connect(outputAudioNode);
  28905. }
  28906. };
  28907. Analyser.prototype.dispose = function () {
  28908. if (this._audioEngine.canUseWebAudio) {
  28909. this._webAudioAnalyser.disconnect();
  28910. }
  28911. };
  28912. return Analyser;
  28913. })();
  28914. BABYLON.Analyser = Analyser;
  28915. })(BABYLON || (BABYLON = {}));
  28916. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28917. (function (BABYLON) {
  28918. var DepthRenderer = (function () {
  28919. function DepthRenderer(scene, type) {
  28920. var _this = this;
  28921. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28922. this._viewMatrix = BABYLON.Matrix.Zero();
  28923. this._projectionMatrix = BABYLON.Matrix.Zero();
  28924. this._transformMatrix = BABYLON.Matrix.Zero();
  28925. this._worldViewProjection = BABYLON.Matrix.Zero();
  28926. this._scene = scene;
  28927. var engine = scene.getEngine();
  28928. // Render target
  28929. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28930. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28931. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28932. this._depthMap.refreshRate = 1;
  28933. this._depthMap.renderParticles = false;
  28934. this._depthMap.renderList = null;
  28935. // Custom render function
  28936. var renderSubMesh = function (subMesh) {
  28937. var mesh = subMesh.getRenderingMesh();
  28938. var scene = _this._scene;
  28939. var engine = scene.getEngine();
  28940. // Culling
  28941. engine.setState(subMesh.getMaterial().backFaceCulling);
  28942. // Managing instances
  28943. var batch = mesh._getInstancesRenderList(subMesh._id);
  28944. if (batch.mustReturn) {
  28945. return;
  28946. }
  28947. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28948. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28949. engine.enableEffect(_this._effect);
  28950. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28951. var material = subMesh.getMaterial();
  28952. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28953. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28954. // Alpha test
  28955. if (material && material.needAlphaTesting()) {
  28956. var alphaTexture = material.getAlphaTestTexture();
  28957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28959. }
  28960. // Bones
  28961. if (mesh.useBones) {
  28962. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28963. }
  28964. // Draw
  28965. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28966. }
  28967. };
  28968. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28969. var index;
  28970. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28971. renderSubMesh(opaqueSubMeshes.data[index]);
  28972. }
  28973. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28974. renderSubMesh(alphaTestSubMeshes.data[index]);
  28975. }
  28976. };
  28977. }
  28978. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28979. var defines = [];
  28980. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28981. var mesh = subMesh.getMesh();
  28982. var scene = mesh.getScene();
  28983. var material = subMesh.getMaterial();
  28984. // Alpha test
  28985. if (material && material.needAlphaTesting()) {
  28986. defines.push("#define ALPHATEST");
  28987. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28988. attribs.push(BABYLON.VertexBuffer.UVKind);
  28989. defines.push("#define UV1");
  28990. }
  28991. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28992. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28993. defines.push("#define UV2");
  28994. }
  28995. }
  28996. // Bones
  28997. if (mesh.useBones) {
  28998. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28999. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29000. defines.push("#define BONES");
  29001. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29002. }
  29003. // Instances
  29004. if (useInstances) {
  29005. defines.push("#define INSTANCES");
  29006. attribs.push("world0");
  29007. attribs.push("world1");
  29008. attribs.push("world2");
  29009. attribs.push("world3");
  29010. }
  29011. // Get correct effect
  29012. var join = defines.join("\n");
  29013. if (this._cachedDefines !== join) {
  29014. this._cachedDefines = join;
  29015. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  29016. }
  29017. return this._effect.isReady();
  29018. };
  29019. DepthRenderer.prototype.getDepthMap = function () {
  29020. return this._depthMap;
  29021. };
  29022. // Methods
  29023. DepthRenderer.prototype.dispose = function () {
  29024. this._depthMap.dispose();
  29025. };
  29026. return DepthRenderer;
  29027. })();
  29028. BABYLON.DepthRenderer = DepthRenderer;
  29029. })(BABYLON || (BABYLON = {}));
  29030. //# sourceMappingURL=babylon.depthRenderer.js.map
  29031. var BABYLON;
  29032. (function (BABYLON) {
  29033. var SSAORenderingPipeline = (function (_super) {
  29034. __extends(SSAORenderingPipeline, _super);
  29035. /**
  29036. * @constructor
  29037. * @param {string} name - The rendering pipeline name
  29038. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29039. * @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)
  29040. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29041. */
  29042. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  29043. var _this = this;
  29044. _super.call(this, scene.getEngine(), name);
  29045. // Members
  29046. /**
  29047. * The PassPostProcess id in the pipeline that contains the original scene color
  29048. * @type {string}
  29049. */
  29050. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  29051. /**
  29052. * The SSAO PostProcess id in the pipeline
  29053. * @type {string}
  29054. */
  29055. this.SSAORenderEffect = "SSAORenderEffect";
  29056. /**
  29057. * The horizontal blur PostProcess id in the pipeline
  29058. * @type {string}
  29059. */
  29060. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  29061. /**
  29062. * The vertical blur PostProcess id in the pipeline
  29063. * @type {string}
  29064. */
  29065. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  29066. /**
  29067. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  29068. * @type {string}
  29069. */
  29070. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  29071. this._firstUpdate = true;
  29072. this._scene = scene;
  29073. // Set up assets
  29074. this._createRandomTexture();
  29075. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29076. var ssaoRatio = ratio.ssaoRatio || ratio;
  29077. var combineRatio = ratio.combineRatio || ratio;
  29078. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29079. this._createSSAOPostProcess(ssaoRatio);
  29080. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29081. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  29082. this._createSSAOCombinePostProcess(combineRatio);
  29083. // Set up pipeline
  29084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  29085. return _this._originalColorPostProcess;
  29086. }, true));
  29087. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  29088. return _this._ssaoPostProcess;
  29089. }, true));
  29090. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  29091. return _this._blurHPostProcess;
  29092. }, true));
  29093. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  29094. return _this._blurVPostProcess;
  29095. }, true));
  29096. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  29097. return _this._ssaoCombinePostProcess;
  29098. }, true));
  29099. // Finish
  29100. scene.postProcessRenderPipelineManager.addPipeline(this);
  29101. if (cameras)
  29102. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29103. }
  29104. // Public Methods
  29105. /**
  29106. * Returns the horizontal blur PostProcess
  29107. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  29108. */
  29109. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  29110. return this._blurHPostProcess;
  29111. };
  29112. /**
  29113. * Returns the vertical blur PostProcess
  29114. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  29115. */
  29116. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  29117. return this._blurVPostProcess;
  29118. };
  29119. /**
  29120. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  29121. */
  29122. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29123. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29124. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29125. this._originalColorPostProcess = undefined;
  29126. this._ssaoPostProcess = undefined;
  29127. this._blurHPostProcess = undefined;
  29128. this._blurVPostProcess = undefined;
  29129. this._ssaoCombinePostProcess = undefined;
  29130. this._randomTexture.dispose();
  29131. if (disableDepthRender)
  29132. this._scene.disableDepthRenderer();
  29133. };
  29134. // Private Methods
  29135. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  29136. var _this = this;
  29137. var sampleSphere = [
  29138. 0.5381,
  29139. 0.1856,
  29140. -0.4319,
  29141. 0.1379,
  29142. 0.2486,
  29143. 0.4430,
  29144. 0.3371,
  29145. 0.5679,
  29146. -0.0057,
  29147. -0.6999,
  29148. -0.0451,
  29149. -0.0019,
  29150. 0.0689,
  29151. -0.1598,
  29152. -0.8547,
  29153. 0.0560,
  29154. 0.0069,
  29155. -0.1843,
  29156. -0.0146,
  29157. 0.1402,
  29158. 0.0762,
  29159. 0.0100,
  29160. -0.1924,
  29161. -0.0344,
  29162. -0.3577,
  29163. -0.5301,
  29164. -0.4358,
  29165. -0.3169,
  29166. 0.1063,
  29167. 0.0158,
  29168. 0.0103,
  29169. -0.5869,
  29170. 0.0046,
  29171. -0.0897,
  29172. -0.4940,
  29173. 0.3287,
  29174. 0.7119,
  29175. -0.0154,
  29176. -0.0918,
  29177. -0.0533,
  29178. 0.0596,
  29179. -0.5411,
  29180. 0.0352,
  29181. -0.0631,
  29182. 0.5460,
  29183. -0.4776,
  29184. 0.2847,
  29185. -0.0271
  29186. ];
  29187. var samplesFactor = 1.0 / 16.0;
  29188. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29189. this._ssaoPostProcess.onApply = function (effect) {
  29190. if (_this._firstUpdate) {
  29191. effect.setArray3("sampleSphere", sampleSphere);
  29192. effect.setFloat("samplesFactor", samplesFactor);
  29193. effect.setFloat("randTextureTiles", 4.0 / ratio);
  29194. _this._firstUpdate = false;
  29195. }
  29196. effect.setTexture("textureSampler", _this._depthTexture);
  29197. effect.setTexture("randomSampler", _this._randomTexture);
  29198. };
  29199. };
  29200. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  29201. var _this = this;
  29202. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29203. this._ssaoCombinePostProcess.onApply = function (effect) {
  29204. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  29205. };
  29206. };
  29207. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  29208. var size = 512;
  29209. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29210. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29211. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29212. var context = this._randomTexture.getContext();
  29213. var rand = function (min, max) {
  29214. return Math.random() * (max - min) + min;
  29215. };
  29216. for (var x = 0; x < size; x++) {
  29217. for (var y = 0; y < size; y++) {
  29218. var randVector = BABYLON.Vector3.Zero();
  29219. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  29220. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  29221. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  29222. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  29223. context.fillRect(x, y, 1, 1);
  29224. }
  29225. }
  29226. this._randomTexture.update(false);
  29227. };
  29228. return SSAORenderingPipeline;
  29229. })(BABYLON.PostProcessRenderPipeline);
  29230. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  29231. })(BABYLON || (BABYLON = {}));
  29232. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  29233. var BABYLON;
  29234. (function (BABYLON) {
  29235. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  29236. var VolumetricLightScatteringPostProcess = (function (_super) {
  29237. __extends(VolumetricLightScatteringPostProcess, _super);
  29238. /**
  29239. * @constructor
  29240. * @param {string} name - The post-process name
  29241. * @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)
  29242. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  29243. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  29244. * @param {number} samples - The post-process quality, default 100
  29245. * @param {number} samplingMode - The post-process filtering mode
  29246. * @param {BABYLON.Engine} engine - The babylon engine
  29247. * @param {boolean} reusable - If the post-process is reusable
  29248. */
  29249. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  29250. var _this = this;
  29251. if (samples === void 0) { samples = 100; }
  29252. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  29253. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  29254. this._screenCoordinates = BABYLON.Vector2.Zero();
  29255. /**
  29256. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  29257. * @type {boolean}
  29258. */
  29259. this.useCustomMeshPosition = false;
  29260. /**
  29261. * If the post-process should inverse the light scattering direction
  29262. * @type {boolean}
  29263. */
  29264. this.invert = true;
  29265. /**
  29266. * Array containing the excluded meshes not rendered in the internal pass
  29267. */
  29268. this.excludedMeshes = new Array();
  29269. this.exposure = 0.3;
  29270. this.decay = 0.96815;
  29271. this.weight = 0.58767;
  29272. this.density = 0.926;
  29273. var scene = camera.getScene();
  29274. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  29275. // Configure mesh
  29276. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  29277. // Configure
  29278. this._createPass(scene, ratio.passRatio || ratio);
  29279. this.onApply = function (effect) {
  29280. _this._updateMeshScreenCoordinates(scene);
  29281. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  29282. effect.setFloat("exposure", _this.exposure);
  29283. effect.setFloat("decay", _this.decay);
  29284. effect.setFloat("weight", _this.weight);
  29285. effect.setFloat("density", _this.density);
  29286. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  29287. };
  29288. }
  29289. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  29290. var mesh = subMesh.getMesh();
  29291. var defines = [];
  29292. var attribs = [BABYLON.VertexBuffer.PositionKind];
  29293. var material = subMesh.getMaterial();
  29294. var needUV = false;
  29295. // Render this.mesh as default
  29296. if (mesh === this.mesh) {
  29297. defines.push("#define BASIC_RENDER");
  29298. defines.push("#define NEED_UV");
  29299. needUV = true;
  29300. }
  29301. // Alpha test
  29302. if (material) {
  29303. if (material.needAlphaTesting() || mesh === this.mesh)
  29304. defines.push("#define ALPHATEST");
  29305. if (material.opacityTexture !== undefined) {
  29306. defines.push("#define OPACITY");
  29307. if (material.opacityTexture.getAlphaFromRGB)
  29308. defines.push("#define OPACITYRGB");
  29309. if (!needUV)
  29310. defines.push("#define NEED_UV");
  29311. }
  29312. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29313. attribs.push(BABYLON.VertexBuffer.UVKind);
  29314. defines.push("#define UV1");
  29315. }
  29316. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  29317. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  29318. defines.push("#define UV2");
  29319. }
  29320. }
  29321. // Bones
  29322. if (mesh.useBones) {
  29323. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29324. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29325. defines.push("#define BONES");
  29326. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  29327. }
  29328. // Instances
  29329. if (useInstances) {
  29330. defines.push("#define INSTANCES");
  29331. attribs.push("world0");
  29332. attribs.push("world1");
  29333. attribs.push("world2");
  29334. attribs.push("world3");
  29335. }
  29336. // Get correct effect
  29337. var join = defines.join("\n");
  29338. if (this._cachedDefines !== join) {
  29339. this._cachedDefines = join;
  29340. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "opacityLevel"], ["diffuseSampler", "opacitySampler"], join);
  29341. }
  29342. return this._volumetricLightScatteringPass.isReady();
  29343. };
  29344. /**
  29345. * Sets the new light position for light scattering effect
  29346. * @param {BABYLON.Vector3} The new custom light position
  29347. */
  29348. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  29349. this._customMeshPosition = position;
  29350. };
  29351. /**
  29352. * Returns the light position for light scattering effect
  29353. * @return {BABYLON.Vector3} The custom light position
  29354. */
  29355. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  29356. return this._customMeshPosition;
  29357. };
  29358. /**
  29359. * Disposes the internal assets and detaches the post-process from the camera
  29360. */
  29361. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  29362. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  29363. if (rttIndex !== -1) {
  29364. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  29365. }
  29366. this._volumetricLightScatteringRTT.dispose();
  29367. _super.prototype.dispose.call(this, camera);
  29368. };
  29369. /**
  29370. * Returns the render target texture used by the post-process
  29371. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  29372. */
  29373. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  29374. return this._volumetricLightScatteringRTT;
  29375. };
  29376. // Private methods
  29377. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29378. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29379. return true;
  29380. }
  29381. return false;
  29382. };
  29383. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29384. var _this = this;
  29385. var engine = scene.getEngine();
  29386. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29387. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29388. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29389. this._volumetricLightScatteringRTT.renderList = null;
  29390. this._volumetricLightScatteringRTT.renderParticles = false;
  29391. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29392. // Custom render function for submeshes
  29393. var renderSubMesh = function (subMesh) {
  29394. var mesh = subMesh.getRenderingMesh();
  29395. if (_this._meshExcluded(mesh)) {
  29396. return;
  29397. }
  29398. var scene = mesh.getScene();
  29399. var engine = scene.getEngine();
  29400. // Culling
  29401. engine.setState(subMesh.getMaterial().backFaceCulling);
  29402. // Managing instances
  29403. var batch = mesh._getInstancesRenderList(subMesh._id);
  29404. if (batch.mustReturn) {
  29405. return;
  29406. }
  29407. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29408. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29409. engine.enableEffect(_this._volumetricLightScatteringPass);
  29410. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29411. var material = subMesh.getMaterial();
  29412. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29413. // Alpha test
  29414. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29415. var alphaTexture = material.getAlphaTestTexture();
  29416. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29417. if (alphaTexture) {
  29418. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29419. }
  29420. if (material.opacityTexture !== undefined) {
  29421. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29422. _this._volumetricLightScatteringPass.setFloat("opacityLevel", material.opacityTexture.level);
  29423. }
  29424. }
  29425. // Bones
  29426. if (mesh.useBones) {
  29427. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29428. }
  29429. // Draw
  29430. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29431. }
  29432. };
  29433. // Render target texture callbacks
  29434. var savedSceneClearColor;
  29435. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  29436. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29437. savedSceneClearColor = scene.clearColor;
  29438. scene.clearColor = sceneClearColor;
  29439. };
  29440. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29441. scene.clearColor = savedSceneClearColor;
  29442. };
  29443. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29444. var engine = scene.getEngine();
  29445. var index;
  29446. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29447. renderSubMesh(opaqueSubMeshes.data[index]);
  29448. }
  29449. engine.setAlphaTesting(true);
  29450. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29451. renderSubMesh(alphaTestSubMeshes.data[index]);
  29452. }
  29453. engine.setAlphaTesting(false);
  29454. if (transparentSubMeshes.length) {
  29455. for (index = 0; index < transparentSubMeshes.length; index++) {
  29456. var submesh = transparentSubMeshes.data[index];
  29457. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  29458. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  29459. }
  29460. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  29461. sortedArray.sort(function (a, b) {
  29462. // Alpha index first
  29463. if (a._alphaIndex > b._alphaIndex) {
  29464. return 1;
  29465. }
  29466. if (a._alphaIndex < b._alphaIndex) {
  29467. return -1;
  29468. }
  29469. // Then distance to camera
  29470. if (a._distanceToCamera < b._distanceToCamera) {
  29471. return 1;
  29472. }
  29473. if (a._distanceToCamera > b._distanceToCamera) {
  29474. return -1;
  29475. }
  29476. return 0;
  29477. });
  29478. // Render sub meshes
  29479. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29480. for (index = 0; index < sortedArray.length; index++) {
  29481. renderSubMesh(sortedArray[index]);
  29482. }
  29483. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29484. }
  29485. };
  29486. };
  29487. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29488. var transform = scene.getTransformMatrix();
  29489. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29490. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29491. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29492. if (this.invert)
  29493. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29494. };
  29495. // Static methods
  29496. /**
  29497. * Creates a default mesh for the Volumeric Light Scattering post-process
  29498. * @param {string} The mesh name
  29499. * @param {BABYLON.Scene} The scene where to create the mesh
  29500. * @return {BABYLON.Mesh} the default mesh
  29501. */
  29502. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29503. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29504. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29505. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29506. return mesh;
  29507. };
  29508. return VolumetricLightScatteringPostProcess;
  29509. })(BABYLON.PostProcess);
  29510. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29511. })(BABYLON || (BABYLON = {}));
  29512. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29513. var BABYLON;
  29514. (function (BABYLON) {
  29515. var LensRenderingPipeline = (function (_super) {
  29516. __extends(LensRenderingPipeline, _super);
  29517. /**
  29518. * @constructor
  29519. * @param {string} name - The rendering pipeline name
  29520. * @param {object} parameters - An object containing all parameters (see below)
  29521. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29522. * @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)
  29523. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29524. Effect parameters are as follow:
  29525. {
  29526. chromatic_aberration: number; // from 0 to x (1 for realism)
  29527. edge_blur: number; // from 0 to x (1 for realism)
  29528. distortion: number; // from 0 to x (1 for realism)
  29529. grain_amount: number; // from 0 to 1
  29530. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29531. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29532. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29533. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29534. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29535. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29536. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29537. }
  29538. Note: if an effect parameter is unset, effect is disabled
  29539. */
  29540. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29541. var _this = this;
  29542. if (ratio === void 0) { ratio = 1.0; }
  29543. _super.call(this, scene.getEngine(), name);
  29544. // Lens effects can be of the following:
  29545. // - chromatic aberration (slight shift of RGB colors)
  29546. // - blur on the edge of the lens
  29547. // - lens distortion
  29548. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29549. // - grain/dust-on-lens effect
  29550. // Two additional texture samplers are needed:
  29551. // - depth map (for depth-of-field)
  29552. // - grain texture
  29553. /**
  29554. * The chromatic aberration PostProcess id in the pipeline
  29555. * @type {string}
  29556. */
  29557. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29558. /**
  29559. * The depth-of-field PostProcess id in the pipeline
  29560. * @type {string}
  29561. */
  29562. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29563. this._scene = scene;
  29564. // Fetch texture samplers
  29565. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29566. if (parameters.grain_texture) {
  29567. this._grainTexture = parameters.grain_texture;
  29568. }
  29569. else {
  29570. this._createGrainTexture();
  29571. }
  29572. // save parameters
  29573. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29574. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29575. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29576. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29577. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29578. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29579. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29580. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29581. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29582. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29583. // Create effects
  29584. this._createChromaticAberrationPostProcess(ratio);
  29585. this._createDepthOfFieldPostProcess(ratio);
  29586. // Set up pipeline
  29587. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29588. return _this._chromaticAberrationPostProcess;
  29589. }, true));
  29590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29591. return _this._depthOfFieldPostProcess;
  29592. }, true));
  29593. // Finish
  29594. scene.postProcessRenderPipelineManager.addPipeline(this);
  29595. if (cameras) {
  29596. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29597. }
  29598. }
  29599. // public methods
  29600. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29601. this._edgeBlur = amount;
  29602. };
  29603. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29604. this._edgeBlur = 0;
  29605. };
  29606. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29607. this._grainAmount = amount;
  29608. };
  29609. LensRenderingPipeline.prototype.disableGrain = function () {
  29610. this._grainAmount = 0;
  29611. };
  29612. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29613. this._chromaticAberration = amount;
  29614. };
  29615. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29616. this._chromaticAberration = 0;
  29617. };
  29618. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29619. this._distortion = amount;
  29620. };
  29621. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29622. this._distortion = 0;
  29623. };
  29624. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29625. this._highlightsGain = amount;
  29626. };
  29627. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29628. this._highlightsThreshold = amount;
  29629. };
  29630. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29631. this._dofDepth = amount;
  29632. };
  29633. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29634. this._dofDepth = -1;
  29635. };
  29636. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29637. this._dofAperture = amount;
  29638. };
  29639. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29640. this._dofPentagon = true;
  29641. };
  29642. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29643. this._dofPentagon = false;
  29644. };
  29645. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29646. this._blurNoise = true;
  29647. };
  29648. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29649. this._blurNoise = false;
  29650. };
  29651. /**
  29652. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29653. */
  29654. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29655. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29656. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29657. this._chromaticAberrationPostProcess = undefined;
  29658. this._depthOfFieldPostProcess = undefined;
  29659. this._grainTexture.dispose();
  29660. if (disableDepthRender)
  29661. this._scene.disableDepthRenderer();
  29662. };
  29663. // colors shifting and distortion
  29664. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29665. var _this = this;
  29666. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29667. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29668. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29669. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29670. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29671. };
  29672. };
  29673. // colors shifting and distortion
  29674. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29675. var _this = this;
  29676. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29677. "gain",
  29678. "threshold",
  29679. "focus_depth",
  29680. "aperture",
  29681. "pentagon",
  29682. "maxZ",
  29683. "edge_blur",
  29684. "chromatic_aberration",
  29685. "distortion",
  29686. "blur_noise",
  29687. "grain_amount",
  29688. "screen_width",
  29689. "screen_height"
  29690. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29691. this._depthOfFieldPostProcess.onApply = function (effect) {
  29692. effect.setBool('pentagon', _this._dofPentagon);
  29693. effect.setBool('blur_noise', _this._blurNoise);
  29694. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29695. effect.setFloat('grain_amount', _this._grainAmount);
  29696. effect.setTexture("depthSampler", _this._depthTexture);
  29697. effect.setTexture("grainSampler", _this._grainTexture);
  29698. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29699. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29700. effect.setFloat('distortion', _this._distortion);
  29701. effect.setFloat('focus_depth', _this._dofDepth);
  29702. effect.setFloat('aperture', _this._dofAperture);
  29703. effect.setFloat('gain', _this._highlightsGain);
  29704. effect.setFloat('threshold', _this._highlightsThreshold);
  29705. effect.setFloat('edge_blur', _this._edgeBlur);
  29706. };
  29707. };
  29708. // creates a black and white random noise texture, 512x512
  29709. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29710. var size = 512;
  29711. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29712. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29713. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29714. var context = this._grainTexture.getContext();
  29715. var rand = function (min, max) {
  29716. return Math.random() * (max - min) + min;
  29717. };
  29718. var value;
  29719. for (var x = 0; x < size; x++) {
  29720. for (var y = 0; y < size; y++) {
  29721. value = Math.floor(rand(0.42, 0.58) * 255);
  29722. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29723. context.fillRect(x, y, 1, 1);
  29724. }
  29725. }
  29726. this._grainTexture.update(false);
  29727. };
  29728. return LensRenderingPipeline;
  29729. })(BABYLON.PostProcessRenderPipeline);
  29730. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29731. })(BABYLON || (BABYLON = {}));
  29732. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29733. // This post-process allows the modification of rendered colors by using
  29734. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29735. //
  29736. // The object needs to be provided an url to a texture containing the color
  29737. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29738. // Use an image editing software to tweak the LUT to match your needs.
  29739. //
  29740. // For an example of a color LUT, see here:
  29741. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29742. // For explanations on color grading, see here:
  29743. // http://udn.epicgames.com/Three/ColorGrading.html
  29744. //
  29745. var BABYLON;
  29746. (function (BABYLON) {
  29747. var ColorCorrectionPostProcess = (function (_super) {
  29748. __extends(ColorCorrectionPostProcess, _super);
  29749. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29750. var _this = this;
  29751. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29752. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29753. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29754. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29755. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29756. this.onApply = function (effect) {
  29757. effect.setTexture("colorTable", _this._colorTableTexture);
  29758. };
  29759. }
  29760. return ColorCorrectionPostProcess;
  29761. })(BABYLON.PostProcess);
  29762. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29763. })(BABYLON || (BABYLON = {}));
  29764. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.mapvar BABYLON;
  29765. (function (BABYLON) {
  29766. var SmartCollection = (function () {
  29767. function SmartCollection(capacity) {
  29768. if (capacity === void 0) { capacity = 10; }
  29769. this.count = 0;
  29770. this._initialCapacity = capacity;
  29771. this.items = {};
  29772. this._keys = new Array(this._initialCapacity);
  29773. }
  29774. SmartCollection.prototype.add = function (key, item) {
  29775. if (this.items[key] != undefined) {
  29776. return -1;
  29777. }
  29778. this.items[key] = item;
  29779. //literal keys are always strings, but we keep source type of key in _keys array
  29780. this._keys[this.count++] = key;
  29781. if (this.count > this._keys.length) {
  29782. this._keys.length *= 2;
  29783. }
  29784. return this.count;
  29785. };
  29786. SmartCollection.prototype.remove = function (key) {
  29787. if (this.items[key] == undefined) {
  29788. return -1;
  29789. }
  29790. return this.removeItemOfIndex(this.indexOf(key));
  29791. };
  29792. SmartCollection.prototype.removeItemOfIndex = function (index) {
  29793. if (index < this.count && index > -1) {
  29794. delete this.items[this._keys[index]];
  29795. while (index < this.count) {
  29796. this._keys[index] = this._keys[index + 1];
  29797. index++;
  29798. }
  29799. }
  29800. else {
  29801. return -1;
  29802. }
  29803. return --this.count;
  29804. };
  29805. SmartCollection.prototype.indexOf = function (key) {
  29806. for (var i = 0; i !== this.count; i++) {
  29807. if (this._keys[i] === key) {
  29808. return i;
  29809. }
  29810. }
  29811. return -1;
  29812. };
  29813. SmartCollection.prototype.item = function (key) {
  29814. return this.items[key];
  29815. };
  29816. SmartCollection.prototype.getAllKeys = function () {
  29817. if (this.count > 0) {
  29818. var keys = new Array(this.count);
  29819. for (var i = 0; i < this.count; i++) {
  29820. keys[i] = this._keys[i];
  29821. }
  29822. return keys;
  29823. }
  29824. else {
  29825. return undefined;
  29826. }
  29827. };
  29828. SmartCollection.prototype.getKeyByIndex = function (index) {
  29829. if (index < this.count && index > -1) {
  29830. return this._keys[index];
  29831. }
  29832. else {
  29833. return undefined;
  29834. }
  29835. };
  29836. SmartCollection.prototype.getItemByIndex = function (index) {
  29837. if (index < this.count && index > -1) {
  29838. return this.items[this._keys[index]];
  29839. }
  29840. else {
  29841. return undefined;
  29842. }
  29843. };
  29844. SmartCollection.prototype.empty = function () {
  29845. if (this.count > 0) {
  29846. this.count = 0;
  29847. this.items = {};
  29848. this._keys = new Array(this._initialCapacity);
  29849. }
  29850. };
  29851. return SmartCollection;
  29852. })();
  29853. BABYLON.SmartCollection = SmartCollection;
  29854. })(BABYLON || (BABYLON = {}));
  29855. //# sourceMappingURL=babylon.smartCollection.js.map