babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = new Array();
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = new Array();
  2418. this._distances = new Array();
  2419. this._tangents = new Array();
  2420. this._normals = new Array();
  2421. this._binormals = new Array();
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. var Curve3 = (function () {
  2499. function Curve3(points) {
  2500. this._points = points;
  2501. }
  2502. // QuadraticBezier(origin_V3, control_V3, destination_V3 )
  2503. Curve3.QuadraticBezier = function (v0, v1, v2, nbPoints) {
  2504. nbPoints = nbPoints > 2 ? nbPoints : 3;
  2505. var bez = new Array();
  2506. var step = 1 / nbPoints;
  2507. var equation = function (t, val0, val1, val2) {
  2508. var res = (1 - t) * (1 - t) * val0 + 2 * t * (1 - t) * val1 + t * t * val2;
  2509. return res;
  2510. };
  2511. for (var i = 0; i <= 1; i += step) {
  2512. 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)));
  2513. }
  2514. return new Curve3(bez);
  2515. };
  2516. // CubicBezier(origin_V3, control1_V3, control2_V3, destination_V3)
  2517. Curve3.CubicBezier = function (v0, v1, v2, v3, nbPoints) {
  2518. nbPoints = nbPoints > 3 ? nbPoints : 4;
  2519. var bez = new Array();
  2520. var step = 1 / nbPoints;
  2521. var equation = function (t, val0, val1, val2, val3) {
  2522. 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;
  2523. return res;
  2524. };
  2525. for (var i = 0; i <= 1; i += step) {
  2526. 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)));
  2527. }
  2528. return new Curve3(bez);
  2529. };
  2530. Curve3.prototype.getPoints = function () {
  2531. return this._points;
  2532. };
  2533. return Curve3;
  2534. })();
  2535. BABYLON.Curve3 = Curve3;
  2536. })(BABYLON || (BABYLON = {}));
  2537. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2538. (function (BABYLON) {
  2539. // Screenshots
  2540. var screenshotCanvas;
  2541. var cloneValue = function (source, destinationObject) {
  2542. if (!source)
  2543. return null;
  2544. if (source instanceof BABYLON.Mesh) {
  2545. return null;
  2546. }
  2547. if (source instanceof BABYLON.SubMesh) {
  2548. return source.clone(destinationObject);
  2549. }
  2550. else if (source.clone) {
  2551. return source.clone();
  2552. }
  2553. return null;
  2554. };
  2555. var Tools = (function () {
  2556. function Tools() {
  2557. }
  2558. Tools.GetFilename = function (path) {
  2559. var index = path.lastIndexOf("/");
  2560. if (index < 0)
  2561. return path;
  2562. return path.substring(index + 1);
  2563. };
  2564. Tools.GetDOMTextContent = function (element) {
  2565. var result = "";
  2566. var child = element.firstChild;
  2567. while (child) {
  2568. if (child.nodeType === 3) {
  2569. result += child.textContent;
  2570. }
  2571. child = child.nextSibling;
  2572. }
  2573. return result;
  2574. };
  2575. Tools.ToDegrees = function (angle) {
  2576. return angle * 180 / Math.PI;
  2577. };
  2578. Tools.ToRadians = function (angle) {
  2579. return angle * Math.PI / 180;
  2580. };
  2581. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2582. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2583. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2584. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2585. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2586. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2587. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2588. }
  2589. return {
  2590. minimum: minimum,
  2591. maximum: maximum
  2592. };
  2593. };
  2594. Tools.ExtractMinAndMax = function (positions, start, count) {
  2595. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2596. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2597. for (var index = start; index < start + count; index++) {
  2598. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2599. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2600. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2601. }
  2602. return {
  2603. minimum: minimum,
  2604. maximum: maximum
  2605. };
  2606. };
  2607. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2608. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2609. return undefined;
  2610. return Array.isArray(obj) ? obj : [obj];
  2611. };
  2612. // Misc.
  2613. Tools.GetPointerPrefix = function () {
  2614. var eventPrefix = "pointer";
  2615. // Check if hand.js is referenced or if the browser natively supports pointer events
  2616. if (!navigator.pointerEnabled) {
  2617. eventPrefix = "mouse";
  2618. }
  2619. return eventPrefix;
  2620. };
  2621. Tools.QueueNewFrame = function (func) {
  2622. if (window.requestAnimationFrame)
  2623. window.requestAnimationFrame(func);
  2624. else if (window.msRequestAnimationFrame)
  2625. window.msRequestAnimationFrame(func);
  2626. else if (window.webkitRequestAnimationFrame)
  2627. window.webkitRequestAnimationFrame(func);
  2628. else if (window.mozRequestAnimationFrame)
  2629. window.mozRequestAnimationFrame(func);
  2630. else if (window.oRequestAnimationFrame)
  2631. window.oRequestAnimationFrame(func);
  2632. else {
  2633. window.setTimeout(func, 16);
  2634. }
  2635. };
  2636. Tools.RequestFullscreen = function (element) {
  2637. if (element.requestFullscreen)
  2638. element.requestFullscreen();
  2639. else if (element.msRequestFullscreen)
  2640. element.msRequestFullscreen();
  2641. else if (element.webkitRequestFullscreen)
  2642. element.webkitRequestFullscreen();
  2643. else if (element.mozRequestFullScreen)
  2644. element.mozRequestFullScreen();
  2645. };
  2646. Tools.ExitFullscreen = function () {
  2647. if (document.exitFullscreen) {
  2648. document.exitFullscreen();
  2649. }
  2650. else if (document.mozCancelFullScreen) {
  2651. document.mozCancelFullScreen();
  2652. }
  2653. else if (document.webkitCancelFullScreen) {
  2654. document.webkitCancelFullScreen();
  2655. }
  2656. else if (document.msCancelFullScreen) {
  2657. document.msCancelFullScreen();
  2658. }
  2659. };
  2660. // External files
  2661. Tools.CleanUrl = function (url) {
  2662. url = url.replace(/#/mg, "%23");
  2663. return url;
  2664. };
  2665. Tools.LoadImage = function (url, onload, onerror, database) {
  2666. url = Tools.CleanUrl(url);
  2667. var img = new Image();
  2668. if (url.substr(0, 5) !== "data:")
  2669. img.crossOrigin = 'anonymous';
  2670. img.onload = function () {
  2671. onload(img);
  2672. };
  2673. img.onerror = function (err) {
  2674. onerror(img, err);
  2675. };
  2676. var noIndexedDB = function () {
  2677. img.src = url;
  2678. };
  2679. var loadFromIndexedDB = function () {
  2680. database.loadImageFromDB(url, img);
  2681. };
  2682. //ANY database to do!
  2683. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2684. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2685. }
  2686. else {
  2687. if (url.indexOf("file:") === -1) {
  2688. noIndexedDB();
  2689. }
  2690. else {
  2691. try {
  2692. var textureName = url.substring(5);
  2693. var blobURL;
  2694. try {
  2695. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2696. }
  2697. catch (ex) {
  2698. // Chrome doesn't support oneTimeOnly parameter
  2699. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2700. }
  2701. img.src = blobURL;
  2702. }
  2703. catch (e) {
  2704. Tools.Log("Error while trying to load texture: " + textureName);
  2705. img.src = null;
  2706. }
  2707. }
  2708. }
  2709. return img;
  2710. };
  2711. //ANY
  2712. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2713. url = Tools.CleanUrl(url);
  2714. var noIndexedDB = function () {
  2715. var request = new XMLHttpRequest();
  2716. var loadUrl = Tools.BaseUrl + url;
  2717. request.open('GET', loadUrl, true);
  2718. if (useArrayBuffer) {
  2719. request.responseType = "arraybuffer";
  2720. }
  2721. request.onprogress = progressCallBack;
  2722. request.onreadystatechange = function () {
  2723. if (request.readyState === 4) {
  2724. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2725. callback(!useArrayBuffer ? request.responseText : request.response);
  2726. }
  2727. else {
  2728. if (onError) {
  2729. onError();
  2730. }
  2731. else {
  2732. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2733. }
  2734. }
  2735. }
  2736. };
  2737. request.send(null);
  2738. };
  2739. var loadFromIndexedDB = function () {
  2740. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2741. };
  2742. if (url.indexOf("file:") !== -1) {
  2743. var fileName = url.substring(5);
  2744. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2745. }
  2746. else {
  2747. // Caching all files
  2748. if (database && database.enableSceneOffline) {
  2749. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2750. }
  2751. else {
  2752. noIndexedDB();
  2753. }
  2754. }
  2755. };
  2756. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2757. var reader = new FileReader();
  2758. reader.onload = function (e) {
  2759. //target doesn't have result from ts 1.3
  2760. callback(e.target['result']);
  2761. };
  2762. reader.onprogress = progressCallback;
  2763. reader.readAsDataURL(fileToLoad);
  2764. };
  2765. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2766. var reader = new FileReader();
  2767. reader.onerror = function (e) {
  2768. Tools.Log("Error while reading file: " + fileToLoad.name);
  2769. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2770. };
  2771. reader.onload = function (e) {
  2772. //target doesn't have result from ts 1.3
  2773. callback(e.target['result']);
  2774. };
  2775. reader.onprogress = progressCallBack;
  2776. if (!useArrayBuffer) {
  2777. // Asynchronous read
  2778. reader.readAsText(fileToLoad);
  2779. }
  2780. else {
  2781. reader.readAsArrayBuffer(fileToLoad);
  2782. }
  2783. };
  2784. // Misc.
  2785. Tools.Clamp = function (value, min, max) {
  2786. if (min === void 0) { min = 0; }
  2787. if (max === void 0) { max = 1; }
  2788. return Math.min(max, Math.max(min, value));
  2789. };
  2790. // Returns -1 when value is a negative number and
  2791. // +1 when value is a positive number.
  2792. Tools.Sign = function (value) {
  2793. value = +value; // convert to a number
  2794. if (value === 0 || isNaN(value))
  2795. return value;
  2796. return value > 0 ? 1 : -1;
  2797. };
  2798. Tools.Format = function (value, decimals) {
  2799. if (decimals === void 0) { decimals = 2; }
  2800. return value.toFixed(decimals);
  2801. };
  2802. Tools.CheckExtends = function (v, min, max) {
  2803. if (v.x < min.x)
  2804. min.x = v.x;
  2805. if (v.y < min.y)
  2806. min.y = v.y;
  2807. if (v.z < min.z)
  2808. min.z = v.z;
  2809. if (v.x > max.x)
  2810. max.x = v.x;
  2811. if (v.y > max.y)
  2812. max.y = v.y;
  2813. if (v.z > max.z)
  2814. max.z = v.z;
  2815. };
  2816. Tools.WithinEpsilon = function (a, b, epsilon) {
  2817. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2818. var num = a - b;
  2819. return -epsilon <= num && num <= epsilon;
  2820. };
  2821. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2822. for (var prop in source) {
  2823. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2824. continue;
  2825. }
  2826. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2827. continue;
  2828. }
  2829. var sourceValue = source[prop];
  2830. var typeOfSourceValue = typeof sourceValue;
  2831. if (typeOfSourceValue === "function") {
  2832. continue;
  2833. }
  2834. if (typeOfSourceValue === "object") {
  2835. if (sourceValue instanceof Array) {
  2836. destination[prop] = [];
  2837. if (sourceValue.length > 0) {
  2838. if (typeof sourceValue[0] == "object") {
  2839. for (var index = 0; index < sourceValue.length; index++) {
  2840. var clonedValue = cloneValue(sourceValue[index], destination);
  2841. if (destination[prop].indexOf(clonedValue) === -1) {
  2842. destination[prop].push(clonedValue);
  2843. }
  2844. }
  2845. }
  2846. else {
  2847. destination[prop] = sourceValue.slice(0);
  2848. }
  2849. }
  2850. }
  2851. else {
  2852. destination[prop] = cloneValue(sourceValue, destination);
  2853. }
  2854. }
  2855. else {
  2856. destination[prop] = sourceValue;
  2857. }
  2858. }
  2859. };
  2860. Tools.IsEmpty = function (obj) {
  2861. for (var i in obj) {
  2862. return false;
  2863. }
  2864. return true;
  2865. };
  2866. Tools.RegisterTopRootEvents = function (events) {
  2867. for (var index = 0; index < events.length; index++) {
  2868. var event = events[index];
  2869. window.addEventListener(event.name, event.handler, false);
  2870. try {
  2871. if (window.parent) {
  2872. window.parent.addEventListener(event.name, event.handler, false);
  2873. }
  2874. }
  2875. catch (e) {
  2876. }
  2877. }
  2878. };
  2879. Tools.UnregisterTopRootEvents = function (events) {
  2880. for (var index = 0; index < events.length; index++) {
  2881. var event = events[index];
  2882. window.removeEventListener(event.name, event.handler);
  2883. try {
  2884. if (window.parent) {
  2885. window.parent.removeEventListener(event.name, event.handler);
  2886. }
  2887. }
  2888. catch (e) {
  2889. }
  2890. }
  2891. };
  2892. Tools.DumpFramebuffer = function (width, height, engine) {
  2893. // Read the contents of the framebuffer
  2894. var numberOfChannelsByLine = width * 4;
  2895. var halfHeight = height / 2;
  2896. //Reading datas from WebGL
  2897. var data = engine.readPixels(0, 0, width, height);
  2898. for (var i = 0; i < halfHeight; i++) {
  2899. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2900. var currentCell = j + i * numberOfChannelsByLine;
  2901. var targetLine = height - i - 1;
  2902. var targetCell = j + targetLine * numberOfChannelsByLine;
  2903. var temp = data[currentCell];
  2904. data[currentCell] = data[targetCell];
  2905. data[targetCell] = temp;
  2906. }
  2907. }
  2908. // Create a 2D canvas to store the result
  2909. if (!screenshotCanvas) {
  2910. screenshotCanvas = document.createElement('canvas');
  2911. }
  2912. screenshotCanvas.width = width;
  2913. screenshotCanvas.height = height;
  2914. var context = screenshotCanvas.getContext('2d');
  2915. // Copy the pixels to a 2D canvas
  2916. var imageData = context.createImageData(width, height);
  2917. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2918. var castData = imageData.data;
  2919. castData.set(data);
  2920. context.putImageData(imageData, 0, 0);
  2921. var base64Image = screenshotCanvas.toDataURL();
  2922. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2923. if (("download" in document.createElement("a"))) {
  2924. var a = window.document.createElement("a");
  2925. a.href = base64Image;
  2926. var date = new Date();
  2927. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2928. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2929. window.document.body.appendChild(a);
  2930. a.addEventListener("click", function () {
  2931. a.parentElement.removeChild(a);
  2932. });
  2933. a.click();
  2934. }
  2935. else {
  2936. var newWindow = window.open("");
  2937. var img = newWindow.document.createElement("img");
  2938. img.src = base64Image;
  2939. newWindow.document.body.appendChild(img);
  2940. }
  2941. };
  2942. Tools.CreateScreenshot = function (engine, camera, size) {
  2943. var width;
  2944. var height;
  2945. var scene = camera.getScene();
  2946. var previousCamera = null;
  2947. if (scene.activeCamera !== camera) {
  2948. previousCamera = scene.activeCamera;
  2949. scene.activeCamera = camera;
  2950. }
  2951. //If a precision value is specified
  2952. if (size.precision) {
  2953. width = Math.round(engine.getRenderWidth() * size.precision);
  2954. height = Math.round(width / engine.getAspectRatio(camera));
  2955. size = { width: width, height: height };
  2956. }
  2957. else if (size.width && size.height) {
  2958. width = size.width;
  2959. height = size.height;
  2960. }
  2961. else if (size.width && !size.height) {
  2962. width = size.width;
  2963. height = Math.round(width / engine.getAspectRatio(camera));
  2964. size = { width: width, height: height };
  2965. }
  2966. else if (size.height && !size.width) {
  2967. height = size.height;
  2968. width = Math.round(height * engine.getAspectRatio(camera));
  2969. size = { width: width, height: height };
  2970. }
  2971. else if (!isNaN(size)) {
  2972. height = size;
  2973. width = size;
  2974. }
  2975. else {
  2976. Tools.Error("Invalid 'size' parameter !");
  2977. return;
  2978. }
  2979. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2980. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2981. texture.renderList = scene.meshes;
  2982. texture.onAfterRender = function () {
  2983. Tools.DumpFramebuffer(width, height, engine);
  2984. };
  2985. scene.incrementRenderId();
  2986. texture.render(true);
  2987. texture.dispose();
  2988. if (previousCamera) {
  2989. scene.activeCamera = previousCamera;
  2990. }
  2991. };
  2992. // XHR response validator for local file scenario
  2993. Tools.ValidateXHRData = function (xhr, dataType) {
  2994. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2995. if (dataType === void 0) { dataType = 7; }
  2996. try {
  2997. if (dataType & 1) {
  2998. if (xhr.responseText && xhr.responseText.length > 0) {
  2999. return true;
  3000. }
  3001. else if (dataType === 1) {
  3002. return false;
  3003. }
  3004. }
  3005. if (dataType & 2) {
  3006. // Check header width and height since there is no "TGA" magic number
  3007. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  3008. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  3009. return true;
  3010. }
  3011. else if (dataType === 2) {
  3012. return false;
  3013. }
  3014. }
  3015. if (dataType & 4) {
  3016. // Check for the "DDS" magic number
  3017. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  3018. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  3019. return true;
  3020. }
  3021. else {
  3022. return false;
  3023. }
  3024. }
  3025. }
  3026. catch (e) {
  3027. }
  3028. return false;
  3029. };
  3030. Object.defineProperty(Tools, "NoneLogLevel", {
  3031. get: function () {
  3032. return Tools._NoneLogLevel;
  3033. },
  3034. enumerable: true,
  3035. configurable: true
  3036. });
  3037. Object.defineProperty(Tools, "MessageLogLevel", {
  3038. get: function () {
  3039. return Tools._MessageLogLevel;
  3040. },
  3041. enumerable: true,
  3042. configurable: true
  3043. });
  3044. Object.defineProperty(Tools, "WarningLogLevel", {
  3045. get: function () {
  3046. return Tools._WarningLogLevel;
  3047. },
  3048. enumerable: true,
  3049. configurable: true
  3050. });
  3051. Object.defineProperty(Tools, "ErrorLogLevel", {
  3052. get: function () {
  3053. return Tools._ErrorLogLevel;
  3054. },
  3055. enumerable: true,
  3056. configurable: true
  3057. });
  3058. Object.defineProperty(Tools, "AllLogLevel", {
  3059. get: function () {
  3060. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3061. },
  3062. enumerable: true,
  3063. configurable: true
  3064. });
  3065. Tools._AddLogEntry = function (entry) {
  3066. Tools._LogCache = entry + Tools._LogCache;
  3067. if (Tools.OnNewCacheEntry) {
  3068. Tools.OnNewCacheEntry(entry);
  3069. }
  3070. };
  3071. Tools._FormatMessage = function (message) {
  3072. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3073. var date = new Date();
  3074. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3075. };
  3076. Tools._LogDisabled = function (message) {
  3077. // nothing to do
  3078. };
  3079. Tools._LogEnabled = function (message) {
  3080. var formattedMessage = Tools._FormatMessage(message);
  3081. console.log("BJS - " + formattedMessage);
  3082. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3083. Tools._AddLogEntry(entry);
  3084. };
  3085. Tools._WarnDisabled = function (message) {
  3086. // nothing to do
  3087. };
  3088. Tools._WarnEnabled = function (message) {
  3089. var formattedMessage = Tools._FormatMessage(message);
  3090. console.warn("BJS - " + formattedMessage);
  3091. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3092. Tools._AddLogEntry(entry);
  3093. };
  3094. Tools._ErrorDisabled = function (message) {
  3095. // nothing to do
  3096. };
  3097. Tools._ErrorEnabled = function (message) {
  3098. var formattedMessage = Tools._FormatMessage(message);
  3099. console.error("BJS - " + formattedMessage);
  3100. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3101. Tools._AddLogEntry(entry);
  3102. };
  3103. Object.defineProperty(Tools, "LogCache", {
  3104. get: function () {
  3105. return Tools._LogCache;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "LogLevels", {
  3111. set: function (level) {
  3112. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3113. Tools.Log = Tools._LogEnabled;
  3114. }
  3115. else {
  3116. Tools.Log = Tools._LogDisabled;
  3117. }
  3118. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3119. Tools.Warn = Tools._WarnEnabled;
  3120. }
  3121. else {
  3122. Tools.Warn = Tools._WarnDisabled;
  3123. }
  3124. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3125. Tools.Error = Tools._ErrorEnabled;
  3126. }
  3127. else {
  3128. Tools.Error = Tools._ErrorDisabled;
  3129. }
  3130. },
  3131. enumerable: true,
  3132. configurable: true
  3133. });
  3134. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3135. get: function () {
  3136. return Tools._PerformanceNoneLogLevel;
  3137. },
  3138. enumerable: true,
  3139. configurable: true
  3140. });
  3141. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3142. get: function () {
  3143. return Tools._PerformanceUserMarkLogLevel;
  3144. },
  3145. enumerable: true,
  3146. configurable: true
  3147. });
  3148. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3149. get: function () {
  3150. return Tools._PerformanceConsoleLogLevel;
  3151. },
  3152. enumerable: true,
  3153. configurable: true
  3154. });
  3155. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3156. set: function (level) {
  3157. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3158. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3159. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3160. return;
  3161. }
  3162. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3163. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3164. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3165. return;
  3166. }
  3167. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3168. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3169. },
  3170. enumerable: true,
  3171. configurable: true
  3172. });
  3173. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3174. };
  3175. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3176. };
  3177. Tools._StartUserMark = function (counterName, condition) {
  3178. if (condition === void 0) { condition = true; }
  3179. if (!condition || !Tools._performance.mark) {
  3180. return;
  3181. }
  3182. Tools._performance.mark(counterName + "-Begin");
  3183. };
  3184. Tools._EndUserMark = function (counterName, condition) {
  3185. if (condition === void 0) { condition = true; }
  3186. if (!condition || !Tools._performance.mark) {
  3187. return;
  3188. }
  3189. Tools._performance.mark(counterName + "-End");
  3190. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3191. };
  3192. Tools._StartPerformanceConsole = function (counterName, condition) {
  3193. if (condition === void 0) { condition = true; }
  3194. if (!condition) {
  3195. return;
  3196. }
  3197. Tools._StartUserMark(counterName, condition);
  3198. if (console.time) {
  3199. console.time(counterName);
  3200. }
  3201. };
  3202. Tools._EndPerformanceConsole = function (counterName, condition) {
  3203. if (condition === void 0) { condition = true; }
  3204. if (!condition) {
  3205. return;
  3206. }
  3207. Tools._EndUserMark(counterName, condition);
  3208. if (console.time) {
  3209. console.timeEnd(counterName);
  3210. }
  3211. };
  3212. Object.defineProperty(Tools, "Now", {
  3213. get: function () {
  3214. if (window.performance && window.performance.now) {
  3215. return window.performance.now();
  3216. }
  3217. return new Date().getTime();
  3218. },
  3219. enumerable: true,
  3220. configurable: true
  3221. });
  3222. // Deprecated
  3223. Tools.GetFps = function () {
  3224. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3225. return 0;
  3226. };
  3227. Tools.BaseUrl = "";
  3228. Tools.GetExponantOfTwo = function (value, max) {
  3229. var count = 1;
  3230. do {
  3231. count *= 2;
  3232. } while (count < value);
  3233. if (count > max)
  3234. count = max;
  3235. return count;
  3236. };
  3237. // Logs
  3238. Tools._NoneLogLevel = 0;
  3239. Tools._MessageLogLevel = 1;
  3240. Tools._WarningLogLevel = 2;
  3241. Tools._ErrorLogLevel = 4;
  3242. Tools._LogCache = "";
  3243. Tools.Log = Tools._LogEnabled;
  3244. Tools.Warn = Tools._WarnEnabled;
  3245. Tools.Error = Tools._ErrorEnabled;
  3246. // Performances
  3247. Tools._PerformanceNoneLogLevel = 0;
  3248. Tools._PerformanceUserMarkLogLevel = 1;
  3249. Tools._PerformanceConsoleLogLevel = 2;
  3250. Tools._performance = window.performance;
  3251. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3252. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3253. return Tools;
  3254. })();
  3255. BABYLON.Tools = Tools;
  3256. /**
  3257. * An implementation of a loop for asynchronous functions.
  3258. */
  3259. var AsyncLoop = (function () {
  3260. /**
  3261. * Constroctor.
  3262. * @param iterations the number of iterations.
  3263. * @param _fn the function to run each iteration
  3264. * @param _successCallback the callback that will be called upon succesful execution
  3265. * @param offset starting offset.
  3266. */
  3267. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3268. if (offset === void 0) { offset = 0; }
  3269. this.iterations = iterations;
  3270. this._fn = _fn;
  3271. this._successCallback = _successCallback;
  3272. this.index = offset - 1;
  3273. this._done = false;
  3274. }
  3275. /**
  3276. * Execute the next iteration. Must be called after the last iteration was finished.
  3277. */
  3278. AsyncLoop.prototype.executeNext = function () {
  3279. if (!this._done) {
  3280. if (this.index + 1 < this.iterations) {
  3281. ++this.index;
  3282. this._fn(this);
  3283. }
  3284. else {
  3285. this.breakLoop();
  3286. }
  3287. }
  3288. };
  3289. /**
  3290. * Break the loop and run the success callback.
  3291. */
  3292. AsyncLoop.prototype.breakLoop = function () {
  3293. this._done = true;
  3294. this._successCallback();
  3295. };
  3296. /**
  3297. * Helper function
  3298. */
  3299. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3300. if (offset === void 0) { offset = 0; }
  3301. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3302. loop.executeNext();
  3303. return loop;
  3304. };
  3305. /**
  3306. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3307. * @param iterations total number of iterations
  3308. * @param syncedIterations number of synchronous iterations in each async iteration.
  3309. * @param fn the function to call each iteration.
  3310. * @param callback a success call back that will be called when iterating stops.
  3311. * @param breakFunction a break condition (optional)
  3312. * @param timeout timeout settings for the setTimeout function. default - 0.
  3313. * @constructor
  3314. */
  3315. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3316. if (timeout === void 0) { timeout = 0; }
  3317. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3318. if (breakFunction && breakFunction())
  3319. loop.breakLoop();
  3320. else {
  3321. setTimeout(function () {
  3322. for (var i = 0; i < syncedIterations; ++i) {
  3323. var iteration = (loop.index * syncedIterations) + i;
  3324. if (iteration >= iterations)
  3325. break;
  3326. fn(iteration);
  3327. if (breakFunction && breakFunction()) {
  3328. loop.breakLoop();
  3329. break;
  3330. }
  3331. }
  3332. loop.executeNext();
  3333. }, timeout);
  3334. }
  3335. }, callback);
  3336. };
  3337. return AsyncLoop;
  3338. })();
  3339. BABYLON.AsyncLoop = AsyncLoop;
  3340. })(BABYLON || (BABYLON = {}));
  3341. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3342. (function (BABYLON) {
  3343. var _DepthCullingState = (function () {
  3344. function _DepthCullingState() {
  3345. this._isDepthTestDirty = false;
  3346. this._isDepthMaskDirty = false;
  3347. this._isDepthFuncDirty = false;
  3348. this._isCullFaceDirty = false;
  3349. this._isCullDirty = false;
  3350. }
  3351. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3352. get: function () {
  3353. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3354. },
  3355. enumerable: true,
  3356. configurable: true
  3357. });
  3358. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3359. get: function () {
  3360. return this._cullFace;
  3361. },
  3362. set: function (value) {
  3363. if (this._cullFace === value) {
  3364. return;
  3365. }
  3366. this._cullFace = value;
  3367. this._isCullFaceDirty = true;
  3368. },
  3369. enumerable: true,
  3370. configurable: true
  3371. });
  3372. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3373. get: function () {
  3374. return this._cull;
  3375. },
  3376. set: function (value) {
  3377. if (this._cull === value) {
  3378. return;
  3379. }
  3380. this._cull = value;
  3381. this._isCullDirty = true;
  3382. },
  3383. enumerable: true,
  3384. configurable: true
  3385. });
  3386. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3387. get: function () {
  3388. return this._depthFunc;
  3389. },
  3390. set: function (value) {
  3391. if (this._depthFunc === value) {
  3392. return;
  3393. }
  3394. this._depthFunc = value;
  3395. this._isDepthFuncDirty = true;
  3396. },
  3397. enumerable: true,
  3398. configurable: true
  3399. });
  3400. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3401. get: function () {
  3402. return this._depthMask;
  3403. },
  3404. set: function (value) {
  3405. if (this._depthMask === value) {
  3406. return;
  3407. }
  3408. this._depthMask = value;
  3409. this._isDepthMaskDirty = true;
  3410. },
  3411. enumerable: true,
  3412. configurable: true
  3413. });
  3414. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3415. get: function () {
  3416. return this._depthTest;
  3417. },
  3418. set: function (value) {
  3419. if (this._depthTest === value) {
  3420. return;
  3421. }
  3422. this._depthTest = value;
  3423. this._isDepthTestDirty = true;
  3424. },
  3425. enumerable: true,
  3426. configurable: true
  3427. });
  3428. _DepthCullingState.prototype.reset = function () {
  3429. this._depthMask = true;
  3430. this._depthTest = true;
  3431. this._depthFunc = null;
  3432. this._cull = null;
  3433. this._cullFace = null;
  3434. this._isDepthTestDirty = true;
  3435. this._isDepthMaskDirty = true;
  3436. this._isDepthFuncDirty = false;
  3437. this._isCullFaceDirty = false;
  3438. this._isCullDirty = false;
  3439. };
  3440. _DepthCullingState.prototype.apply = function (gl) {
  3441. if (!this.isDirty) {
  3442. return;
  3443. }
  3444. // Cull
  3445. if (this._isCullDirty) {
  3446. if (this.cull) {
  3447. gl.enable(gl.CULL_FACE);
  3448. }
  3449. else {
  3450. gl.disable(gl.CULL_FACE);
  3451. }
  3452. this._isCullDirty = false;
  3453. }
  3454. // Cull face
  3455. if (this._isCullFaceDirty) {
  3456. gl.cullFace(this.cullFace);
  3457. this._isCullFaceDirty = false;
  3458. }
  3459. // Depth mask
  3460. if (this._isDepthMaskDirty) {
  3461. gl.depthMask(this.depthMask);
  3462. this._isDepthMaskDirty = false;
  3463. }
  3464. // Depth test
  3465. if (this._isDepthTestDirty) {
  3466. if (this.depthTest) {
  3467. gl.enable(gl.DEPTH_TEST);
  3468. }
  3469. else {
  3470. gl.disable(gl.DEPTH_TEST);
  3471. }
  3472. this._isDepthTestDirty = false;
  3473. }
  3474. // Depth func
  3475. if (this._isDepthFuncDirty) {
  3476. gl.depthFunc(this.depthFunc);
  3477. this._isDepthFuncDirty = false;
  3478. }
  3479. };
  3480. return _DepthCullingState;
  3481. })();
  3482. BABYLON._DepthCullingState = _DepthCullingState;
  3483. var _AlphaState = (function () {
  3484. function _AlphaState() {
  3485. this._isAlphaBlendDirty = false;
  3486. this._isBlendFunctionParametersDirty = false;
  3487. this._alphaBlend = false;
  3488. this._blendFunctionParameters = new Array(4);
  3489. }
  3490. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3491. get: function () {
  3492. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3493. },
  3494. enumerable: true,
  3495. configurable: true
  3496. });
  3497. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3498. get: function () {
  3499. return this._alphaBlend;
  3500. },
  3501. set: function (value) {
  3502. if (this._alphaBlend === value) {
  3503. return;
  3504. }
  3505. this._alphaBlend = value;
  3506. this._isAlphaBlendDirty = true;
  3507. },
  3508. enumerable: true,
  3509. configurable: true
  3510. });
  3511. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3512. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3513. return;
  3514. }
  3515. this._blendFunctionParameters[0] = value0;
  3516. this._blendFunctionParameters[1] = value1;
  3517. this._blendFunctionParameters[2] = value2;
  3518. this._blendFunctionParameters[3] = value3;
  3519. this._isBlendFunctionParametersDirty = true;
  3520. };
  3521. _AlphaState.prototype.reset = function () {
  3522. this._alphaBlend = false;
  3523. this._blendFunctionParameters[0] = null;
  3524. this._blendFunctionParameters[1] = null;
  3525. this._blendFunctionParameters[2] = null;
  3526. this._blendFunctionParameters[3] = null;
  3527. this._isAlphaBlendDirty = true;
  3528. this._isBlendFunctionParametersDirty = false;
  3529. };
  3530. _AlphaState.prototype.apply = function (gl) {
  3531. if (!this.isDirty) {
  3532. return;
  3533. }
  3534. // Alpha blend
  3535. if (this._isAlphaBlendDirty) {
  3536. if (this._alphaBlend) {
  3537. gl.enable(gl.BLEND);
  3538. }
  3539. else {
  3540. gl.disable(gl.BLEND);
  3541. }
  3542. this._isAlphaBlendDirty = false;
  3543. }
  3544. // Alpha function
  3545. if (this._isBlendFunctionParametersDirty) {
  3546. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3547. this._isBlendFunctionParametersDirty = false;
  3548. }
  3549. };
  3550. return _AlphaState;
  3551. })();
  3552. BABYLON._AlphaState = _AlphaState;
  3553. var compileShader = function (gl, source, type, defines) {
  3554. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3555. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3556. gl.compileShader(shader);
  3557. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3558. throw new Error(gl.getShaderInfoLog(shader));
  3559. }
  3560. return shader;
  3561. };
  3562. var getWebGLTextureType = function (gl, type) {
  3563. var textureType = gl.UNSIGNED_BYTE;
  3564. if (type === Engine.TEXTURETYPE_FLOAT)
  3565. textureType = gl.FLOAT;
  3566. return textureType;
  3567. };
  3568. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3569. var magFilter = gl.NEAREST;
  3570. var minFilter = gl.NEAREST;
  3571. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3572. magFilter = gl.LINEAR;
  3573. if (generateMipMaps) {
  3574. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3575. }
  3576. else {
  3577. minFilter = gl.LINEAR;
  3578. }
  3579. }
  3580. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3581. magFilter = gl.LINEAR;
  3582. if (generateMipMaps) {
  3583. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3584. }
  3585. else {
  3586. minFilter = gl.LINEAR;
  3587. }
  3588. }
  3589. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3590. magFilter = gl.NEAREST;
  3591. if (generateMipMaps) {
  3592. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3593. }
  3594. else {
  3595. minFilter = gl.NEAREST;
  3596. }
  3597. }
  3598. return {
  3599. min: minFilter,
  3600. mag: magFilter
  3601. };
  3602. };
  3603. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3604. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3605. var engine = scene.getEngine();
  3606. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3607. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3608. gl.bindTexture(gl.TEXTURE_2D, texture);
  3609. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3610. processFunction(potWidth, potHeight);
  3611. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3612. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3613. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3614. if (!noMipmap && !isCompressed) {
  3615. gl.generateMipmap(gl.TEXTURE_2D);
  3616. }
  3617. gl.bindTexture(gl.TEXTURE_2D, null);
  3618. engine._activeTexturesCache = [];
  3619. texture._baseWidth = width;
  3620. texture._baseHeight = height;
  3621. texture._width = potWidth;
  3622. texture._height = potHeight;
  3623. texture.isReady = true;
  3624. texture.samplingMode = samplingMode;
  3625. scene._removePendingData(texture);
  3626. };
  3627. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3628. var onload = function () {
  3629. loadedImages[index] = img;
  3630. loadedImages._internalCount++;
  3631. scene._removePendingData(img);
  3632. if (loadedImages._internalCount === 6) {
  3633. onfinish(loadedImages);
  3634. }
  3635. };
  3636. var onerror = function () {
  3637. scene._removePendingData(img);
  3638. };
  3639. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3640. scene._addPendingData(img);
  3641. };
  3642. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3643. var loadedImages = [];
  3644. loadedImages._internalCount = 0;
  3645. for (var index = 0; index < 6; index++) {
  3646. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3647. }
  3648. };
  3649. var EngineCapabilities = (function () {
  3650. function EngineCapabilities() {
  3651. }
  3652. return EngineCapabilities;
  3653. })();
  3654. BABYLON.EngineCapabilities = EngineCapabilities;
  3655. /**
  3656. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3657. */
  3658. var Engine = (function () {
  3659. /**
  3660. * @constructor
  3661. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3662. * @param {boolean} [antialias] - enable antialias
  3663. * @param options - further options to be sent to the getContext function
  3664. */
  3665. function Engine(canvas, antialias, options) {
  3666. var _this = this;
  3667. // Public members
  3668. this.isFullscreen = false;
  3669. this.isPointerLock = false;
  3670. this.cullBackFaces = true;
  3671. this.renderEvenInBackground = true;
  3672. this.scenes = new Array();
  3673. this._windowIsBackground = false;
  3674. this._loadingDivBackgroundColor = "black";
  3675. this._drawCalls = 0;
  3676. this._renderingQueueLaunched = false;
  3677. this._activeRenderLoops = [];
  3678. // FPS
  3679. this.fpsRange = 60;
  3680. this.previousFramesDuration = [];
  3681. this.fps = 60;
  3682. this.deltaTime = 0;
  3683. // States
  3684. this._depthCullingState = new _DepthCullingState();
  3685. this._alphaState = new _AlphaState();
  3686. this._alphaMode = Engine.ALPHA_DISABLE;
  3687. // Cache
  3688. this._loadedTexturesCache = new Array();
  3689. this._activeTexturesCache = new Array();
  3690. this._compiledEffects = {};
  3691. this._uintIndicesCurrentlySet = false;
  3692. this._renderingCanvas = canvas;
  3693. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3694. options = options || {};
  3695. options.antialias = antialias;
  3696. try {
  3697. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3698. }
  3699. catch (e) {
  3700. throw new Error("WebGL not supported");
  3701. }
  3702. if (!this._gl) {
  3703. throw new Error("WebGL not supported");
  3704. }
  3705. this._onBlur = function () {
  3706. _this._windowIsBackground = true;
  3707. };
  3708. this._onFocus = function () {
  3709. _this._windowIsBackground = false;
  3710. };
  3711. window.addEventListener("blur", this._onBlur);
  3712. window.addEventListener("focus", this._onFocus);
  3713. // Textures
  3714. this._workingCanvas = document.createElement("canvas");
  3715. this._workingContext = this._workingCanvas.getContext("2d");
  3716. // Viewport
  3717. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3718. this.resize();
  3719. // Caps
  3720. this._caps = new EngineCapabilities();
  3721. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3722. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3723. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3724. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3725. // Infos
  3726. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3727. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3728. if (rendererInfo != null) {
  3729. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3730. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3731. }
  3732. if (!this._glVendor) {
  3733. this._glVendor = "Unknown vendor";
  3734. }
  3735. if (!this._glRenderer) {
  3736. this._glRenderer = "Unknown renderer";
  3737. }
  3738. // Extensions
  3739. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3740. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3741. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3742. 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');
  3743. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3744. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3745. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3746. // Depth buffer
  3747. this.setDepthBuffer(true);
  3748. this.setDepthFunctionToLessOrEqual();
  3749. this.setDepthWrite(true);
  3750. // Fullscreen
  3751. this._onFullscreenChange = function () {
  3752. if (document.fullscreen !== undefined) {
  3753. _this.isFullscreen = document.fullscreen;
  3754. }
  3755. else if (document.mozFullScreen !== undefined) {
  3756. _this.isFullscreen = document.mozFullScreen;
  3757. }
  3758. else if (document.webkitIsFullScreen !== undefined) {
  3759. _this.isFullscreen = document.webkitIsFullScreen;
  3760. }
  3761. else if (document.msIsFullScreen !== undefined) {
  3762. _this.isFullscreen = document.msIsFullScreen;
  3763. }
  3764. // Pointer lock
  3765. if (_this.isFullscreen && _this._pointerLockRequested) {
  3766. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3767. if (canvas.requestPointerLock) {
  3768. canvas.requestPointerLock();
  3769. }
  3770. }
  3771. };
  3772. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3773. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3774. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3775. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3776. // Pointer lock
  3777. this._onPointerLockChange = function () {
  3778. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3779. };
  3780. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3781. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3782. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3783. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3784. if (!Engine.audioEngine) {
  3785. Engine.audioEngine = new BABYLON.AudioEngine();
  3786. }
  3787. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3788. }
  3789. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3790. get: function () {
  3791. return Engine._ALPHA_DISABLE;
  3792. },
  3793. enumerable: true,
  3794. configurable: true
  3795. });
  3796. Object.defineProperty(Engine, "ALPHA_ADD", {
  3797. get: function () {
  3798. return Engine._ALPHA_ADD;
  3799. },
  3800. enumerable: true,
  3801. configurable: true
  3802. });
  3803. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3804. get: function () {
  3805. return Engine._ALPHA_COMBINE;
  3806. },
  3807. enumerable: true,
  3808. configurable: true
  3809. });
  3810. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3811. get: function () {
  3812. return Engine._DELAYLOADSTATE_NONE;
  3813. },
  3814. enumerable: true,
  3815. configurable: true
  3816. });
  3817. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3818. get: function () {
  3819. return Engine._DELAYLOADSTATE_LOADED;
  3820. },
  3821. enumerable: true,
  3822. configurable: true
  3823. });
  3824. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3825. get: function () {
  3826. return Engine._DELAYLOADSTATE_LOADING;
  3827. },
  3828. enumerable: true,
  3829. configurable: true
  3830. });
  3831. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3832. get: function () {
  3833. return Engine._DELAYLOADSTATE_NOTLOADED;
  3834. },
  3835. enumerable: true,
  3836. configurable: true
  3837. });
  3838. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3839. get: function () {
  3840. return Engine._TEXTUREFORMAT_ALPHA;
  3841. },
  3842. enumerable: true,
  3843. configurable: true
  3844. });
  3845. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3846. get: function () {
  3847. return Engine._TEXTUREFORMAT_LUMINANCE;
  3848. },
  3849. enumerable: true,
  3850. configurable: true
  3851. });
  3852. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3853. get: function () {
  3854. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3855. },
  3856. enumerable: true,
  3857. configurable: true
  3858. });
  3859. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3860. get: function () {
  3861. return Engine._TEXTUREFORMAT_RGB;
  3862. },
  3863. enumerable: true,
  3864. configurable: true
  3865. });
  3866. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3867. get: function () {
  3868. return Engine._TEXTUREFORMAT_RGBA;
  3869. },
  3870. enumerable: true,
  3871. configurable: true
  3872. });
  3873. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3874. get: function () {
  3875. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3876. },
  3877. enumerable: true,
  3878. configurable: true
  3879. });
  3880. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3881. get: function () {
  3882. return Engine._TEXTURETYPE_FLOAT;
  3883. },
  3884. enumerable: true,
  3885. configurable: true
  3886. });
  3887. Object.defineProperty(Engine, "Version", {
  3888. get: function () {
  3889. return "2.1.0 alpha";
  3890. },
  3891. enumerable: true,
  3892. configurable: true
  3893. });
  3894. Engine.prototype.getGlInfo = function () {
  3895. return {
  3896. vendor: this._glVendor,
  3897. renderer: this._glRenderer,
  3898. version: this._glVersion
  3899. };
  3900. };
  3901. Engine.prototype.getAspectRatio = function (camera) {
  3902. var viewport = camera.viewport;
  3903. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3904. };
  3905. Engine.prototype.getRenderWidth = function () {
  3906. if (this._currentRenderTarget) {
  3907. return this._currentRenderTarget._width;
  3908. }
  3909. return this._renderingCanvas.width;
  3910. };
  3911. Engine.prototype.getRenderHeight = function () {
  3912. if (this._currentRenderTarget) {
  3913. return this._currentRenderTarget._height;
  3914. }
  3915. return this._renderingCanvas.height;
  3916. };
  3917. Engine.prototype.getRenderingCanvas = function () {
  3918. return this._renderingCanvas;
  3919. };
  3920. Engine.prototype.getRenderingCanvasClientRect = function () {
  3921. return this._renderingCanvas.getBoundingClientRect();
  3922. };
  3923. Engine.prototype.setHardwareScalingLevel = function (level) {
  3924. this._hardwareScalingLevel = level;
  3925. this.resize();
  3926. };
  3927. Engine.prototype.getHardwareScalingLevel = function () {
  3928. return this._hardwareScalingLevel;
  3929. };
  3930. Engine.prototype.getLoadedTexturesCache = function () {
  3931. return this._loadedTexturesCache;
  3932. };
  3933. Engine.prototype.getCaps = function () {
  3934. return this._caps;
  3935. };
  3936. Object.defineProperty(Engine.prototype, "drawCalls", {
  3937. get: function () {
  3938. return this._drawCalls;
  3939. },
  3940. enumerable: true,
  3941. configurable: true
  3942. });
  3943. // Methods
  3944. Engine.prototype.resetDrawCalls = function () {
  3945. this._drawCalls = 0;
  3946. };
  3947. Engine.prototype.setDepthFunctionToGreater = function () {
  3948. this._depthCullingState.depthFunc = this._gl.GREATER;
  3949. };
  3950. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3951. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3952. };
  3953. Engine.prototype.setDepthFunctionToLess = function () {
  3954. this._depthCullingState.depthFunc = this._gl.LESS;
  3955. };
  3956. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3957. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3958. };
  3959. /**
  3960. * stop executing a render loop function and remove it from the execution array
  3961. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3962. */
  3963. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3964. if (!renderFunction) {
  3965. this._activeRenderLoops = [];
  3966. return;
  3967. }
  3968. var index = this._activeRenderLoops.indexOf(renderFunction);
  3969. if (index >= 0) {
  3970. this._activeRenderLoops.splice(index, 1);
  3971. }
  3972. };
  3973. Engine.prototype._renderLoop = function () {
  3974. var _this = this;
  3975. var shouldRender = true;
  3976. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3977. shouldRender = false;
  3978. }
  3979. if (shouldRender) {
  3980. // Start new frame
  3981. this.beginFrame();
  3982. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3983. var renderFunction = this._activeRenderLoops[index];
  3984. renderFunction();
  3985. }
  3986. // Present
  3987. this.endFrame();
  3988. }
  3989. if (this._activeRenderLoops.length > 0) {
  3990. // Register new frame
  3991. BABYLON.Tools.QueueNewFrame(function () {
  3992. _this._renderLoop();
  3993. });
  3994. }
  3995. else {
  3996. this._renderingQueueLaunched = false;
  3997. }
  3998. };
  3999. /**
  4000. * Register and execute a render loop. The engine can have more than one render function.
  4001. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  4002. * @example
  4003. * engine.runRenderLoop(function () {
  4004. * scene.render()
  4005. * })
  4006. */
  4007. Engine.prototype.runRenderLoop = function (renderFunction) {
  4008. var _this = this;
  4009. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  4010. return;
  4011. }
  4012. this._activeRenderLoops.push(renderFunction);
  4013. if (!this._renderingQueueLaunched) {
  4014. this._renderingQueueLaunched = true;
  4015. BABYLON.Tools.QueueNewFrame(function () {
  4016. _this._renderLoop();
  4017. });
  4018. }
  4019. };
  4020. /**
  4021. * Toggle full screen mode.
  4022. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  4023. */
  4024. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  4025. if (this.isFullscreen) {
  4026. BABYLON.Tools.ExitFullscreen();
  4027. }
  4028. else {
  4029. this._pointerLockRequested = requestPointerLock;
  4030. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  4031. }
  4032. };
  4033. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  4034. this.applyStates();
  4035. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  4036. if (this._depthCullingState.depthMask) {
  4037. this._gl.clearDepth(1.0);
  4038. }
  4039. var mode = 0;
  4040. if (backBuffer)
  4041. mode |= this._gl.COLOR_BUFFER_BIT;
  4042. if (depthStencil && this._depthCullingState.depthMask)
  4043. mode |= this._gl.DEPTH_BUFFER_BIT;
  4044. this._gl.clear(mode);
  4045. };
  4046. /**
  4047. * Set the WebGL's viewport
  4048. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4049. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4050. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4051. */
  4052. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4053. var width = requiredWidth || this._renderingCanvas.width;
  4054. var height = requiredHeight || this._renderingCanvas.height;
  4055. var x = viewport.x || 0;
  4056. var y = viewport.y || 0;
  4057. this._cachedViewport = viewport;
  4058. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4059. };
  4060. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4061. this._cachedViewport = null;
  4062. this._gl.viewport(x, y, width, height);
  4063. };
  4064. Engine.prototype.beginFrame = function () {
  4065. this._measureFps();
  4066. };
  4067. Engine.prototype.endFrame = function () {
  4068. //this.flushFramebuffer();
  4069. };
  4070. /**
  4071. * resize the view according to the canvas' size.
  4072. * @example
  4073. * window.addEventListener("resize", function () {
  4074. * engine.resize();
  4075. * });
  4076. */
  4077. Engine.prototype.resize = function () {
  4078. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4079. };
  4080. /**
  4081. * force a specific size of the canvas
  4082. * @param {number} width - the new canvas' width
  4083. * @param {number} height - the new canvas' height
  4084. */
  4085. Engine.prototype.setSize = function (width, height) {
  4086. this._renderingCanvas.width = width;
  4087. this._renderingCanvas.height = height;
  4088. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4089. };
  4090. Engine.prototype.bindFramebuffer = function (texture) {
  4091. this._currentRenderTarget = texture;
  4092. var gl = this._gl;
  4093. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4094. this._gl.viewport(0, 0, texture._width, texture._height);
  4095. this.wipeCaches();
  4096. };
  4097. Engine.prototype.unBindFramebuffer = function (texture) {
  4098. this._currentRenderTarget = null;
  4099. if (texture.generateMipMaps) {
  4100. var gl = this._gl;
  4101. gl.bindTexture(gl.TEXTURE_2D, texture);
  4102. gl.generateMipmap(gl.TEXTURE_2D);
  4103. gl.bindTexture(gl.TEXTURE_2D, null);
  4104. }
  4105. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4106. };
  4107. Engine.prototype.flushFramebuffer = function () {
  4108. this._gl.flush();
  4109. };
  4110. Engine.prototype.restoreDefaultFramebuffer = function () {
  4111. this._currentRenderTarget = null;
  4112. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4113. this.setViewport(this._cachedViewport);
  4114. this.wipeCaches();
  4115. };
  4116. // VBOs
  4117. Engine.prototype._resetVertexBufferBinding = function () {
  4118. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4119. this._cachedVertexBuffers = null;
  4120. };
  4121. Engine.prototype.createVertexBuffer = function (vertices) {
  4122. var vbo = this._gl.createBuffer();
  4123. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4124. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4125. this._resetVertexBufferBinding();
  4126. vbo.references = 1;
  4127. return vbo;
  4128. };
  4129. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4130. var vbo = this._gl.createBuffer();
  4131. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4132. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4133. this._resetVertexBufferBinding();
  4134. vbo.references = 1;
  4135. return vbo;
  4136. };
  4137. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4138. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4139. if (offset === undefined) {
  4140. offset = 0;
  4141. }
  4142. if (vertices instanceof Float32Array) {
  4143. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4144. }
  4145. else {
  4146. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4147. }
  4148. this._resetVertexBufferBinding();
  4149. };
  4150. Engine.prototype._resetIndexBufferBinding = function () {
  4151. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4152. this._cachedIndexBuffer = null;
  4153. };
  4154. Engine.prototype.createIndexBuffer = function (indices) {
  4155. var vbo = this._gl.createBuffer();
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4157. // Check for 32 bits indices
  4158. var arrayBuffer;
  4159. var need32Bits = false;
  4160. if (this._caps.uintIndices) {
  4161. for (var index = 0; index < indices.length; index++) {
  4162. if (indices[index] > 65535) {
  4163. need32Bits = true;
  4164. break;
  4165. }
  4166. }
  4167. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4168. }
  4169. else {
  4170. arrayBuffer = new Uint16Array(indices);
  4171. }
  4172. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4173. this._resetIndexBufferBinding();
  4174. vbo.references = 1;
  4175. vbo.is32Bits = need32Bits;
  4176. return vbo;
  4177. };
  4178. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4179. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4180. this._cachedVertexBuffers = vertexBuffer;
  4181. this._cachedEffectForVertexBuffers = effect;
  4182. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4183. var offset = 0;
  4184. for (var index = 0; index < vertexDeclaration.length; index++) {
  4185. var order = effect.getAttributeLocation(index);
  4186. if (order >= 0) {
  4187. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4188. }
  4189. offset += vertexDeclaration[index] * 4;
  4190. }
  4191. }
  4192. if (this._cachedIndexBuffer !== indexBuffer) {
  4193. this._cachedIndexBuffer = indexBuffer;
  4194. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4195. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4196. }
  4197. };
  4198. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4199. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4200. this._cachedVertexBuffers = vertexBuffers;
  4201. this._cachedEffectForVertexBuffers = effect;
  4202. var attributes = effect.getAttributesNames();
  4203. for (var index = 0; index < attributes.length; index++) {
  4204. var order = effect.getAttributeLocation(index);
  4205. if (order >= 0) {
  4206. var vertexBuffer = vertexBuffers[attributes[index]];
  4207. if (!vertexBuffer) {
  4208. continue;
  4209. }
  4210. var stride = vertexBuffer.getStrideSize();
  4211. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4212. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4213. }
  4214. }
  4215. }
  4216. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4217. this._cachedIndexBuffer = indexBuffer;
  4218. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4219. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4220. }
  4221. };
  4222. Engine.prototype._releaseBuffer = function (buffer) {
  4223. buffer.references--;
  4224. if (buffer.references === 0) {
  4225. this._gl.deleteBuffer(buffer);
  4226. return true;
  4227. }
  4228. return false;
  4229. };
  4230. Engine.prototype.createInstancesBuffer = function (capacity) {
  4231. var buffer = this._gl.createBuffer();
  4232. buffer.capacity = capacity;
  4233. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4234. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4235. return buffer;
  4236. };
  4237. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4238. this._gl.deleteBuffer(buffer);
  4239. };
  4240. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4241. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4242. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4243. for (var index = 0; index < 4; index++) {
  4244. var offsetLocation = offsetLocations[index];
  4245. this._gl.enableVertexAttribArray(offsetLocation);
  4246. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4247. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4248. }
  4249. };
  4250. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4251. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4252. for (var index = 0; index < 4; index++) {
  4253. var offsetLocation = offsetLocations[index];
  4254. this._gl.disableVertexAttribArray(offsetLocation);
  4255. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4256. }
  4257. };
  4258. Engine.prototype.applyStates = function () {
  4259. this._depthCullingState.apply(this._gl);
  4260. this._alphaState.apply(this._gl);
  4261. };
  4262. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4263. // Apply states
  4264. this.applyStates();
  4265. this._drawCalls++;
  4266. // Render
  4267. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4268. if (instancesCount) {
  4269. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4270. return;
  4271. }
  4272. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4273. };
  4274. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4275. // Apply states
  4276. this.applyStates();
  4277. this._drawCalls++;
  4278. if (instancesCount) {
  4279. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4280. return;
  4281. }
  4282. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4283. };
  4284. // Shaders
  4285. Engine.prototype._releaseEffect = function (effect) {
  4286. if (this._compiledEffects[effect._key]) {
  4287. delete this._compiledEffects[effect._key];
  4288. if (effect.getProgram()) {
  4289. this._gl.deleteProgram(effect.getProgram());
  4290. }
  4291. }
  4292. };
  4293. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4294. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4295. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4296. var name = vertex + "+" + fragment + "@" + defines;
  4297. if (this._compiledEffects[name]) {
  4298. return this._compiledEffects[name];
  4299. }
  4300. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4301. effect._key = name;
  4302. this._compiledEffects[name] = effect;
  4303. return effect;
  4304. };
  4305. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4306. if (uniformsNames === void 0) { uniformsNames = []; }
  4307. if (samplers === void 0) { samplers = []; }
  4308. if (defines === void 0) { defines = ""; }
  4309. return this.createEffect({
  4310. vertex: "particles",
  4311. fragmentElement: fragmentName
  4312. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4313. };
  4314. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4315. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4316. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4317. var shaderProgram = this._gl.createProgram();
  4318. this._gl.attachShader(shaderProgram, vertexShader);
  4319. this._gl.attachShader(shaderProgram, fragmentShader);
  4320. this._gl.linkProgram(shaderProgram);
  4321. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4322. if (!linked) {
  4323. var error = this._gl.getProgramInfoLog(shaderProgram);
  4324. if (error) {
  4325. throw new Error(error);
  4326. }
  4327. }
  4328. this._gl.deleteShader(vertexShader);
  4329. this._gl.deleteShader(fragmentShader);
  4330. return shaderProgram;
  4331. };
  4332. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4333. var results = [];
  4334. for (var index = 0; index < uniformsNames.length; index++) {
  4335. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4336. }
  4337. return results;
  4338. };
  4339. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4340. var results = [];
  4341. for (var index = 0; index < attributesNames.length; index++) {
  4342. try {
  4343. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4344. }
  4345. catch (e) {
  4346. results.push(-1);
  4347. }
  4348. }
  4349. return results;
  4350. };
  4351. Engine.prototype.enableEffect = function (effect) {
  4352. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4353. if (effect && effect.onBind) {
  4354. effect.onBind(effect);
  4355. }
  4356. return;
  4357. }
  4358. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4359. // Use program
  4360. this._gl.useProgram(effect.getProgram());
  4361. for (var i in this._vertexAttribArrays) {
  4362. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4363. continue;
  4364. }
  4365. this._vertexAttribArrays[i] = false;
  4366. this._gl.disableVertexAttribArray(i);
  4367. }
  4368. var attributesCount = effect.getAttributesCount();
  4369. for (var index = 0; index < attributesCount; index++) {
  4370. // Attributes
  4371. var order = effect.getAttributeLocation(index);
  4372. if (order >= 0) {
  4373. this._vertexAttribArrays[order] = true;
  4374. this._gl.enableVertexAttribArray(order);
  4375. }
  4376. }
  4377. this._currentEffect = effect;
  4378. if (effect.onBind) {
  4379. effect.onBind(effect);
  4380. }
  4381. };
  4382. Engine.prototype.setArray = function (uniform, array) {
  4383. if (!uniform)
  4384. return;
  4385. this._gl.uniform1fv(uniform, array);
  4386. };
  4387. Engine.prototype.setArray2 = function (uniform, array) {
  4388. if (!uniform || array.length % 2 !== 0)
  4389. return;
  4390. this._gl.uniform2fv(uniform, array);
  4391. };
  4392. Engine.prototype.setArray3 = function (uniform, array) {
  4393. if (!uniform || array.length % 3 !== 0)
  4394. return;
  4395. this._gl.uniform3fv(uniform, array);
  4396. };
  4397. Engine.prototype.setArray4 = function (uniform, array) {
  4398. if (!uniform || array.length % 4 !== 0)
  4399. return;
  4400. this._gl.uniform4fv(uniform, array);
  4401. };
  4402. Engine.prototype.setMatrices = function (uniform, matrices) {
  4403. if (!uniform)
  4404. return;
  4405. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4406. };
  4407. Engine.prototype.setMatrix = function (uniform, matrix) {
  4408. if (!uniform)
  4409. return;
  4410. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4411. };
  4412. Engine.prototype.setFloat = function (uniform, value) {
  4413. if (!uniform)
  4414. return;
  4415. this._gl.uniform1f(uniform, value);
  4416. };
  4417. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4418. if (!uniform)
  4419. return;
  4420. this._gl.uniform2f(uniform, x, y);
  4421. };
  4422. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4423. if (!uniform)
  4424. return;
  4425. this._gl.uniform3f(uniform, x, y, z);
  4426. };
  4427. Engine.prototype.setBool = function (uniform, bool) {
  4428. if (!uniform)
  4429. return;
  4430. this._gl.uniform1i(uniform, bool);
  4431. };
  4432. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4433. if (!uniform)
  4434. return;
  4435. this._gl.uniform4f(uniform, x, y, z, w);
  4436. };
  4437. Engine.prototype.setColor3 = function (uniform, color3) {
  4438. if (!uniform)
  4439. return;
  4440. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4441. };
  4442. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4443. if (!uniform)
  4444. return;
  4445. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4446. };
  4447. // States
  4448. Engine.prototype.setState = function (culling, force) {
  4449. // Culling
  4450. if (this._depthCullingState.cull !== culling || force) {
  4451. if (culling) {
  4452. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4453. this._depthCullingState.cull = true;
  4454. }
  4455. else {
  4456. this._depthCullingState.cull = false;
  4457. }
  4458. }
  4459. };
  4460. Engine.prototype.setDepthBuffer = function (enable) {
  4461. this._depthCullingState.depthTest = enable;
  4462. };
  4463. Engine.prototype.getDepthWrite = function () {
  4464. return this._depthCullingState.depthMask;
  4465. };
  4466. Engine.prototype.setDepthWrite = function (enable) {
  4467. this._depthCullingState.depthMask = enable;
  4468. };
  4469. Engine.prototype.setColorWrite = function (enable) {
  4470. this._gl.colorMask(enable, enable, enable, enable);
  4471. };
  4472. Engine.prototype.setAlphaMode = function (mode) {
  4473. switch (mode) {
  4474. case Engine.ALPHA_DISABLE:
  4475. this.setDepthWrite(true);
  4476. this._alphaState.alphaBlend = false;
  4477. break;
  4478. case Engine.ALPHA_COMBINE:
  4479. this.setDepthWrite(false);
  4480. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4481. this._alphaState.alphaBlend = true;
  4482. break;
  4483. case Engine.ALPHA_ADD:
  4484. this.setDepthWrite(false);
  4485. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4486. this._alphaState.alphaBlend = true;
  4487. break;
  4488. }
  4489. this._alphaMode = mode;
  4490. };
  4491. Engine.prototype.getAlphaMode = function () {
  4492. return this._alphaMode;
  4493. };
  4494. Engine.prototype.setAlphaTesting = function (enable) {
  4495. this._alphaTest = enable;
  4496. };
  4497. Engine.prototype.getAlphaTesting = function () {
  4498. return this._alphaTest;
  4499. };
  4500. // Textures
  4501. Engine.prototype.wipeCaches = function () {
  4502. this._activeTexturesCache = [];
  4503. this._currentEffect = null;
  4504. this._depthCullingState.reset();
  4505. this._alphaState.reset();
  4506. this._cachedVertexBuffers = null;
  4507. this._cachedIndexBuffer = null;
  4508. this._cachedEffectForVertexBuffers = null;
  4509. };
  4510. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4511. var gl = this._gl;
  4512. gl.bindTexture(gl.TEXTURE_2D, texture);
  4513. var magFilter = gl.NEAREST;
  4514. var minFilter = gl.NEAREST;
  4515. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4516. magFilter = gl.LINEAR;
  4517. minFilter = gl.LINEAR;
  4518. }
  4519. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4520. magFilter = gl.LINEAR;
  4521. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4522. }
  4523. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4524. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4525. gl.bindTexture(gl.TEXTURE_2D, null);
  4526. texture.samplingMode = samplingMode;
  4527. };
  4528. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4529. var _this = this;
  4530. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4531. if (onLoad === void 0) { onLoad = null; }
  4532. if (onError === void 0) { onError = null; }
  4533. if (buffer === void 0) { buffer = null; }
  4534. var texture = this._gl.createTexture();
  4535. var extension;
  4536. var fromData = false;
  4537. if (url.substr(0, 5) === "data:") {
  4538. fromData = true;
  4539. }
  4540. if (!fromData)
  4541. extension = url.substr(url.length - 4, 4).toLowerCase();
  4542. else {
  4543. var oldUrl = url;
  4544. fromData = oldUrl.split(':');
  4545. url = oldUrl;
  4546. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4547. }
  4548. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4549. var isTGA = (extension === ".tga");
  4550. scene._addPendingData(texture);
  4551. texture.url = url;
  4552. texture.noMipmap = noMipmap;
  4553. texture.references = 1;
  4554. this._loadedTexturesCache.push(texture);
  4555. var onerror = function () {
  4556. scene._removePendingData(texture);
  4557. if (onError) {
  4558. onError();
  4559. }
  4560. };
  4561. if (isTGA) {
  4562. var callback = function (arrayBuffer) {
  4563. var data = new Uint8Array(arrayBuffer);
  4564. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4565. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4566. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4567. if (onLoad) {
  4568. onLoad();
  4569. }
  4570. }, samplingMode);
  4571. };
  4572. if (!(fromData instanceof Array))
  4573. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4574. callback(arrayBuffer);
  4575. }, onerror, scene.database, true);
  4576. else
  4577. callback(buffer);
  4578. }
  4579. else if (isDDS) {
  4580. callback = function (data) {
  4581. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4582. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4583. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4584. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4585. if (onLoad) {
  4586. onLoad();
  4587. }
  4588. }, samplingMode);
  4589. };
  4590. if (!(fromData instanceof Array))
  4591. BABYLON.Tools.LoadFile(url, function (data) {
  4592. callback(data);
  4593. }, onerror, scene.database, true);
  4594. else
  4595. callback(buffer);
  4596. }
  4597. else {
  4598. var onload = function (img) {
  4599. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4600. var isPot = (img.width === potWidth && img.height === potHeight);
  4601. if (!isPot) {
  4602. _this._workingCanvas.width = potWidth;
  4603. _this._workingCanvas.height = potHeight;
  4604. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4605. _this._workingContext.imageSmoothingEnabled = false;
  4606. _this._workingContext.mozImageSmoothingEnabled = false;
  4607. _this._workingContext.oImageSmoothingEnabled = false;
  4608. _this._workingContext.webkitImageSmoothingEnabled = false;
  4609. _this._workingContext.msImageSmoothingEnabled = false;
  4610. }
  4611. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4612. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4613. _this._workingContext.imageSmoothingEnabled = true;
  4614. _this._workingContext.mozImageSmoothingEnabled = true;
  4615. _this._workingContext.oImageSmoothingEnabled = true;
  4616. _this._workingContext.webkitImageSmoothingEnabled = true;
  4617. _this._workingContext.msImageSmoothingEnabled = true;
  4618. }
  4619. }
  4620. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4621. if (onLoad) {
  4622. onLoad();
  4623. }
  4624. }, samplingMode);
  4625. };
  4626. if (!(fromData instanceof Array))
  4627. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4628. else
  4629. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4630. }
  4631. return texture;
  4632. };
  4633. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4634. var texture = this._gl.createTexture();
  4635. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4636. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4637. // Format
  4638. var internalFormat = this._gl.RGBA;
  4639. switch (format) {
  4640. case Engine.TEXTUREFORMAT_ALPHA:
  4641. internalFormat = this._gl.ALPHA;
  4642. break;
  4643. case Engine.TEXTUREFORMAT_LUMINANCE:
  4644. internalFormat = this._gl.LUMINANCE;
  4645. break;
  4646. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4647. internalFormat = this._gl.LUMINANCE_ALPHA;
  4648. break;
  4649. case Engine.TEXTUREFORMAT_RGB:
  4650. internalFormat = this._gl.RGB;
  4651. break;
  4652. case Engine.TEXTUREFORMAT_RGBA:
  4653. internalFormat = this._gl.RGBA;
  4654. break;
  4655. }
  4656. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4657. if (generateMipMaps) {
  4658. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4659. }
  4660. // Filters
  4661. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4662. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4663. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4664. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4665. this._activeTexturesCache = [];
  4666. texture._baseWidth = width;
  4667. texture._baseHeight = height;
  4668. texture._width = width;
  4669. texture._height = height;
  4670. texture.isReady = true;
  4671. texture.references = 1;
  4672. texture.samplingMode = samplingMode;
  4673. this._loadedTexturesCache.push(texture);
  4674. return texture;
  4675. };
  4676. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4677. var texture = this._gl.createTexture();
  4678. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4679. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4680. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4681. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4682. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4683. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4684. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4685. this._activeTexturesCache = [];
  4686. texture._baseWidth = width;
  4687. texture._baseHeight = height;
  4688. texture._width = width;
  4689. texture._height = height;
  4690. texture.isReady = false;
  4691. texture.generateMipMaps = generateMipMaps;
  4692. texture.references = 1;
  4693. texture.samplingMode = samplingMode;
  4694. this._loadedTexturesCache.push(texture);
  4695. return texture;
  4696. };
  4697. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4698. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4699. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4700. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4701. if (texture.generateMipMaps) {
  4702. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4703. }
  4704. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4705. this._activeTexturesCache = [];
  4706. texture.isReady = true;
  4707. };
  4708. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4709. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4710. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4711. // Scale the video if it is a NPOT using the current working canvas
  4712. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4713. if (!texture._workingCanvas) {
  4714. texture._workingCanvas = document.createElement("canvas");
  4715. texture._workingContext = texture._workingCanvas.getContext("2d");
  4716. texture._workingCanvas.width = texture._width;
  4717. texture._workingCanvas.height = texture._height;
  4718. }
  4719. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4720. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4721. }
  4722. else {
  4723. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4724. }
  4725. if (texture.generateMipMaps) {
  4726. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4727. }
  4728. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4729. this._activeTexturesCache = [];
  4730. texture.isReady = true;
  4731. };
  4732. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4733. // old version had a "generateMipMaps" arg instead of options.
  4734. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4735. // in the same way, generateDepthBuffer is defaulted to true
  4736. var generateMipMaps = false;
  4737. var generateDepthBuffer = true;
  4738. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4739. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4740. if (options !== undefined) {
  4741. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4742. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4743. type = options.type === undefined ? type : options.type;
  4744. if (options.samplingMode !== undefined) {
  4745. samplingMode = options.samplingMode;
  4746. }
  4747. if (type === Engine.TEXTURETYPE_FLOAT) {
  4748. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4749. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4750. }
  4751. }
  4752. var gl = this._gl;
  4753. var texture = gl.createTexture();
  4754. gl.bindTexture(gl.TEXTURE_2D, texture);
  4755. var width = size.width || size;
  4756. var height = size.height || size;
  4757. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4758. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4759. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4760. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4761. }
  4762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4763. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4764. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4765. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4766. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4767. var depthBuffer;
  4768. // Create the depth buffer
  4769. if (generateDepthBuffer) {
  4770. depthBuffer = gl.createRenderbuffer();
  4771. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4772. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4773. }
  4774. // Create the framebuffer
  4775. var framebuffer = gl.createFramebuffer();
  4776. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4777. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4778. if (generateDepthBuffer) {
  4779. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4780. }
  4781. // Unbind
  4782. gl.bindTexture(gl.TEXTURE_2D, null);
  4783. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4784. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4785. texture._framebuffer = framebuffer;
  4786. if (generateDepthBuffer) {
  4787. texture._depthBuffer = depthBuffer;
  4788. }
  4789. texture._width = width;
  4790. texture._height = height;
  4791. texture.isReady = true;
  4792. texture.generateMipMaps = generateMipMaps;
  4793. texture.references = 1;
  4794. texture.samplingMode = samplingMode;
  4795. this._activeTexturesCache = [];
  4796. this._loadedTexturesCache.push(texture);
  4797. return texture;
  4798. };
  4799. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4800. var _this = this;
  4801. var gl = this._gl;
  4802. var texture = gl.createTexture();
  4803. texture.isCube = true;
  4804. texture.url = rootUrl;
  4805. texture.references = 1;
  4806. this._loadedTexturesCache.push(texture);
  4807. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4808. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4809. if (isDDS) {
  4810. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4811. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4812. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4813. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4814. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4815. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4816. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4817. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4818. }
  4819. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4820. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4821. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4822. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4823. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4824. _this._activeTexturesCache = [];
  4825. texture._width = info.width;
  4826. texture._height = info.height;
  4827. texture.isReady = true;
  4828. }, null, null, true);
  4829. }
  4830. else {
  4831. cascadeLoad(rootUrl, scene, function (imgs) {
  4832. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4833. var height = width;
  4834. _this._workingCanvas.width = width;
  4835. _this._workingCanvas.height = height;
  4836. var faces = [
  4837. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4838. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4839. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4840. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4841. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4842. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4843. ];
  4844. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4845. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4846. for (var index = 0; index < faces.length; index++) {
  4847. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4848. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4849. }
  4850. if (!noMipmap) {
  4851. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4852. }
  4853. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4854. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4855. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4856. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4857. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4858. _this._activeTexturesCache = [];
  4859. texture._width = width;
  4860. texture._height = height;
  4861. texture.isReady = true;
  4862. }, extensions);
  4863. }
  4864. return texture;
  4865. };
  4866. Engine.prototype._releaseTexture = function (texture) {
  4867. var gl = this._gl;
  4868. if (texture._framebuffer) {
  4869. gl.deleteFramebuffer(texture._framebuffer);
  4870. }
  4871. if (texture._depthBuffer) {
  4872. gl.deleteRenderbuffer(texture._depthBuffer);
  4873. }
  4874. gl.deleteTexture(texture);
  4875. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4876. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4877. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4878. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4879. this._activeTexturesCache[channel] = null;
  4880. }
  4881. var index = this._loadedTexturesCache.indexOf(texture);
  4882. if (index !== -1) {
  4883. this._loadedTexturesCache.splice(index, 1);
  4884. }
  4885. };
  4886. Engine.prototype.bindSamplers = function (effect) {
  4887. this._gl.useProgram(effect.getProgram());
  4888. var samplers = effect.getSamplers();
  4889. for (var index = 0; index < samplers.length; index++) {
  4890. var uniform = effect.getUniform(samplers[index]);
  4891. this._gl.uniform1i(uniform, index);
  4892. }
  4893. this._currentEffect = null;
  4894. };
  4895. Engine.prototype._bindTexture = function (channel, texture) {
  4896. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4897. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4898. this._activeTexturesCache[channel] = null;
  4899. };
  4900. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4901. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4902. };
  4903. Engine.prototype.setTexture = function (channel, texture) {
  4904. if (channel < 0) {
  4905. return;
  4906. }
  4907. // Not ready?
  4908. if (!texture || !texture.isReady()) {
  4909. if (this._activeTexturesCache[channel] != null) {
  4910. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4911. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4912. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4913. this._activeTexturesCache[channel] = null;
  4914. }
  4915. return;
  4916. }
  4917. // Video
  4918. if (texture instanceof BABYLON.VideoTexture) {
  4919. if (texture.update()) {
  4920. this._activeTexturesCache[channel] = null;
  4921. }
  4922. }
  4923. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4924. texture.delayLoad();
  4925. return;
  4926. }
  4927. if (this._activeTexturesCache[channel] === texture) {
  4928. return;
  4929. }
  4930. this._activeTexturesCache[channel] = texture;
  4931. var internalTexture = texture.getInternalTexture();
  4932. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4933. if (internalTexture.isCube) {
  4934. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4935. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4936. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4937. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4938. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4939. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4940. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4941. }
  4942. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4943. }
  4944. else {
  4945. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4946. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4947. internalTexture._cachedWrapU = texture.wrapU;
  4948. switch (texture.wrapU) {
  4949. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4950. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4951. break;
  4952. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4953. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4954. break;
  4955. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4956. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4957. break;
  4958. }
  4959. }
  4960. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4961. internalTexture._cachedWrapV = texture.wrapV;
  4962. switch (texture.wrapV) {
  4963. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4964. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4965. break;
  4966. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4967. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4968. break;
  4969. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4970. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4971. break;
  4972. }
  4973. }
  4974. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4975. }
  4976. };
  4977. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4978. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4979. var value = texture.anisotropicFilteringLevel;
  4980. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4981. value = 1;
  4982. }
  4983. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  4984. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  4985. texture._cachedAnisotropicFilteringLevel = value;
  4986. }
  4987. };
  4988. Engine.prototype.readPixels = function (x, y, width, height) {
  4989. var data = new Uint8Array(height * width * 4);
  4990. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4991. return data;
  4992. };
  4993. // Dispose
  4994. Engine.prototype.dispose = function () {
  4995. this.hideLoadingUI();
  4996. this.stopRenderLoop();
  4997. while (this.scenes.length) {
  4998. this.scenes[0].dispose();
  4999. }
  5000. // Release audio engine
  5001. Engine.audioEngine.dispose();
  5002. for (var name in this._compiledEffects) {
  5003. this._gl.deleteProgram(this._compiledEffects[name]._program);
  5004. }
  5005. for (var i in this._vertexAttribArrays) {
  5006. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  5007. continue;
  5008. }
  5009. this._gl.disableVertexAttribArray(i);
  5010. }
  5011. // Events
  5012. window.removeEventListener("blur", this._onBlur);
  5013. window.removeEventListener("focus", this._onFocus);
  5014. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  5015. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  5016. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  5017. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  5018. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  5019. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  5020. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  5021. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  5022. };
  5023. // Loading screen
  5024. Engine.prototype.displayLoadingUI = function () {
  5025. var _this = this;
  5026. this._loadingDiv = document.createElement("div");
  5027. this._loadingDiv.style.opacity = "0";
  5028. this._loadingDiv.style.transition = "opacity 1.5s ease";
  5029. // Loading text
  5030. this._loadingTextDiv = document.createElement("div");
  5031. this._loadingTextDiv.style.position = "absolute";
  5032. this._loadingTextDiv.style.left = "0";
  5033. this._loadingTextDiv.style.top = "50%";
  5034. this._loadingTextDiv.style.marginTop = "80px";
  5035. this._loadingTextDiv.style.width = "100%";
  5036. this._loadingTextDiv.style.height = "20px";
  5037. this._loadingTextDiv.style.fontFamily = "Arial";
  5038. this._loadingTextDiv.style.fontSize = "14px";
  5039. this._loadingTextDiv.style.color = "white";
  5040. this._loadingTextDiv.style.textAlign = "center";
  5041. this._loadingTextDiv.innerHTML = "Loading";
  5042. this._loadingDiv.appendChild(this._loadingTextDiv);
  5043. // Loading img
  5044. var imgBack = new Image();
  5045. 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==";
  5046. imgBack.style.position = "absolute";
  5047. imgBack.style.left = "50%";
  5048. imgBack.style.top = "50%";
  5049. imgBack.style.marginLeft = "-50px";
  5050. imgBack.style.marginTop = "-50px";
  5051. imgBack.style.transition = "transform 1.0s ease";
  5052. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5053. var deg = 360;
  5054. var onTransitionEnd = function () {
  5055. deg += 360;
  5056. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5057. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5058. };
  5059. imgBack.addEventListener("transitionend", onTransitionEnd);
  5060. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5061. this._loadingDiv.appendChild(imgBack);
  5062. // front image
  5063. var imgFront = new Image();
  5064. 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=";
  5065. imgFront.style.position = "absolute";
  5066. imgFront.style.left = "50%";
  5067. imgFront.style.top = "50%";
  5068. imgFront.style.marginLeft = "-50px";
  5069. imgFront.style.marginTop = "-50px";
  5070. this._loadingDiv.appendChild(imgFront);
  5071. // Resize
  5072. this._resizeLoadingUI = function () {
  5073. var canvasRect = _this.getRenderingCanvasClientRect();
  5074. _this._loadingDiv.style.position = "absolute";
  5075. _this._loadingDiv.style.left = canvasRect.left + "px";
  5076. _this._loadingDiv.style.top = canvasRect.top + "px";
  5077. _this._loadingDiv.style.width = canvasRect.width + "px";
  5078. _this._loadingDiv.style.height = canvasRect.height + "px";
  5079. };
  5080. this._resizeLoadingUI();
  5081. window.addEventListener("resize", this._resizeLoadingUI);
  5082. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5083. document.body.appendChild(this._loadingDiv);
  5084. setTimeout(function () {
  5085. _this._loadingDiv.style.opacity = "1";
  5086. imgBack.style.transform = "rotateZ(360deg)";
  5087. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5088. }, 0);
  5089. };
  5090. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5091. set: function (text) {
  5092. if (!this._loadingDiv) {
  5093. return;
  5094. }
  5095. this._loadingTextDiv.innerHTML = text;
  5096. },
  5097. enumerable: true,
  5098. configurable: true
  5099. });
  5100. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5101. get: function () {
  5102. return this._loadingDivBackgroundColor;
  5103. },
  5104. set: function (color) {
  5105. this._loadingDivBackgroundColor = color;
  5106. if (!this._loadingDiv) {
  5107. return;
  5108. }
  5109. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5110. },
  5111. enumerable: true,
  5112. configurable: true
  5113. });
  5114. Engine.prototype.hideLoadingUI = function () {
  5115. var _this = this;
  5116. if (!this._loadingDiv) {
  5117. return;
  5118. }
  5119. var onTransitionEnd = function () {
  5120. if (!_this._loadingDiv) {
  5121. return;
  5122. }
  5123. document.body.removeChild(_this._loadingDiv);
  5124. window.removeEventListener("resize", _this._resizeLoadingUI);
  5125. _this._loadingDiv = null;
  5126. };
  5127. this._loadingDiv.style.opacity = "0";
  5128. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5129. };
  5130. // FPS
  5131. Engine.prototype.getFps = function () {
  5132. return this.fps;
  5133. };
  5134. Engine.prototype.getDeltaTime = function () {
  5135. return this.deltaTime;
  5136. };
  5137. Engine.prototype._measureFps = function () {
  5138. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5139. var length = this.previousFramesDuration.length;
  5140. if (length >= 2) {
  5141. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5142. }
  5143. if (length >= this.fpsRange) {
  5144. if (length > this.fpsRange) {
  5145. this.previousFramesDuration.splice(0, 1);
  5146. length = this.previousFramesDuration.length;
  5147. }
  5148. var sum = 0;
  5149. for (var id = 0; id < length - 1; id++) {
  5150. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5151. }
  5152. this.fps = 1000.0 / (sum / (length - 1));
  5153. }
  5154. };
  5155. // Statics
  5156. Engine.isSupported = function () {
  5157. try {
  5158. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5159. if (navigator.isCocoonJS) {
  5160. return true;
  5161. }
  5162. var tempcanvas = document.createElement("canvas");
  5163. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5164. return gl != null && !!window.WebGLRenderingContext;
  5165. }
  5166. catch (e) {
  5167. return false;
  5168. }
  5169. };
  5170. // Const statics
  5171. Engine._ALPHA_DISABLE = 0;
  5172. Engine._ALPHA_ADD = 1;
  5173. Engine._ALPHA_COMBINE = 2;
  5174. Engine._DELAYLOADSTATE_NONE = 0;
  5175. Engine._DELAYLOADSTATE_LOADED = 1;
  5176. Engine._DELAYLOADSTATE_LOADING = 2;
  5177. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5178. Engine._TEXTUREFORMAT_ALPHA = 0;
  5179. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5180. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5181. Engine._TEXTUREFORMAT_RGB = 4;
  5182. Engine._TEXTUREFORMAT_RGBA = 4;
  5183. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5184. Engine._TEXTURETYPE_FLOAT = 1;
  5185. // Updatable statics so stick with vars here
  5186. Engine.Epsilon = 0.001;
  5187. Engine.CollisionsEpsilon = 0.001;
  5188. Engine.ShadersRepository = "Babylon/Shaders/";
  5189. return Engine;
  5190. })();
  5191. BABYLON.Engine = Engine;
  5192. })(BABYLON || (BABYLON = {}));
  5193. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5194. (function (BABYLON) {
  5195. /**
  5196. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5197. */
  5198. var Node = (function () {
  5199. /**
  5200. * @constructor
  5201. * @param {string} name - the name and id to be given to this node
  5202. * @param {BABYLON.Scene} the scene this node will be added to
  5203. */
  5204. function Node(name, scene) {
  5205. this.state = "";
  5206. this.animations = new Array();
  5207. this._childrenFlag = -1;
  5208. this._isEnabled = true;
  5209. this._isReady = true;
  5210. this._currentRenderId = -1;
  5211. this.name = name;
  5212. this.id = name;
  5213. this._scene = scene;
  5214. this._initCache();
  5215. }
  5216. Node.prototype.getScene = function () {
  5217. return this._scene;
  5218. };
  5219. Node.prototype.getEngine = function () {
  5220. return this._scene.getEngine();
  5221. };
  5222. // override it in derived class
  5223. Node.prototype.getWorldMatrix = function () {
  5224. return BABYLON.Matrix.Identity();
  5225. };
  5226. // override it in derived class if you add new variables to the cache
  5227. // and call the parent class method
  5228. Node.prototype._initCache = function () {
  5229. this._cache = {};
  5230. this._cache.parent = undefined;
  5231. };
  5232. Node.prototype.updateCache = function (force) {
  5233. if (!force && this.isSynchronized())
  5234. return;
  5235. this._cache.parent = this.parent;
  5236. this._updateCache();
  5237. };
  5238. // override it in derived class if you add new variables to the cache
  5239. // and call the parent class method if !ignoreParentClass
  5240. Node.prototype._updateCache = function (ignoreParentClass) {
  5241. };
  5242. // override it in derived class if you add new variables to the cache
  5243. Node.prototype._isSynchronized = function () {
  5244. return true;
  5245. };
  5246. Node.prototype.isSynchronizedWithParent = function () {
  5247. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5248. };
  5249. Node.prototype.isSynchronized = function (updateCache) {
  5250. var check = this.hasNewParent();
  5251. check = check || !this.isSynchronizedWithParent();
  5252. check = check || !this._isSynchronized();
  5253. if (updateCache)
  5254. this.updateCache(true);
  5255. return !check;
  5256. };
  5257. Node.prototype.hasNewParent = function (update) {
  5258. if (this._cache.parent === this.parent)
  5259. return false;
  5260. if (update)
  5261. this._cache.parent = this.parent;
  5262. return true;
  5263. };
  5264. /**
  5265. * Is this node ready to be used/rendered
  5266. * @return {boolean} is it ready
  5267. */
  5268. Node.prototype.isReady = function () {
  5269. return this._isReady;
  5270. };
  5271. /**
  5272. * Is this node enabled.
  5273. * If the node has a parent and is enabled, the parent will be inspected as well.
  5274. * @return {boolean} whether this node (and its parent) is enabled.
  5275. * @see setEnabled
  5276. */
  5277. Node.prototype.isEnabled = function () {
  5278. if (!this._isEnabled) {
  5279. return false;
  5280. }
  5281. if (this.parent) {
  5282. return this.parent.isEnabled();
  5283. }
  5284. return true;
  5285. };
  5286. /**
  5287. * Set the enabled state of this node.
  5288. * @param {boolean} value - the new enabled state
  5289. * @see isEnabled
  5290. */
  5291. Node.prototype.setEnabled = function (value) {
  5292. this._isEnabled = value;
  5293. };
  5294. /**
  5295. * Is this node a descendant of the given node.
  5296. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5297. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5298. * @see parent
  5299. */
  5300. Node.prototype.isDescendantOf = function (ancestor) {
  5301. if (this.parent) {
  5302. if (this.parent === ancestor) {
  5303. return true;
  5304. }
  5305. return this.parent.isDescendantOf(ancestor);
  5306. }
  5307. return false;
  5308. };
  5309. Node.prototype._getDescendants = function (list, results) {
  5310. for (var index = 0; index < list.length; index++) {
  5311. var item = list[index];
  5312. if (item.isDescendantOf(this)) {
  5313. results.push(item);
  5314. }
  5315. }
  5316. };
  5317. /**
  5318. * Will return all nodes that have this node as parent.
  5319. * @return {BABYLON.Node[]} all children nodes of all types.
  5320. */
  5321. Node.prototype.getDescendants = function () {
  5322. var results = [];
  5323. this._getDescendants(this._scene.meshes, results);
  5324. this._getDescendants(this._scene.lights, results);
  5325. this._getDescendants(this._scene.cameras, results);
  5326. return results;
  5327. };
  5328. Node.prototype._setReady = function (state) {
  5329. if (state == this._isReady) {
  5330. return;
  5331. }
  5332. if (!state) {
  5333. this._isReady = false;
  5334. return;
  5335. }
  5336. this._isReady = true;
  5337. if (this.onReady) {
  5338. this.onReady(this);
  5339. }
  5340. };
  5341. return Node;
  5342. })();
  5343. BABYLON.Node = Node;
  5344. })(BABYLON || (BABYLON = {}));
  5345. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5346. (function (BABYLON) {
  5347. var BoundingSphere = (function () {
  5348. function BoundingSphere(minimum, maximum) {
  5349. this.minimum = minimum;
  5350. this.maximum = maximum;
  5351. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5352. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5353. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5354. this.radius = distance * 0.5;
  5355. this.centerWorld = BABYLON.Vector3.Zero();
  5356. this._update(BABYLON.Matrix.Identity());
  5357. }
  5358. // Methods
  5359. BoundingSphere.prototype._update = function (world) {
  5360. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5361. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5362. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5363. };
  5364. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5365. for (var i = 0; i < 6; i++) {
  5366. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5367. return false;
  5368. }
  5369. return true;
  5370. };
  5371. BoundingSphere.prototype.intersectsPoint = function (point) {
  5372. var x = this.centerWorld.x - point.x;
  5373. var y = this.centerWorld.y - point.y;
  5374. var z = this.centerWorld.z - point.z;
  5375. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5376. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5377. return false;
  5378. return true;
  5379. };
  5380. // Statics
  5381. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5382. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5383. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5384. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5385. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5386. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5387. return false;
  5388. return true;
  5389. };
  5390. return BoundingSphere;
  5391. })();
  5392. BABYLON.BoundingSphere = BoundingSphere;
  5393. })(BABYLON || (BABYLON = {}));
  5394. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5395. (function (BABYLON) {
  5396. var BoundingBox = (function () {
  5397. function BoundingBox(minimum, maximum) {
  5398. this.minimum = minimum;
  5399. this.maximum = maximum;
  5400. this.vectors = new Array();
  5401. this.vectorsWorld = new Array();
  5402. // Bounding vectors
  5403. this.vectors.push(this.minimum.clone());
  5404. this.vectors.push(this.maximum.clone());
  5405. this.vectors.push(this.minimum.clone());
  5406. this.vectors[2].x = this.maximum.x;
  5407. this.vectors.push(this.minimum.clone());
  5408. this.vectors[3].y = this.maximum.y;
  5409. this.vectors.push(this.minimum.clone());
  5410. this.vectors[4].z = this.maximum.z;
  5411. this.vectors.push(this.maximum.clone());
  5412. this.vectors[5].z = this.minimum.z;
  5413. this.vectors.push(this.maximum.clone());
  5414. this.vectors[6].x = this.minimum.x;
  5415. this.vectors.push(this.maximum.clone());
  5416. this.vectors[7].y = this.minimum.y;
  5417. // OBB
  5418. this.center = this.maximum.add(this.minimum).scale(0.5);
  5419. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5420. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5421. for (var index = 0; index < this.vectors.length; index++) {
  5422. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5423. }
  5424. this.minimumWorld = BABYLON.Vector3.Zero();
  5425. this.maximumWorld = BABYLON.Vector3.Zero();
  5426. this._update(BABYLON.Matrix.Identity());
  5427. }
  5428. // Methods
  5429. BoundingBox.prototype.getWorldMatrix = function () {
  5430. return this._worldMatrix;
  5431. };
  5432. BoundingBox.prototype._update = function (world) {
  5433. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5434. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5435. for (var index = 0; index < this.vectors.length; index++) {
  5436. var v = this.vectorsWorld[index];
  5437. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5438. if (v.x < this.minimumWorld.x)
  5439. this.minimumWorld.x = v.x;
  5440. if (v.y < this.minimumWorld.y)
  5441. this.minimumWorld.y = v.y;
  5442. if (v.z < this.minimumWorld.z)
  5443. this.minimumWorld.z = v.z;
  5444. if (v.x > this.maximumWorld.x)
  5445. this.maximumWorld.x = v.x;
  5446. if (v.y > this.maximumWorld.y)
  5447. this.maximumWorld.y = v.y;
  5448. if (v.z > this.maximumWorld.z)
  5449. this.maximumWorld.z = v.z;
  5450. }
  5451. // OBB
  5452. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5453. this.center.scaleInPlace(0.5);
  5454. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5455. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5456. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5457. this._worldMatrix = world;
  5458. };
  5459. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5460. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5461. };
  5462. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5463. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5464. };
  5465. BoundingBox.prototype.intersectsPoint = function (point) {
  5466. var delta = BABYLON.Engine.Epsilon;
  5467. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5468. return false;
  5469. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5470. return false;
  5471. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5472. return false;
  5473. return true;
  5474. };
  5475. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5476. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5477. };
  5478. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5479. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5480. return false;
  5481. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5482. return false;
  5483. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5484. return false;
  5485. return true;
  5486. };
  5487. // Statics
  5488. BoundingBox.Intersects = function (box0, box1) {
  5489. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5490. return false;
  5491. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5492. return false;
  5493. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5494. return false;
  5495. return true;
  5496. };
  5497. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5498. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5499. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5500. return (num <= (sphereRadius * sphereRadius));
  5501. };
  5502. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5503. for (var p = 0; p < 6; p++) {
  5504. for (var i = 0; i < 8; i++) {
  5505. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5506. return false;
  5507. }
  5508. }
  5509. }
  5510. return true;
  5511. };
  5512. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5513. for (var p = 0; p < 6; p++) {
  5514. var inCount = 8;
  5515. for (var i = 0; i < 8; i++) {
  5516. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5517. --inCount;
  5518. }
  5519. else {
  5520. break;
  5521. }
  5522. }
  5523. if (inCount === 0)
  5524. return false;
  5525. }
  5526. return true;
  5527. };
  5528. return BoundingBox;
  5529. })();
  5530. BABYLON.BoundingBox = BoundingBox;
  5531. })(BABYLON || (BABYLON = {}));
  5532. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5533. (function (BABYLON) {
  5534. var computeBoxExtents = function (axis, box) {
  5535. var p = BABYLON.Vector3.Dot(box.center, axis);
  5536. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5537. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5538. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5539. var r = r0 + r1 + r2;
  5540. return {
  5541. min: p - r,
  5542. max: p + r
  5543. };
  5544. };
  5545. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5546. var axisOverlap = function (axis, box0, box1) {
  5547. var result0 = computeBoxExtents(axis, box0);
  5548. var result1 = computeBoxExtents(axis, box1);
  5549. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5550. };
  5551. var BoundingInfo = (function () {
  5552. function BoundingInfo(minimum, maximum) {
  5553. this.minimum = minimum;
  5554. this.maximum = maximum;
  5555. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5556. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5557. }
  5558. // Methods
  5559. BoundingInfo.prototype._update = function (world) {
  5560. this.boundingBox._update(world);
  5561. this.boundingSphere._update(world);
  5562. };
  5563. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5564. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5565. return false;
  5566. return this.boundingBox.isInFrustum(frustumPlanes);
  5567. };
  5568. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5569. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5570. };
  5571. BoundingInfo.prototype._checkCollision = function (collider) {
  5572. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5573. };
  5574. BoundingInfo.prototype.intersectsPoint = function (point) {
  5575. if (!this.boundingSphere.centerWorld) {
  5576. return false;
  5577. }
  5578. if (!this.boundingSphere.intersectsPoint(point)) {
  5579. return false;
  5580. }
  5581. if (!this.boundingBox.intersectsPoint(point)) {
  5582. return false;
  5583. }
  5584. return true;
  5585. };
  5586. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5587. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5588. return false;
  5589. }
  5590. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5591. return false;
  5592. }
  5593. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5594. return false;
  5595. }
  5596. if (!precise) {
  5597. return true;
  5598. }
  5599. var box0 = this.boundingBox;
  5600. var box1 = boundingInfo.boundingBox;
  5601. if (!axisOverlap(box0.directions[0], box0, box1))
  5602. return false;
  5603. if (!axisOverlap(box0.directions[1], box0, box1))
  5604. return false;
  5605. if (!axisOverlap(box0.directions[2], box0, box1))
  5606. return false;
  5607. if (!axisOverlap(box1.directions[0], box0, box1))
  5608. return false;
  5609. if (!axisOverlap(box1.directions[1], box0, box1))
  5610. return false;
  5611. if (!axisOverlap(box1.directions[2], box0, box1))
  5612. return false;
  5613. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5614. return false;
  5615. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5616. return false;
  5617. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5618. return false;
  5619. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5620. return false;
  5621. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5622. return false;
  5623. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5624. return false;
  5625. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5626. return false;
  5627. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5628. return false;
  5629. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5630. return false;
  5631. return true;
  5632. };
  5633. return BoundingInfo;
  5634. })();
  5635. BABYLON.BoundingInfo = BoundingInfo;
  5636. })(BABYLON || (BABYLON = {}));
  5637. //# sourceMappingURL=babylon.boundingInfo.js.map
  5638. var BABYLON;
  5639. (function (BABYLON) {
  5640. var Light = (function (_super) {
  5641. __extends(Light, _super);
  5642. function Light(name, scene) {
  5643. _super.call(this, name, scene);
  5644. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5645. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5646. this.intensity = 1.0;
  5647. this.range = Number.MAX_VALUE;
  5648. this.includedOnlyMeshes = new Array();
  5649. this.excludedMeshes = new Array();
  5650. this._excludedMeshesIds = new Array();
  5651. this._includedOnlyMeshesIds = new Array();
  5652. scene.lights.push(this);
  5653. }
  5654. Light.prototype.getShadowGenerator = function () {
  5655. return this._shadowGenerator;
  5656. };
  5657. Light.prototype.getAbsolutePosition = function () {
  5658. return BABYLON.Vector3.Zero();
  5659. };
  5660. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5661. };
  5662. Light.prototype._getWorldMatrix = function () {
  5663. return BABYLON.Matrix.Identity();
  5664. };
  5665. Light.prototype.canAffectMesh = function (mesh) {
  5666. if (!mesh) {
  5667. return true;
  5668. }
  5669. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5670. return false;
  5671. }
  5672. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5673. return false;
  5674. }
  5675. return true;
  5676. };
  5677. Light.prototype.getWorldMatrix = function () {
  5678. this._currentRenderId = this.getScene().getRenderId();
  5679. var worldMatrix = this._getWorldMatrix();
  5680. if (this.parent && this.parent.getWorldMatrix) {
  5681. if (!this._parentedWorldMatrix) {
  5682. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5683. }
  5684. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5685. return this._parentedWorldMatrix;
  5686. }
  5687. return worldMatrix;
  5688. };
  5689. Light.prototype.dispose = function () {
  5690. if (this._shadowGenerator) {
  5691. this._shadowGenerator.dispose();
  5692. this._shadowGenerator = null;
  5693. }
  5694. // Remove from scene
  5695. var index = this.getScene().lights.indexOf(this);
  5696. this.getScene().lights.splice(index, 1);
  5697. };
  5698. return Light;
  5699. })(BABYLON.Node);
  5700. BABYLON.Light = Light;
  5701. })(BABYLON || (BABYLON = {}));
  5702. //# sourceMappingURL=babylon.light.js.map
  5703. var BABYLON;
  5704. (function (BABYLON) {
  5705. var PointLight = (function (_super) {
  5706. __extends(PointLight, _super);
  5707. function PointLight(name, position, scene) {
  5708. _super.call(this, name, scene);
  5709. this.position = position;
  5710. }
  5711. PointLight.prototype.getAbsolutePosition = function () {
  5712. return this._transformedPosition ? this._transformedPosition : this.position;
  5713. };
  5714. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5715. if (this.parent && this.parent.getWorldMatrix) {
  5716. if (!this._transformedPosition) {
  5717. this._transformedPosition = BABYLON.Vector3.Zero();
  5718. }
  5719. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5720. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5721. return;
  5722. }
  5723. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5724. };
  5725. PointLight.prototype.getShadowGenerator = function () {
  5726. return null;
  5727. };
  5728. PointLight.prototype._getWorldMatrix = function () {
  5729. if (!this._worldMatrix) {
  5730. this._worldMatrix = BABYLON.Matrix.Identity();
  5731. }
  5732. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5733. return this._worldMatrix;
  5734. };
  5735. return PointLight;
  5736. })(BABYLON.Light);
  5737. BABYLON.PointLight = PointLight;
  5738. })(BABYLON || (BABYLON = {}));
  5739. //# sourceMappingURL=babylon.pointLight.js.map
  5740. var BABYLON;
  5741. (function (BABYLON) {
  5742. var SpotLight = (function (_super) {
  5743. __extends(SpotLight, _super);
  5744. function SpotLight(name, position, direction, angle, exponent, scene) {
  5745. _super.call(this, name, scene);
  5746. this.position = position;
  5747. this.direction = direction;
  5748. this.angle = angle;
  5749. this.exponent = exponent;
  5750. }
  5751. SpotLight.prototype.getAbsolutePosition = function () {
  5752. return this.transformedPosition ? this.transformedPosition : this.position;
  5753. };
  5754. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5755. var activeCamera = this.getScene().activeCamera;
  5756. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5757. };
  5758. SpotLight.prototype.supportsVSM = function () {
  5759. return true;
  5760. };
  5761. SpotLight.prototype.needRefreshPerFrame = function () {
  5762. return false;
  5763. };
  5764. SpotLight.prototype.setDirectionToTarget = function (target) {
  5765. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5766. return this.direction;
  5767. };
  5768. SpotLight.prototype.computeTransformedPosition = function () {
  5769. if (this.parent && this.parent.getWorldMatrix) {
  5770. if (!this.transformedPosition) {
  5771. this.transformedPosition = BABYLON.Vector3.Zero();
  5772. }
  5773. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5774. return true;
  5775. }
  5776. return false;
  5777. };
  5778. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5779. var normalizeDirection;
  5780. if (this.parent && this.parent.getWorldMatrix) {
  5781. if (!this._transformedDirection) {
  5782. this._transformedDirection = BABYLON.Vector3.Zero();
  5783. }
  5784. this.computeTransformedPosition();
  5785. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5786. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5787. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5788. }
  5789. else {
  5790. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5791. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5792. }
  5793. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5794. };
  5795. SpotLight.prototype._getWorldMatrix = function () {
  5796. if (!this._worldMatrix) {
  5797. this._worldMatrix = BABYLON.Matrix.Identity();
  5798. }
  5799. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5800. return this._worldMatrix;
  5801. };
  5802. return SpotLight;
  5803. })(BABYLON.Light);
  5804. BABYLON.SpotLight = SpotLight;
  5805. })(BABYLON || (BABYLON = {}));
  5806. //# sourceMappingURL=babylon.spotLight.js.map
  5807. var BABYLON;
  5808. (function (BABYLON) {
  5809. var DirectionalLight = (function (_super) {
  5810. __extends(DirectionalLight, _super);
  5811. function DirectionalLight(name, direction, scene) {
  5812. _super.call(this, name, scene);
  5813. this.direction = direction;
  5814. this.shadowOrthoScale = 0.1;
  5815. this.position = direction.scale(-1);
  5816. }
  5817. DirectionalLight.prototype.getAbsolutePosition = function () {
  5818. return this.transformedPosition ? this.transformedPosition : this.position;
  5819. };
  5820. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5821. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5822. return this.direction;
  5823. };
  5824. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5825. var orthoLeft = Number.MAX_VALUE;
  5826. var orthoRight = Number.MIN_VALUE;
  5827. var orthoTop = Number.MIN_VALUE;
  5828. var orthoBottom = Number.MAX_VALUE;
  5829. var tempVector3 = BABYLON.Vector3.Zero();
  5830. var activeCamera = this.getScene().activeCamera;
  5831. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5832. var mesh = renderList[meshIndex];
  5833. if (!mesh) {
  5834. continue;
  5835. }
  5836. var boundingInfo = mesh.getBoundingInfo();
  5837. if (!boundingInfo) {
  5838. continue;
  5839. }
  5840. var boundingBox = boundingInfo.boundingBox;
  5841. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5842. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5843. if (tempVector3.x < orthoLeft)
  5844. orthoLeft = tempVector3.x;
  5845. if (tempVector3.y < orthoBottom)
  5846. orthoBottom = tempVector3.y;
  5847. if (tempVector3.x > orthoRight)
  5848. orthoRight = tempVector3.x;
  5849. if (tempVector3.y > orthoTop)
  5850. orthoTop = tempVector3.y;
  5851. }
  5852. }
  5853. var xOffset = orthoRight - orthoLeft;
  5854. var yOffset = orthoTop - orthoBottom;
  5855. BABYLON.Matrix.OrthoOffCenterLHToRef(orthoLeft - xOffset * this.shadowOrthoScale, orthoRight + xOffset * this.shadowOrthoScale, orthoBottom - yOffset * this.shadowOrthoScale, orthoTop + yOffset * this.shadowOrthoScale, -activeCamera.maxZ, activeCamera.maxZ, matrix);
  5856. };
  5857. DirectionalLight.prototype.supportsVSM = function () {
  5858. return true;
  5859. };
  5860. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5861. return true;
  5862. };
  5863. DirectionalLight.prototype.computeTransformedPosition = function () {
  5864. if (this.parent && this.parent.getWorldMatrix) {
  5865. if (!this.transformedPosition) {
  5866. this.transformedPosition = BABYLON.Vector3.Zero();
  5867. }
  5868. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5869. return true;
  5870. }
  5871. return false;
  5872. };
  5873. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5874. if (this.parent && this.parent.getWorldMatrix) {
  5875. if (!this._transformedDirection) {
  5876. this._transformedDirection = BABYLON.Vector3.Zero();
  5877. }
  5878. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5879. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5880. return;
  5881. }
  5882. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5883. };
  5884. DirectionalLight.prototype._getWorldMatrix = function () {
  5885. if (!this._worldMatrix) {
  5886. this._worldMatrix = BABYLON.Matrix.Identity();
  5887. }
  5888. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5889. return this._worldMatrix;
  5890. };
  5891. return DirectionalLight;
  5892. })(BABYLON.Light);
  5893. BABYLON.DirectionalLight = DirectionalLight;
  5894. })(BABYLON || (BABYLON = {}));
  5895. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5896. (function (BABYLON) {
  5897. var ShadowGenerator = (function () {
  5898. function ShadowGenerator(mapSize, light) {
  5899. var _this = this;
  5900. // Members
  5901. this.filter = ShadowGenerator.FILTER_NONE;
  5902. this.blurScale = 2;
  5903. this._blurBoxOffset = 0;
  5904. this._bias = 0.00005;
  5905. this._darkness = 0;
  5906. this._transparencyShadow = false;
  5907. this._viewMatrix = BABYLON.Matrix.Zero();
  5908. this._projectionMatrix = BABYLON.Matrix.Zero();
  5909. this._transformMatrix = BABYLON.Matrix.Zero();
  5910. this._worldViewProjection = BABYLON.Matrix.Zero();
  5911. this._light = light;
  5912. this._scene = light.getScene();
  5913. this._mapSize = mapSize;
  5914. light._shadowGenerator = this;
  5915. // Render target
  5916. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5917. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5918. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5919. this._shadowMap.renderParticles = false;
  5920. this._shadowMap.onAfterUnbind = function () {
  5921. if (!_this.useBlurVarianceShadowMap) {
  5922. return;
  5923. }
  5924. if (!_this._shadowMap2) {
  5925. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false);
  5926. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5927. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5928. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, _this._scene.getEngine());
  5929. _this._downSamplePostprocess.onApply = function (effect) {
  5930. effect.setTexture("textureSampler", _this._shadowMap);
  5931. };
  5932. _this.blurBoxOffset = 1;
  5933. }
  5934. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  5935. };
  5936. // Custom render function
  5937. var renderSubMesh = function (subMesh) {
  5938. var mesh = subMesh.getRenderingMesh();
  5939. var scene = _this._scene;
  5940. var engine = scene.getEngine();
  5941. // Culling
  5942. engine.setState(subMesh.getMaterial().backFaceCulling);
  5943. // Managing instances
  5944. var batch = mesh._getInstancesRenderList(subMesh._id);
  5945. if (batch.mustReturn) {
  5946. return;
  5947. }
  5948. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5949. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5950. engine.enableEffect(_this._effect);
  5951. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5952. var material = subMesh.getMaterial();
  5953. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5954. // Alpha test
  5955. if (material && material.needAlphaTesting()) {
  5956. var alphaTexture = material.getAlphaTestTexture();
  5957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5959. }
  5960. // Bones
  5961. if (mesh.useBones) {
  5962. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5963. }
  5964. // Draw
  5965. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5966. }
  5967. else {
  5968. // Need to reset refresh rate of the shadowMap
  5969. _this._shadowMap.resetRefreshCounter();
  5970. }
  5971. };
  5972. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5973. var index;
  5974. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5975. renderSubMesh(opaqueSubMeshes.data[index]);
  5976. }
  5977. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5978. renderSubMesh(alphaTestSubMeshes.data[index]);
  5979. }
  5980. if (_this._transparencyShadow) {
  5981. for (index = 0; index < transparentSubMeshes.length; index++) {
  5982. renderSubMesh(transparentSubMeshes.data[index]);
  5983. }
  5984. }
  5985. };
  5986. this._shadowMap.onClear = function (engine) {
  5987. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  5988. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true);
  5989. }
  5990. else {
  5991. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true);
  5992. }
  5993. };
  5994. }
  5995. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5996. // Static
  5997. get: function () {
  5998. return ShadowGenerator._FILTER_NONE;
  5999. },
  6000. enumerable: true,
  6001. configurable: true
  6002. });
  6003. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  6004. get: function () {
  6005. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  6006. },
  6007. enumerable: true,
  6008. configurable: true
  6009. });
  6010. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  6011. get: function () {
  6012. return ShadowGenerator._FILTER_POISSONSAMPLING;
  6013. },
  6014. enumerable: true,
  6015. configurable: true
  6016. });
  6017. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  6018. get: function () {
  6019. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  6020. },
  6021. enumerable: true,
  6022. configurable: true
  6023. });
  6024. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  6025. get: function () {
  6026. return this._bias;
  6027. },
  6028. set: function (bias) {
  6029. this._bias = bias;
  6030. },
  6031. enumerable: true,
  6032. configurable: true
  6033. });
  6034. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  6035. get: function () {
  6036. return this._blurBoxOffset;
  6037. },
  6038. set: function (value) {
  6039. var _this = this;
  6040. if (this._blurBoxOffset === value) {
  6041. return;
  6042. }
  6043. this._blurBoxOffset = value;
  6044. if (this._boxBlurPostprocess) {
  6045. this._boxBlurPostprocess.dispose();
  6046. }
  6047. 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);
  6048. this._boxBlurPostprocess.onApply = function (effect) {
  6049. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  6050. };
  6051. },
  6052. enumerable: true,
  6053. configurable: true
  6054. });
  6055. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  6056. get: function () {
  6057. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  6058. },
  6059. set: function (value) {
  6060. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  6066. get: function () {
  6067. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP || this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  6068. },
  6069. set: function (value) {
  6070. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  6071. },
  6072. enumerable: true,
  6073. configurable: true
  6074. });
  6075. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  6076. get: function () {
  6077. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  6078. },
  6079. set: function (value) {
  6080. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  6081. },
  6082. enumerable: true,
  6083. configurable: true
  6084. });
  6085. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  6086. var defines = [];
  6087. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  6088. defines.push("#define VSM");
  6089. }
  6090. var attribs = [BABYLON.VertexBuffer.PositionKind];
  6091. var mesh = subMesh.getMesh();
  6092. var material = subMesh.getMaterial();
  6093. // Alpha test
  6094. if (material && material.needAlphaTesting()) {
  6095. defines.push("#define ALPHATEST");
  6096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  6097. attribs.push(BABYLON.VertexBuffer.UVKind);
  6098. defines.push("#define UV1");
  6099. }
  6100. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  6101. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  6102. defines.push("#define UV2");
  6103. }
  6104. }
  6105. // Bones
  6106. if (mesh.useBones) {
  6107. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  6108. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  6109. defines.push("#define BONES");
  6110. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  6111. }
  6112. // Instances
  6113. if (useInstances) {
  6114. defines.push("#define INSTANCES");
  6115. attribs.push("world0");
  6116. attribs.push("world1");
  6117. attribs.push("world2");
  6118. attribs.push("world3");
  6119. }
  6120. // Get correct effect
  6121. var join = defines.join("\n");
  6122. if (this._cachedDefines !== join) {
  6123. this._cachedDefines = join;
  6124. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  6125. }
  6126. return this._effect.isReady();
  6127. };
  6128. ShadowGenerator.prototype.getShadowMap = function () {
  6129. return this._shadowMap;
  6130. };
  6131. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  6132. if (this._shadowMap2) {
  6133. return this._shadowMap2;
  6134. }
  6135. return this._shadowMap;
  6136. };
  6137. ShadowGenerator.prototype.getLight = function () {
  6138. return this._light;
  6139. };
  6140. // Methods
  6141. ShadowGenerator.prototype.getTransformMatrix = function () {
  6142. var scene = this._scene;
  6143. if (this._currentRenderID === scene.getRenderId()) {
  6144. return this._transformMatrix;
  6145. }
  6146. this._currentRenderID = scene.getRenderId();
  6147. var lightPosition = this._light.position;
  6148. var lightDirection = this._light.direction;
  6149. if (this._light.computeTransformedPosition()) {
  6150. lightPosition = this._light.transformedPosition;
  6151. }
  6152. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6153. this._cachedPosition = lightPosition.clone();
  6154. this._cachedDirection = lightDirection.clone();
  6155. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6156. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6157. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6158. }
  6159. return this._transformMatrix;
  6160. };
  6161. ShadowGenerator.prototype.getDarkness = function () {
  6162. return this._darkness;
  6163. };
  6164. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6165. if (darkness >= 1.0)
  6166. this._darkness = 1.0;
  6167. else if (darkness <= 0.0)
  6168. this._darkness = 0.0;
  6169. else
  6170. this._darkness = darkness;
  6171. };
  6172. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6173. this._transparencyShadow = hasShadow;
  6174. };
  6175. ShadowGenerator.prototype._packHalf = function (depth) {
  6176. var scale = depth * 255.0;
  6177. var fract = scale - Math.floor(scale);
  6178. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  6179. };
  6180. ShadowGenerator.prototype.dispose = function () {
  6181. this._shadowMap.dispose();
  6182. if (this._shadowMap2) {
  6183. this._shadowMap2.dispose();
  6184. }
  6185. if (this._downSamplePostprocess) {
  6186. this._downSamplePostprocess.dispose();
  6187. }
  6188. if (this._boxBlurPostprocess) {
  6189. this._boxBlurPostprocess.dispose();
  6190. }
  6191. };
  6192. ShadowGenerator._FILTER_NONE = 0;
  6193. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6194. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6195. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  6196. return ShadowGenerator;
  6197. })();
  6198. BABYLON.ShadowGenerator = ShadowGenerator;
  6199. })(BABYLON || (BABYLON = {}));
  6200. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6201. var BABYLON;
  6202. (function (BABYLON) {
  6203. var HemisphericLight = (function (_super) {
  6204. __extends(HemisphericLight, _super);
  6205. function HemisphericLight(name, direction, scene) {
  6206. _super.call(this, name, scene);
  6207. this.direction = direction;
  6208. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6209. }
  6210. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6211. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6212. return this.direction;
  6213. };
  6214. HemisphericLight.prototype.getShadowGenerator = function () {
  6215. return null;
  6216. };
  6217. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6218. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6219. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6220. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6221. };
  6222. HemisphericLight.prototype._getWorldMatrix = function () {
  6223. if (!this._worldMatrix) {
  6224. this._worldMatrix = BABYLON.Matrix.Identity();
  6225. }
  6226. return this._worldMatrix;
  6227. };
  6228. return HemisphericLight;
  6229. })(BABYLON.Light);
  6230. BABYLON.HemisphericLight = HemisphericLight;
  6231. })(BABYLON || (BABYLON = {}));
  6232. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6233. (function (BABYLON) {
  6234. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6235. if (boxMin.x > sphereCenter.x + sphereRadius)
  6236. return false;
  6237. if (sphereCenter.x - sphereRadius > boxMax.x)
  6238. return false;
  6239. if (boxMin.y > sphereCenter.y + sphereRadius)
  6240. return false;
  6241. if (sphereCenter.y - sphereRadius > boxMax.y)
  6242. return false;
  6243. if (boxMin.z > sphereCenter.z + sphereRadius)
  6244. return false;
  6245. if (sphereCenter.z - sphereRadius > boxMax.z)
  6246. return false;
  6247. return true;
  6248. };
  6249. var getLowestRoot = function (a, b, c, maxR) {
  6250. var determinant = b * b - 4.0 * a * c;
  6251. var result = { root: 0, found: false };
  6252. if (determinant < 0)
  6253. return result;
  6254. var sqrtD = Math.sqrt(determinant);
  6255. var r1 = (-b - sqrtD) / (2.0 * a);
  6256. var r2 = (-b + sqrtD) / (2.0 * a);
  6257. if (r1 > r2) {
  6258. var temp = r2;
  6259. r2 = r1;
  6260. r1 = temp;
  6261. }
  6262. if (r1 > 0 && r1 < maxR) {
  6263. result.root = r1;
  6264. result.found = true;
  6265. return result;
  6266. }
  6267. if (r2 > 0 && r2 < maxR) {
  6268. result.root = r2;
  6269. result.found = true;
  6270. return result;
  6271. }
  6272. return result;
  6273. };
  6274. var Collider = (function () {
  6275. function Collider() {
  6276. this.radius = new BABYLON.Vector3(1, 1, 1);
  6277. this.retry = 0;
  6278. this.basePointWorld = BABYLON.Vector3.Zero();
  6279. this.velocityWorld = BABYLON.Vector3.Zero();
  6280. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6281. this._collisionPoint = BABYLON.Vector3.Zero();
  6282. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6283. this._tempVector = BABYLON.Vector3.Zero();
  6284. this._tempVector2 = BABYLON.Vector3.Zero();
  6285. this._tempVector3 = BABYLON.Vector3.Zero();
  6286. this._tempVector4 = BABYLON.Vector3.Zero();
  6287. this._edge = BABYLON.Vector3.Zero();
  6288. this._baseToVertex = BABYLON.Vector3.Zero();
  6289. this._destinationPoint = BABYLON.Vector3.Zero();
  6290. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6291. this._displacementVector = BABYLON.Vector3.Zero();
  6292. }
  6293. // Methods
  6294. Collider.prototype._initialize = function (source, dir, e) {
  6295. this.velocity = dir;
  6296. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6297. this.basePoint = source;
  6298. source.multiplyToRef(this.radius, this.basePointWorld);
  6299. dir.multiplyToRef(this.radius, this.velocityWorld);
  6300. this.velocityWorldLength = this.velocityWorld.length();
  6301. this.epsilon = e;
  6302. this.collisionFound = false;
  6303. };
  6304. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6305. pa.subtractToRef(point, this._tempVector);
  6306. pb.subtractToRef(point, this._tempVector2);
  6307. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6308. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6309. if (d < 0)
  6310. return false;
  6311. pc.subtractToRef(point, this._tempVector3);
  6312. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6313. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6314. if (d < 0)
  6315. return false;
  6316. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6317. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6318. return d >= 0;
  6319. };
  6320. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6321. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6322. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6323. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6324. return false;
  6325. }
  6326. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6327. return false;
  6328. return true;
  6329. };
  6330. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6331. var t0;
  6332. var embeddedInPlane = false;
  6333. if (!subMesh._trianglePlanes) {
  6334. subMesh._trianglePlanes = [];
  6335. }
  6336. if (!subMesh._trianglePlanes[faceIndex]) {
  6337. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6338. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6339. }
  6340. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6341. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6342. return;
  6343. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6344. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6345. if (normalDotVelocity == 0) {
  6346. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6347. return;
  6348. embeddedInPlane = true;
  6349. t0 = 0;
  6350. }
  6351. else {
  6352. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6353. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6354. if (t0 > t1) {
  6355. var temp = t1;
  6356. t1 = t0;
  6357. t0 = temp;
  6358. }
  6359. if (t0 > 1.0 || t1 < 0.0)
  6360. return;
  6361. if (t0 < 0)
  6362. t0 = 0;
  6363. if (t0 > 1.0)
  6364. t0 = 1.0;
  6365. }
  6366. this._collisionPoint.copyFromFloats(0, 0, 0);
  6367. var found = false;
  6368. var t = 1.0;
  6369. if (!embeddedInPlane) {
  6370. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6371. this.velocity.scaleToRef(t0, this._tempVector);
  6372. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6373. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6374. found = true;
  6375. t = t0;
  6376. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6377. }
  6378. }
  6379. if (!found) {
  6380. var velocitySquaredLength = this.velocity.lengthSquared();
  6381. var a = velocitySquaredLength;
  6382. this.basePoint.subtractToRef(p1, this._tempVector);
  6383. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6384. var c = this._tempVector.lengthSquared() - 1.0;
  6385. var lowestRoot = getLowestRoot(a, b, c, t);
  6386. if (lowestRoot.found) {
  6387. t = lowestRoot.root;
  6388. found = true;
  6389. this._collisionPoint.copyFrom(p1);
  6390. }
  6391. this.basePoint.subtractToRef(p2, this._tempVector);
  6392. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6393. c = this._tempVector.lengthSquared() - 1.0;
  6394. lowestRoot = getLowestRoot(a, b, c, t);
  6395. if (lowestRoot.found) {
  6396. t = lowestRoot.root;
  6397. found = true;
  6398. this._collisionPoint.copyFrom(p2);
  6399. }
  6400. this.basePoint.subtractToRef(p3, this._tempVector);
  6401. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6402. c = this._tempVector.lengthSquared() - 1.0;
  6403. lowestRoot = getLowestRoot(a, b, c, t);
  6404. if (lowestRoot.found) {
  6405. t = lowestRoot.root;
  6406. found = true;
  6407. this._collisionPoint.copyFrom(p3);
  6408. }
  6409. p2.subtractToRef(p1, this._edge);
  6410. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6411. var edgeSquaredLength = this._edge.lengthSquared();
  6412. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6413. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6414. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6415. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6416. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6417. lowestRoot = getLowestRoot(a, b, c, t);
  6418. if (lowestRoot.found) {
  6419. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6420. if (f >= 0.0 && f <= 1.0) {
  6421. t = lowestRoot.root;
  6422. found = true;
  6423. this._edge.scaleInPlace(f);
  6424. p1.addToRef(this._edge, this._collisionPoint);
  6425. }
  6426. }
  6427. p3.subtractToRef(p2, this._edge);
  6428. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6429. edgeSquaredLength = this._edge.lengthSquared();
  6430. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6431. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6432. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6433. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6434. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6435. lowestRoot = getLowestRoot(a, b, c, t);
  6436. if (lowestRoot.found) {
  6437. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6438. if (f >= 0.0 && f <= 1.0) {
  6439. t = lowestRoot.root;
  6440. found = true;
  6441. this._edge.scaleInPlace(f);
  6442. p2.addToRef(this._edge, this._collisionPoint);
  6443. }
  6444. }
  6445. p1.subtractToRef(p3, this._edge);
  6446. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6447. edgeSquaredLength = this._edge.lengthSquared();
  6448. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6449. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6450. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6451. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6452. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6453. lowestRoot = getLowestRoot(a, b, c, t);
  6454. if (lowestRoot.found) {
  6455. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6456. if (f >= 0.0 && f <= 1.0) {
  6457. t = lowestRoot.root;
  6458. found = true;
  6459. this._edge.scaleInPlace(f);
  6460. p3.addToRef(this._edge, this._collisionPoint);
  6461. }
  6462. }
  6463. }
  6464. if (found) {
  6465. var distToCollision = t * this.velocity.length();
  6466. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6467. if (!this.intersectionPoint) {
  6468. this.intersectionPoint = this._collisionPoint.clone();
  6469. }
  6470. else {
  6471. this.intersectionPoint.copyFrom(this._collisionPoint);
  6472. }
  6473. this.nearestDistance = distToCollision;
  6474. this.collisionFound = true;
  6475. this.collidedMesh = subMesh.getMesh();
  6476. }
  6477. }
  6478. };
  6479. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6480. for (var i = indexStart; i < indexEnd; i += 3) {
  6481. var p1 = pts[indices[i] - decal];
  6482. var p2 = pts[indices[i + 1] - decal];
  6483. var p3 = pts[indices[i + 2] - decal];
  6484. this._testTriangle(i, subMesh, p3, p2, p1);
  6485. }
  6486. };
  6487. Collider.prototype._getResponse = function (pos, vel) {
  6488. pos.addToRef(vel, this._destinationPoint);
  6489. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6490. this.basePoint.addToRef(vel, pos);
  6491. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6492. this._slidePlaneNormal.normalize();
  6493. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6494. pos.addInPlace(this._displacementVector);
  6495. this.intersectionPoint.addInPlace(this._displacementVector);
  6496. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6497. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6498. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6499. };
  6500. return Collider;
  6501. })();
  6502. BABYLON.Collider = Collider;
  6503. })(BABYLON || (BABYLON = {}));
  6504. //# sourceMappingURL=babylon.collider.js.map
  6505. var BABYLON;
  6506. (function (BABYLON) {
  6507. var Camera = (function (_super) {
  6508. __extends(Camera, _super);
  6509. function Camera(name, position, scene) {
  6510. _super.call(this, name, scene);
  6511. this.position = position;
  6512. // Members
  6513. this.upVector = BABYLON.Vector3.Up();
  6514. this.orthoLeft = null;
  6515. this.orthoRight = null;
  6516. this.orthoBottom = null;
  6517. this.orthoTop = null;
  6518. this.fov = 0.8;
  6519. this.minZ = 1.0;
  6520. this.maxZ = 10000.0;
  6521. this.inertia = 0.9;
  6522. this.mode = Camera.PERSPECTIVE_CAMERA;
  6523. this.isIntermediate = false;
  6524. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6525. this.subCameras = [];
  6526. this.layerMask = 0xFFFFFFFF;
  6527. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6528. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6529. this._projectionMatrix = new BABYLON.Matrix();
  6530. this._postProcesses = new Array();
  6531. this._postProcessesTakenIndices = [];
  6532. this._activeMeshes = new BABYLON.SmartArray(256);
  6533. scene.cameras.push(this);
  6534. if (!scene.activeCamera) {
  6535. scene.activeCamera = this;
  6536. }
  6537. }
  6538. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6539. get: function () {
  6540. return Camera._PERSPECTIVE_CAMERA;
  6541. },
  6542. enumerable: true,
  6543. configurable: true
  6544. });
  6545. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6546. get: function () {
  6547. return Camera._ORTHOGRAPHIC_CAMERA;
  6548. },
  6549. enumerable: true,
  6550. configurable: true
  6551. });
  6552. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6553. get: function () {
  6554. return Camera._FOVMODE_VERTICAL_FIXED;
  6555. },
  6556. enumerable: true,
  6557. configurable: true
  6558. });
  6559. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6560. get: function () {
  6561. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6562. },
  6563. enumerable: true,
  6564. configurable: true
  6565. });
  6566. Camera.prototype.getActiveMeshes = function () {
  6567. return this._activeMeshes;
  6568. };
  6569. Camera.prototype.isActiveMesh = function (mesh) {
  6570. return (this._activeMeshes.indexOf(mesh) !== -1);
  6571. };
  6572. //Cache
  6573. Camera.prototype._initCache = function () {
  6574. _super.prototype._initCache.call(this);
  6575. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6576. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6577. this._cache.mode = undefined;
  6578. this._cache.minZ = undefined;
  6579. this._cache.maxZ = undefined;
  6580. this._cache.fov = undefined;
  6581. this._cache.aspectRatio = undefined;
  6582. this._cache.orthoLeft = undefined;
  6583. this._cache.orthoRight = undefined;
  6584. this._cache.orthoBottom = undefined;
  6585. this._cache.orthoTop = undefined;
  6586. this._cache.renderWidth = undefined;
  6587. this._cache.renderHeight = undefined;
  6588. };
  6589. Camera.prototype._updateCache = function (ignoreParentClass) {
  6590. if (!ignoreParentClass) {
  6591. _super.prototype._updateCache.call(this);
  6592. }
  6593. var engine = this.getEngine();
  6594. this._cache.position.copyFrom(this.position);
  6595. this._cache.upVector.copyFrom(this.upVector);
  6596. this._cache.mode = this.mode;
  6597. this._cache.minZ = this.minZ;
  6598. this._cache.maxZ = this.maxZ;
  6599. this._cache.fov = this.fov;
  6600. this._cache.aspectRatio = engine.getAspectRatio(this);
  6601. this._cache.orthoLeft = this.orthoLeft;
  6602. this._cache.orthoRight = this.orthoRight;
  6603. this._cache.orthoBottom = this.orthoBottom;
  6604. this._cache.orthoTop = this.orthoTop;
  6605. this._cache.renderWidth = engine.getRenderWidth();
  6606. this._cache.renderHeight = engine.getRenderHeight();
  6607. };
  6608. Camera.prototype._updateFromScene = function () {
  6609. this.updateCache();
  6610. this._update();
  6611. };
  6612. // Synchronized
  6613. Camera.prototype._isSynchronized = function () {
  6614. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6615. };
  6616. Camera.prototype._isSynchronizedViewMatrix = function () {
  6617. if (!_super.prototype._isSynchronized.call(this))
  6618. return false;
  6619. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6620. };
  6621. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6622. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6623. if (!check) {
  6624. return false;
  6625. }
  6626. var engine = this.getEngine();
  6627. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6628. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6629. }
  6630. else {
  6631. 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();
  6632. }
  6633. return check;
  6634. };
  6635. // Controls
  6636. Camera.prototype.attachControl = function (element) {
  6637. };
  6638. Camera.prototype.detachControl = function (element) {
  6639. };
  6640. Camera.prototype._update = function () {
  6641. };
  6642. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6643. if (insertAt === void 0) { insertAt = null; }
  6644. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6645. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6646. return 0;
  6647. }
  6648. if (insertAt == null || insertAt < 0) {
  6649. this._postProcesses.push(postProcess);
  6650. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6651. return this._postProcesses.length - 1;
  6652. }
  6653. var add = 0;
  6654. if (this._postProcesses[insertAt]) {
  6655. var start = this._postProcesses.length - 1;
  6656. for (var i = start; i >= insertAt + 1; --i) {
  6657. this._postProcesses[i + 1] = this._postProcesses[i];
  6658. }
  6659. add = 1;
  6660. }
  6661. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6662. if (this._postProcessesTakenIndices[i] < insertAt) {
  6663. continue;
  6664. }
  6665. start = this._postProcessesTakenIndices.length - 1;
  6666. for (var j = start; j >= i; --j) {
  6667. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6668. }
  6669. this._postProcessesTakenIndices[i] = insertAt;
  6670. break;
  6671. }
  6672. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6673. this._postProcessesTakenIndices.push(insertAt);
  6674. }
  6675. var result = insertAt + add;
  6676. this._postProcesses[result] = postProcess;
  6677. return result;
  6678. };
  6679. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6680. if (atIndices === void 0) { atIndices = null; }
  6681. var result = [];
  6682. if (!atIndices) {
  6683. var length = this._postProcesses.length;
  6684. for (var i = 0; i < length; i++) {
  6685. if (this._postProcesses[i] !== postProcess) {
  6686. continue;
  6687. }
  6688. delete this._postProcesses[i];
  6689. var index = this._postProcessesTakenIndices.indexOf(i);
  6690. this._postProcessesTakenIndices.splice(index, 1);
  6691. }
  6692. }
  6693. else {
  6694. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6695. for (i = 0; i < atIndices.length; i++) {
  6696. var foundPostProcess = this._postProcesses[atIndices[i]];
  6697. if (foundPostProcess !== postProcess) {
  6698. result.push(i);
  6699. continue;
  6700. }
  6701. delete this._postProcesses[atIndices[i]];
  6702. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6703. this._postProcessesTakenIndices.splice(index, 1);
  6704. }
  6705. }
  6706. return result;
  6707. };
  6708. Camera.prototype.getWorldMatrix = function () {
  6709. if (!this._worldMatrix) {
  6710. this._worldMatrix = BABYLON.Matrix.Identity();
  6711. }
  6712. var viewMatrix = this.getViewMatrix();
  6713. viewMatrix.invertToRef(this._worldMatrix);
  6714. return this._worldMatrix;
  6715. };
  6716. Camera.prototype._getViewMatrix = function () {
  6717. return BABYLON.Matrix.Identity();
  6718. };
  6719. Camera.prototype.getViewMatrix = function () {
  6720. this._computedViewMatrix = this._computeViewMatrix();
  6721. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6722. return this._computedViewMatrix;
  6723. }
  6724. if (!this._worldMatrix) {
  6725. this._worldMatrix = BABYLON.Matrix.Identity();
  6726. }
  6727. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6728. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6729. this._computedViewMatrix.invert();
  6730. this._currentRenderId = this.getScene().getRenderId();
  6731. return this._computedViewMatrix;
  6732. };
  6733. Camera.prototype._computeViewMatrix = function (force) {
  6734. if (!force && this._isSynchronizedViewMatrix()) {
  6735. return this._computedViewMatrix;
  6736. }
  6737. this._computedViewMatrix = this._getViewMatrix();
  6738. if (!this.parent || !this.parent.getWorldMatrix) {
  6739. this._currentRenderId = this.getScene().getRenderId();
  6740. }
  6741. return this._computedViewMatrix;
  6742. };
  6743. Camera.prototype.getProjectionMatrix = function (force) {
  6744. if (!force && this._isSynchronizedProjectionMatrix()) {
  6745. return this._projectionMatrix;
  6746. }
  6747. var engine = this.getEngine();
  6748. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6749. if (this.minZ <= 0) {
  6750. this.minZ = 0.1;
  6751. }
  6752. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6753. return this._projectionMatrix;
  6754. }
  6755. var halfWidth = engine.getRenderWidth() / 2.0;
  6756. var halfHeight = engine.getRenderHeight() / 2.0;
  6757. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6758. return this._projectionMatrix;
  6759. };
  6760. Camera.prototype.dispose = function () {
  6761. // Remove from scene
  6762. var index = this.getScene().cameras.indexOf(this);
  6763. this.getScene().cameras.splice(index, 1);
  6764. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6765. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6766. }
  6767. };
  6768. // Statics
  6769. Camera._PERSPECTIVE_CAMERA = 0;
  6770. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6771. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6772. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6773. return Camera;
  6774. })(BABYLON.Node);
  6775. BABYLON.Camera = Camera;
  6776. })(BABYLON || (BABYLON = {}));
  6777. //# sourceMappingURL=babylon.camera.js.map
  6778. var BABYLON;
  6779. (function (BABYLON) {
  6780. var TargetCamera = (function (_super) {
  6781. __extends(TargetCamera, _super);
  6782. function TargetCamera(name, position, scene) {
  6783. _super.call(this, name, position, scene);
  6784. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6785. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6786. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6787. this.speed = 2.0;
  6788. this.noRotationConstraint = false;
  6789. this.lockedTarget = null;
  6790. this._currentTarget = BABYLON.Vector3.Zero();
  6791. this._viewMatrix = BABYLON.Matrix.Zero();
  6792. this._camMatrix = BABYLON.Matrix.Zero();
  6793. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6794. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6795. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6796. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6797. this._lookAtTemp = BABYLON.Matrix.Zero();
  6798. this._tempMatrix = BABYLON.Matrix.Zero();
  6799. }
  6800. TargetCamera.prototype._getLockedTargetPosition = function () {
  6801. if (!this.lockedTarget) {
  6802. return null;
  6803. }
  6804. return this.lockedTarget.position || this.lockedTarget;
  6805. };
  6806. // Cache
  6807. TargetCamera.prototype._initCache = function () {
  6808. _super.prototype._initCache.call(this);
  6809. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6810. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6811. };
  6812. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6813. if (!ignoreParentClass) {
  6814. _super.prototype._updateCache.call(this);
  6815. }
  6816. var lockedTargetPosition = this._getLockedTargetPosition();
  6817. if (!lockedTargetPosition) {
  6818. this._cache.lockedTarget = null;
  6819. }
  6820. else {
  6821. if (!this._cache.lockedTarget) {
  6822. this._cache.lockedTarget = lockedTargetPosition.clone();
  6823. }
  6824. else {
  6825. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6826. }
  6827. }
  6828. this._cache.rotation.copyFrom(this.rotation);
  6829. };
  6830. // Synchronized
  6831. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6832. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6833. return false;
  6834. }
  6835. var lockedTargetPosition = this._getLockedTargetPosition();
  6836. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6837. };
  6838. // Methods
  6839. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6840. var engine = this.getEngine();
  6841. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6842. };
  6843. // Target
  6844. TargetCamera.prototype.setTarget = function (target) {
  6845. this.upVector.normalize();
  6846. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6847. this._camMatrix.invert();
  6848. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6849. var vDir = target.subtract(this.position);
  6850. if (vDir.x >= 0.0) {
  6851. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6852. }
  6853. else {
  6854. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6855. }
  6856. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6857. if (isNaN(this.rotation.x)) {
  6858. this.rotation.x = 0;
  6859. }
  6860. if (isNaN(this.rotation.y)) {
  6861. this.rotation.y = 0;
  6862. }
  6863. if (isNaN(this.rotation.z)) {
  6864. this.rotation.z = 0;
  6865. }
  6866. };
  6867. TargetCamera.prototype.getTarget = function () {
  6868. return this._currentTarget;
  6869. };
  6870. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6871. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6872. };
  6873. TargetCamera.prototype._updatePosition = function () {
  6874. this.position.addInPlace(this.cameraDirection);
  6875. };
  6876. TargetCamera.prototype._update = function () {
  6877. var needToMove = this._decideIfNeedsToMove();
  6878. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6879. // Move
  6880. if (needToMove) {
  6881. this._updatePosition();
  6882. }
  6883. // Rotate
  6884. if (needToRotate) {
  6885. this.rotation.x += this.cameraRotation.x;
  6886. this.rotation.y += this.cameraRotation.y;
  6887. if (!this.noRotationConstraint) {
  6888. var limit = (Math.PI / 2) * 0.95;
  6889. if (this.rotation.x > limit)
  6890. this.rotation.x = limit;
  6891. if (this.rotation.x < -limit)
  6892. this.rotation.x = -limit;
  6893. }
  6894. }
  6895. // Inertia
  6896. if (needToMove) {
  6897. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6898. this.cameraDirection.x = 0;
  6899. }
  6900. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6901. this.cameraDirection.y = 0;
  6902. }
  6903. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6904. this.cameraDirection.z = 0;
  6905. }
  6906. this.cameraDirection.scaleInPlace(this.inertia);
  6907. }
  6908. if (needToRotate) {
  6909. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6910. this.cameraRotation.x = 0;
  6911. }
  6912. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6913. this.cameraRotation.y = 0;
  6914. }
  6915. this.cameraRotation.scaleInPlace(this.inertia);
  6916. }
  6917. };
  6918. TargetCamera.prototype._getViewMatrix = function () {
  6919. if (!this.lockedTarget) {
  6920. // Compute
  6921. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6922. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6923. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6924. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6925. this._lookAtTemp.invert();
  6926. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6927. }
  6928. else {
  6929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6930. }
  6931. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6932. // Computing target and final matrix
  6933. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6934. }
  6935. else {
  6936. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6937. }
  6938. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6939. return this._viewMatrix;
  6940. };
  6941. return TargetCamera;
  6942. })(BABYLON.Camera);
  6943. BABYLON.TargetCamera = TargetCamera;
  6944. })(BABYLON || (BABYLON = {}));
  6945. //# sourceMappingURL=babylon.targetCamera.js.map
  6946. var BABYLON;
  6947. (function (BABYLON) {
  6948. var FollowCamera = (function (_super) {
  6949. __extends(FollowCamera, _super);
  6950. function FollowCamera(name, position, scene) {
  6951. _super.call(this, name, position, scene);
  6952. this.radius = 12;
  6953. this.rotationOffset = 0;
  6954. this.heightOffset = 4;
  6955. this.cameraAcceleration = 0.05;
  6956. this.maxCameraSpeed = 20;
  6957. }
  6958. FollowCamera.prototype.getRadians = function (degrees) {
  6959. return degrees * Math.PI / 180;
  6960. };
  6961. FollowCamera.prototype.follow = function (cameraTarget) {
  6962. if (!cameraTarget)
  6963. return;
  6964. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6965. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6966. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6967. var dx = targetX - this.position.x;
  6968. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6969. var dz = (targetZ) - this.position.z;
  6970. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6971. var vy = dy * this.cameraAcceleration;
  6972. var vz = dz * this.cameraAcceleration * 2;
  6973. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6974. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6975. }
  6976. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6977. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6978. }
  6979. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6980. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6981. }
  6982. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6983. this.setTarget(cameraTarget.position);
  6984. };
  6985. FollowCamera.prototype._update = function () {
  6986. _super.prototype._update.call(this);
  6987. this.follow(this.target);
  6988. };
  6989. return FollowCamera;
  6990. })(BABYLON.TargetCamera);
  6991. BABYLON.FollowCamera = FollowCamera;
  6992. })(BABYLON || (BABYLON = {}));
  6993. //# sourceMappingURL=babylon.followCamera.js.map
  6994. var BABYLON;
  6995. (function (BABYLON) {
  6996. var FreeCamera = (function (_super) {
  6997. __extends(FreeCamera, _super);
  6998. function FreeCamera(name, position, scene) {
  6999. _super.call(this, name, position, scene);
  7000. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  7001. this.keysUp = [38];
  7002. this.keysDown = [40];
  7003. this.keysLeft = [37];
  7004. this.keysRight = [39];
  7005. this.checkCollisions = false;
  7006. this.applyGravity = false;
  7007. this.angularSensibility = 2000.0;
  7008. this._keys = [];
  7009. this._collider = new BABYLON.Collider();
  7010. this._needMoveForGravity = true;
  7011. this._oldPosition = BABYLON.Vector3.Zero();
  7012. this._diffPosition = BABYLON.Vector3.Zero();
  7013. this._newPosition = BABYLON.Vector3.Zero();
  7014. }
  7015. // Controls
  7016. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  7017. var _this = this;
  7018. var previousPosition;
  7019. var engine = this.getEngine();
  7020. if (this._attachedElement) {
  7021. return;
  7022. }
  7023. this._attachedElement = element;
  7024. if (this._onMouseDown === undefined) {
  7025. this._onMouseDown = function (evt) {
  7026. previousPosition = {
  7027. x: evt.clientX,
  7028. y: evt.clientY
  7029. };
  7030. if (!noPreventDefault) {
  7031. evt.preventDefault();
  7032. }
  7033. };
  7034. this._onMouseUp = function (evt) {
  7035. previousPosition = null;
  7036. if (!noPreventDefault) {
  7037. evt.preventDefault();
  7038. }
  7039. };
  7040. this._onMouseOut = function (evt) {
  7041. previousPosition = null;
  7042. _this._keys = [];
  7043. if (!noPreventDefault) {
  7044. evt.preventDefault();
  7045. }
  7046. };
  7047. this._onMouseMove = function (evt) {
  7048. if (!previousPosition && !engine.isPointerLock) {
  7049. return;
  7050. }
  7051. var offsetX;
  7052. var offsetY;
  7053. if (!engine.isPointerLock) {
  7054. offsetX = evt.clientX - previousPosition.x;
  7055. offsetY = evt.clientY - previousPosition.y;
  7056. }
  7057. else {
  7058. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7059. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7060. }
  7061. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  7062. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  7063. previousPosition = {
  7064. x: evt.clientX,
  7065. y: evt.clientY
  7066. };
  7067. if (!noPreventDefault) {
  7068. evt.preventDefault();
  7069. }
  7070. };
  7071. this._onKeyDown = function (evt) {
  7072. 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) {
  7073. var index = _this._keys.indexOf(evt.keyCode);
  7074. if (index === -1) {
  7075. _this._keys.push(evt.keyCode);
  7076. }
  7077. if (!noPreventDefault) {
  7078. evt.preventDefault();
  7079. }
  7080. }
  7081. };
  7082. this._onKeyUp = function (evt) {
  7083. 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) {
  7084. var index = _this._keys.indexOf(evt.keyCode);
  7085. if (index >= 0) {
  7086. _this._keys.splice(index, 1);
  7087. }
  7088. if (!noPreventDefault) {
  7089. evt.preventDefault();
  7090. }
  7091. }
  7092. };
  7093. this._onLostFocus = function () {
  7094. _this._keys = [];
  7095. };
  7096. this._reset = function () {
  7097. _this._keys = [];
  7098. previousPosition = null;
  7099. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  7100. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  7101. };
  7102. }
  7103. element.addEventListener("mousedown", this._onMouseDown, false);
  7104. element.addEventListener("mouseup", this._onMouseUp, false);
  7105. element.addEventListener("mouseout", this._onMouseOut, false);
  7106. element.addEventListener("mousemove", this._onMouseMove, false);
  7107. BABYLON.Tools.RegisterTopRootEvents([
  7108. { name: "keydown", handler: this._onKeyDown },
  7109. { name: "keyup", handler: this._onKeyUp },
  7110. { name: "blur", handler: this._onLostFocus }
  7111. ]);
  7112. };
  7113. FreeCamera.prototype.detachControl = function (element) {
  7114. if (this._attachedElement != element) {
  7115. return;
  7116. }
  7117. element.removeEventListener("mousedown", this._onMouseDown);
  7118. element.removeEventListener("mouseup", this._onMouseUp);
  7119. element.removeEventListener("mouseout", this._onMouseOut);
  7120. element.removeEventListener("mousemove", this._onMouseMove);
  7121. BABYLON.Tools.UnregisterTopRootEvents([
  7122. { name: "keydown", handler: this._onKeyDown },
  7123. { name: "keyup", handler: this._onKeyUp },
  7124. { name: "blur", handler: this._onLostFocus }
  7125. ]);
  7126. this._attachedElement = null;
  7127. if (this._reset) {
  7128. this._reset();
  7129. }
  7130. };
  7131. FreeCamera.prototype._collideWithWorld = function (velocity) {
  7132. var globalPosition;
  7133. if (this.parent) {
  7134. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  7135. }
  7136. else {
  7137. globalPosition = this.position;
  7138. }
  7139. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  7140. this._collider.radius = this.ellipsoid;
  7141. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7142. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7143. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7144. this.position.addInPlace(this._diffPosition);
  7145. if (this.onCollide) {
  7146. this.onCollide(this._collider.collidedMesh);
  7147. }
  7148. }
  7149. };
  7150. FreeCamera.prototype._checkInputs = function () {
  7151. if (!this._localDirection) {
  7152. this._localDirection = BABYLON.Vector3.Zero();
  7153. this._transformedDirection = BABYLON.Vector3.Zero();
  7154. }
  7155. for (var index = 0; index < this._keys.length; index++) {
  7156. var keyCode = this._keys[index];
  7157. var speed = this._computeLocalCameraSpeed();
  7158. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7159. this._localDirection.copyFromFloats(-speed, 0, 0);
  7160. }
  7161. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7162. this._localDirection.copyFromFloats(0, 0, speed);
  7163. }
  7164. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7165. this._localDirection.copyFromFloats(speed, 0, 0);
  7166. }
  7167. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7168. this._localDirection.copyFromFloats(0, 0, -speed);
  7169. }
  7170. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7171. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7172. this.cameraDirection.addInPlace(this._transformedDirection);
  7173. }
  7174. };
  7175. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7176. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7177. };
  7178. FreeCamera.prototype._updatePosition = function () {
  7179. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7180. this._collideWithWorld(this.cameraDirection);
  7181. if (this.applyGravity) {
  7182. var oldPosition = this.position;
  7183. this._collideWithWorld(this.getScene().gravity);
  7184. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7185. }
  7186. }
  7187. else {
  7188. this.position.addInPlace(this.cameraDirection);
  7189. }
  7190. };
  7191. FreeCamera.prototype._update = function () {
  7192. this._checkInputs();
  7193. _super.prototype._update.call(this);
  7194. };
  7195. return FreeCamera;
  7196. })(BABYLON.TargetCamera);
  7197. BABYLON.FreeCamera = FreeCamera;
  7198. })(BABYLON || (BABYLON = {}));
  7199. //# sourceMappingURL=babylon.freeCamera.js.map
  7200. var BABYLON;
  7201. (function (BABYLON) {
  7202. // We're mainly based on the logic defined into the FreeCamera code
  7203. var TouchCamera = (function (_super) {
  7204. __extends(TouchCamera, _super);
  7205. function TouchCamera(name, position, scene) {
  7206. _super.call(this, name, position, scene);
  7207. this._offsetX = null;
  7208. this._offsetY = null;
  7209. this._pointerCount = 0;
  7210. this._pointerPressed = [];
  7211. this.angularSensibility = 200000.0;
  7212. this.moveSensibility = 500.0;
  7213. }
  7214. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7215. var _this = this;
  7216. var previousPosition;
  7217. if (this._attachedCanvas) {
  7218. return;
  7219. }
  7220. this._attachedCanvas = canvas;
  7221. if (this._onPointerDown === undefined) {
  7222. this._onPointerDown = function (evt) {
  7223. if (!noPreventDefault) {
  7224. evt.preventDefault();
  7225. }
  7226. _this._pointerPressed.push(evt.pointerId);
  7227. if (_this._pointerPressed.length !== 1) {
  7228. return;
  7229. }
  7230. previousPosition = {
  7231. x: evt.clientX,
  7232. y: evt.clientY
  7233. };
  7234. };
  7235. this._onPointerUp = function (evt) {
  7236. if (!noPreventDefault) {
  7237. evt.preventDefault();
  7238. }
  7239. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7240. if (index === -1) {
  7241. return;
  7242. }
  7243. _this._pointerPressed.splice(index, 1);
  7244. if (index != 0) {
  7245. return;
  7246. }
  7247. previousPosition = null;
  7248. _this._offsetX = null;
  7249. _this._offsetY = null;
  7250. };
  7251. this._onPointerMove = function (evt) {
  7252. if (!noPreventDefault) {
  7253. evt.preventDefault();
  7254. }
  7255. if (!previousPosition) {
  7256. return;
  7257. }
  7258. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7259. if (index != 0) {
  7260. return;
  7261. }
  7262. _this._offsetX = evt.clientX - previousPosition.x;
  7263. _this._offsetY = -(evt.clientY - previousPosition.y);
  7264. };
  7265. this._onLostFocus = function () {
  7266. _this._offsetX = null;
  7267. _this._offsetY = null;
  7268. };
  7269. }
  7270. canvas.addEventListener("pointerdown", this._onPointerDown);
  7271. canvas.addEventListener("pointerup", this._onPointerUp);
  7272. canvas.addEventListener("pointerout", this._onPointerUp);
  7273. canvas.addEventListener("pointermove", this._onPointerMove);
  7274. BABYLON.Tools.RegisterTopRootEvents([
  7275. { name: "blur", handler: this._onLostFocus }
  7276. ]);
  7277. };
  7278. TouchCamera.prototype.detachControl = function (canvas) {
  7279. if (this._attachedCanvas != canvas) {
  7280. return;
  7281. }
  7282. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7283. canvas.removeEventListener("pointerup", this._onPointerUp);
  7284. canvas.removeEventListener("pointerout", this._onPointerUp);
  7285. canvas.removeEventListener("pointermove", this._onPointerMove);
  7286. BABYLON.Tools.UnregisterTopRootEvents([
  7287. { name: "blur", handler: this._onLostFocus }
  7288. ]);
  7289. this._attachedCanvas = null;
  7290. };
  7291. TouchCamera.prototype._checkInputs = function () {
  7292. if (!this._offsetX) {
  7293. return;
  7294. }
  7295. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7296. if (this._pointerPressed.length > 1) {
  7297. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7298. }
  7299. else {
  7300. var speed = this._computeLocalCameraSpeed();
  7301. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7302. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7303. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7304. }
  7305. };
  7306. return TouchCamera;
  7307. })(BABYLON.FreeCamera);
  7308. BABYLON.TouchCamera = TouchCamera;
  7309. })(BABYLON || (BABYLON = {}));
  7310. //# sourceMappingURL=babylon.touchCamera.js.map
  7311. var BABYLON;
  7312. (function (BABYLON) {
  7313. // We're mainly based on the logic defined into the FreeCamera code
  7314. var DeviceOrientationCamera = (function (_super) {
  7315. __extends(DeviceOrientationCamera, _super);
  7316. function DeviceOrientationCamera(name, position, scene) {
  7317. var _this = this;
  7318. _super.call(this, name, position, scene);
  7319. this._offsetX = null;
  7320. this._offsetY = null;
  7321. this._orientationGamma = 0;
  7322. this._orientationBeta = 0;
  7323. this._initialOrientationGamma = 0;
  7324. this._initialOrientationBeta = 0;
  7325. this.angularSensibility = 10000.0;
  7326. this.moveSensibility = 50.0;
  7327. window.addEventListener("resize", function () {
  7328. _this._initialOrientationGamma = null;
  7329. }, false);
  7330. }
  7331. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7332. var _this = this;
  7333. if (this._attachedCanvas) {
  7334. return;
  7335. }
  7336. this._attachedCanvas = canvas;
  7337. if (!this._orientationChanged) {
  7338. this._orientationChanged = function (evt) {
  7339. if (!_this._initialOrientationGamma) {
  7340. _this._initialOrientationGamma = evt.gamma;
  7341. _this._initialOrientationBeta = evt.beta;
  7342. }
  7343. _this._orientationGamma = evt.gamma;
  7344. _this._orientationBeta = evt.beta;
  7345. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7346. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7347. };
  7348. }
  7349. window.addEventListener("deviceorientation", this._orientationChanged);
  7350. };
  7351. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7352. if (this._attachedCanvas != canvas) {
  7353. return;
  7354. }
  7355. window.removeEventListener("deviceorientation", this._orientationChanged);
  7356. this._attachedCanvas = null;
  7357. this._orientationGamma = 0;
  7358. this._orientationBeta = 0;
  7359. this._initialOrientationGamma = 0;
  7360. this._initialOrientationBeta = 0;
  7361. };
  7362. DeviceOrientationCamera.prototype._checkInputs = function () {
  7363. if (!this._offsetX) {
  7364. return;
  7365. }
  7366. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7367. var speed = this._computeLocalCameraSpeed();
  7368. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7369. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7370. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7371. };
  7372. return DeviceOrientationCamera;
  7373. })(BABYLON.FreeCamera);
  7374. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7375. })(BABYLON || (BABYLON = {}));
  7376. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7377. var BABYLON;
  7378. (function (BABYLON) {
  7379. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7380. var ArcRotateCamera = (function (_super) {
  7381. __extends(ArcRotateCamera, _super);
  7382. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7383. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7384. this.alpha = alpha;
  7385. this.beta = beta;
  7386. this.radius = radius;
  7387. this.target = target;
  7388. this.inertialAlphaOffset = 0;
  7389. this.inertialBetaOffset = 0;
  7390. this.inertialRadiusOffset = 0;
  7391. this.lowerAlphaLimit = null;
  7392. this.upperAlphaLimit = null;
  7393. this.lowerBetaLimit = 0.01;
  7394. this.upperBetaLimit = Math.PI;
  7395. this.lowerRadiusLimit = null;
  7396. this.upperRadiusLimit = null;
  7397. this.angularSensibility = 1000.0;
  7398. this.wheelPrecision = 3.0;
  7399. this.keysUp = [38];
  7400. this.keysDown = [40];
  7401. this.keysLeft = [37];
  7402. this.keysRight = [39];
  7403. this.zoomOnFactor = 1;
  7404. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7405. this._keys = [];
  7406. this._viewMatrix = new BABYLON.Matrix();
  7407. this.checkCollisions = false;
  7408. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7409. this._collider = new BABYLON.Collider();
  7410. this._previousPosition = BABYLON.Vector3.Zero();
  7411. this._collisionVelocity = BABYLON.Vector3.Zero();
  7412. this._newPosition = BABYLON.Vector3.Zero();
  7413. // Pinch
  7414. // value for pinch step scaling
  7415. // set to 20 by default
  7416. this.pinchPrecision = 20;
  7417. this.getViewMatrix();
  7418. }
  7419. ArcRotateCamera.prototype._getTargetPosition = function () {
  7420. return this.target.position || this.target;
  7421. };
  7422. // Cache
  7423. ArcRotateCamera.prototype._initCache = function () {
  7424. _super.prototype._initCache.call(this);
  7425. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7426. this._cache.alpha = undefined;
  7427. this._cache.beta = undefined;
  7428. this._cache.radius = undefined;
  7429. this._cache.targetScreenOffset = undefined;
  7430. };
  7431. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7432. if (!ignoreParentClass) {
  7433. _super.prototype._updateCache.call(this);
  7434. }
  7435. this._cache.target.copyFrom(this._getTargetPosition());
  7436. this._cache.alpha = this.alpha;
  7437. this._cache.beta = this.beta;
  7438. this._cache.radius = this.radius;
  7439. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7440. };
  7441. // Synchronized
  7442. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7443. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7444. return false;
  7445. 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);
  7446. };
  7447. // Methods
  7448. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7449. var _this = this;
  7450. var previousPosition;
  7451. var pointerId;
  7452. // to know if pinch started
  7453. var pinchStarted = false;
  7454. // two pinch point on X
  7455. // that will use for find if user action is pinch open or pinch close
  7456. var pinchPointX1, pinchPointX2;
  7457. if (this._attachedElement) {
  7458. return;
  7459. }
  7460. this._attachedElement = element;
  7461. var engine = this.getEngine();
  7462. if (this._onPointerDown === undefined) {
  7463. this._onPointerDown = function (evt) {
  7464. if (pointerId) {
  7465. return;
  7466. }
  7467. pointerId = evt.pointerId;
  7468. previousPosition = {
  7469. x: evt.clientX,
  7470. y: evt.clientY
  7471. };
  7472. if (!noPreventDefault) {
  7473. evt.preventDefault();
  7474. }
  7475. };
  7476. this._onPointerUp = function (evt) {
  7477. previousPosition = null;
  7478. pointerId = null;
  7479. if (!noPreventDefault) {
  7480. evt.preventDefault();
  7481. }
  7482. };
  7483. this._onPointerMove = function (evt) {
  7484. if (!previousPosition) {
  7485. return;
  7486. }
  7487. if (pointerId !== evt.pointerId) {
  7488. return;
  7489. }
  7490. // return pinch is started
  7491. if (pinchStarted) {
  7492. return;
  7493. }
  7494. var offsetX = evt.clientX - previousPosition.x;
  7495. var offsetY = evt.clientY - previousPosition.y;
  7496. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7497. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7498. previousPosition = {
  7499. x: evt.clientX,
  7500. y: evt.clientY
  7501. };
  7502. if (!noPreventDefault) {
  7503. evt.preventDefault();
  7504. }
  7505. };
  7506. this._onMouseMove = function (evt) {
  7507. if (!engine.isPointerLock) {
  7508. return;
  7509. }
  7510. // return pinch is started
  7511. if (pinchStarted) {
  7512. return;
  7513. }
  7514. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7515. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7516. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7517. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7518. if (!noPreventDefault) {
  7519. evt.preventDefault();
  7520. }
  7521. };
  7522. this._wheel = function (event) {
  7523. var delta = 0;
  7524. if (event.wheelDelta) {
  7525. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7526. }
  7527. else if (event.detail) {
  7528. delta = -event.detail / _this.wheelPrecision;
  7529. }
  7530. if (delta)
  7531. _this.inertialRadiusOffset += delta;
  7532. if (event.preventDefault) {
  7533. if (!noPreventDefault) {
  7534. event.preventDefault();
  7535. }
  7536. }
  7537. };
  7538. this._onKeyDown = function (evt) {
  7539. 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) {
  7540. var index = _this._keys.indexOf(evt.keyCode);
  7541. if (index === -1) {
  7542. _this._keys.push(evt.keyCode);
  7543. }
  7544. if (evt.preventDefault) {
  7545. if (!noPreventDefault) {
  7546. evt.preventDefault();
  7547. }
  7548. }
  7549. }
  7550. };
  7551. this._onKeyUp = function (evt) {
  7552. 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) {
  7553. var index = _this._keys.indexOf(evt.keyCode);
  7554. if (index >= 0) {
  7555. _this._keys.splice(index, 1);
  7556. }
  7557. if (evt.preventDefault) {
  7558. if (!noPreventDefault) {
  7559. evt.preventDefault();
  7560. }
  7561. }
  7562. }
  7563. };
  7564. this._onLostFocus = function () {
  7565. _this._keys = [];
  7566. pointerId = null;
  7567. };
  7568. this._onGestureStart = function (e) {
  7569. if (window.MSGesture === undefined) {
  7570. return;
  7571. }
  7572. if (!_this._MSGestureHandler) {
  7573. _this._MSGestureHandler = new MSGesture();
  7574. _this._MSGestureHandler.target = element;
  7575. }
  7576. _this._MSGestureHandler.addPointer(e.pointerId);
  7577. };
  7578. this._onGesture = function (e) {
  7579. _this.radius *= e.scale;
  7580. if (e.preventDefault) {
  7581. if (!noPreventDefault) {
  7582. e.stopPropagation();
  7583. e.preventDefault();
  7584. }
  7585. }
  7586. };
  7587. this._reset = function () {
  7588. _this._keys = [];
  7589. _this.inertialAlphaOffset = 0;
  7590. _this.inertialBetaOffset = 0;
  7591. _this.inertialRadiusOffset = 0;
  7592. previousPosition = null;
  7593. pointerId = null;
  7594. };
  7595. this._touchStart = function (event) {
  7596. if (event.touches.length === 2) {
  7597. //-- start pinch if two fingers on the screen
  7598. pinchStarted = true;
  7599. _this._pinchStart(event);
  7600. }
  7601. };
  7602. this._touchMove = function (event) {
  7603. if (pinchStarted) {
  7604. //-- make scaling
  7605. _this._pinchMove(event);
  7606. }
  7607. };
  7608. this._touchEnd = function (event) {
  7609. if (pinchStarted) {
  7610. //-- end of pinch
  7611. _this._pinchEnd(event);
  7612. }
  7613. };
  7614. this._pinchStart = function (event) {
  7615. // save origin touch point
  7616. pinchPointX1 = event.touches[0].clientX;
  7617. pinchPointX2 = event.touches[1].clientX;
  7618. // block the camera
  7619. // if not it rotate around target during pinch
  7620. pinchStarted = true;
  7621. };
  7622. this._pinchMove = function (event) {
  7623. // variable for new camera's radius
  7624. var delta = 0;
  7625. // variables to know if pinch open or pinch close
  7626. var direction = 1;
  7627. var distanceXOrigine, distanceXNow;
  7628. if (event.touches.length !== 2)
  7629. return;
  7630. // calculate absolute distances of the two fingers
  7631. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7632. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7633. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7634. if (distanceXNow < distanceXOrigine) {
  7635. direction = -1;
  7636. }
  7637. // calculate new radius
  7638. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7639. // set new radius
  7640. _this.inertialRadiusOffset -= delta;
  7641. // save origin touch point
  7642. pinchPointX1 = event.touches[0].clientX;
  7643. pinchPointX2 = event.touches[1].clientX;
  7644. };
  7645. this._pinchEnd = function (event) {
  7646. // cancel pinch and deblock camera rotation
  7647. pinchStarted = false;
  7648. };
  7649. }
  7650. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7651. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7652. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7653. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7654. element.addEventListener("mousemove", this._onMouseMove, false);
  7655. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7656. element.addEventListener("MSGestureChange", this._onGesture, false);
  7657. element.addEventListener('mousewheel', this._wheel, false);
  7658. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7659. // pinch
  7660. element.addEventListener('touchstart', this._touchStart, false);
  7661. element.addEventListener('touchmove', this._touchMove, false);
  7662. element.addEventListener('touchend', this._touchEnd, false);
  7663. BABYLON.Tools.RegisterTopRootEvents([
  7664. { name: "keydown", handler: this._onKeyDown },
  7665. { name: "keyup", handler: this._onKeyUp },
  7666. { name: "blur", handler: this._onLostFocus }
  7667. ]);
  7668. };
  7669. ArcRotateCamera.prototype.detachControl = function (element) {
  7670. if (this._attachedElement != element) {
  7671. return;
  7672. }
  7673. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7674. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7675. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7676. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7677. element.removeEventListener("mousemove", this._onMouseMove);
  7678. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7679. element.removeEventListener("MSGestureChange", this._onGesture);
  7680. element.removeEventListener('mousewheel', this._wheel);
  7681. element.removeEventListener('DOMMouseScroll', this._wheel);
  7682. // pinch
  7683. element.removeEventListener('touchstart', this._touchStart);
  7684. element.removeEventListener('touchmove', this._touchMove);
  7685. element.removeEventListener('touchend', this._touchEnd);
  7686. BABYLON.Tools.UnregisterTopRootEvents([
  7687. { name: "keydown", handler: this._onKeyDown },
  7688. { name: "keyup", handler: this._onKeyUp },
  7689. { name: "blur", handler: this._onLostFocus }
  7690. ]);
  7691. this._MSGestureHandler = null;
  7692. this._attachedElement = null;
  7693. if (this._reset) {
  7694. this._reset();
  7695. }
  7696. };
  7697. ArcRotateCamera.prototype._update = function () {
  7698. for (var index = 0; index < this._keys.length; index++) {
  7699. var keyCode = this._keys[index];
  7700. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7701. this.inertialAlphaOffset -= 0.01;
  7702. }
  7703. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7704. this.inertialBetaOffset -= 0.01;
  7705. }
  7706. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7707. this.inertialAlphaOffset += 0.01;
  7708. }
  7709. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7710. this.inertialBetaOffset += 0.01;
  7711. }
  7712. }
  7713. // Inertia
  7714. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7715. this.alpha += this.inertialAlphaOffset;
  7716. this.beta += this.inertialBetaOffset;
  7717. this.radius -= this.inertialRadiusOffset;
  7718. this.inertialAlphaOffset *= this.inertia;
  7719. this.inertialBetaOffset *= this.inertia;
  7720. this.inertialRadiusOffset *= this.inertia;
  7721. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7722. this.inertialAlphaOffset = 0;
  7723. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7724. this.inertialBetaOffset = 0;
  7725. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7726. this.inertialRadiusOffset = 0;
  7727. }
  7728. // Limits
  7729. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7730. this.alpha = this.lowerAlphaLimit;
  7731. }
  7732. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7733. this.alpha = this.upperAlphaLimit;
  7734. }
  7735. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7736. this.beta = this.lowerBetaLimit;
  7737. }
  7738. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7739. this.beta = this.upperBetaLimit;
  7740. }
  7741. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7742. this.radius = this.lowerRadiusLimit;
  7743. }
  7744. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7745. this.radius = this.upperRadiusLimit;
  7746. }
  7747. };
  7748. ArcRotateCamera.prototype.setPosition = function (position) {
  7749. var radiusv3 = position.subtract(this._getTargetPosition());
  7750. this.radius = radiusv3.length();
  7751. // Alpha
  7752. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7753. if (radiusv3.z < 0) {
  7754. this.alpha = 2 * Math.PI - this.alpha;
  7755. }
  7756. // Beta
  7757. this.beta = Math.acos(radiusv3.y / this.radius);
  7758. };
  7759. ArcRotateCamera.prototype._getViewMatrix = function () {
  7760. // Compute
  7761. var cosa = Math.cos(this.alpha);
  7762. var sina = Math.sin(this.alpha);
  7763. var cosb = Math.cos(this.beta);
  7764. var sinb = Math.sin(this.beta);
  7765. var target = this._getTargetPosition();
  7766. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7767. if (this.checkCollisions) {
  7768. this._collider.radius = this.collisionRadius;
  7769. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7770. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7771. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7772. this.position.copyFrom(this._previousPosition);
  7773. this.alpha = this._previousAlpha;
  7774. this.beta = this._previousBeta;
  7775. this.radius = this._previousRadius;
  7776. if (this.onCollide) {
  7777. this.onCollide(this._collider.collidedMesh);
  7778. }
  7779. }
  7780. }
  7781. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7782. this._previousAlpha = this.alpha;
  7783. this._previousBeta = this.beta;
  7784. this._previousRadius = this.radius;
  7785. this._previousPosition.copyFrom(this.position);
  7786. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7787. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7788. return this._viewMatrix;
  7789. };
  7790. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7791. meshes = meshes || this.getScene().meshes;
  7792. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7793. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7794. this.radius = distance * this.zoomOnFactor;
  7795. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7796. };
  7797. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7798. var meshesOrMinMaxVector;
  7799. var distance;
  7800. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7801. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7802. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7803. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7804. }
  7805. else {
  7806. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7807. distance = meshesOrMinMaxVectorAndDistance.distance;
  7808. }
  7809. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7810. this.maxZ = distance * 2;
  7811. };
  7812. return ArcRotateCamera;
  7813. })(BABYLON.Camera);
  7814. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7815. })(BABYLON || (BABYLON = {}));
  7816. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7817. (function (BABYLON) {
  7818. /**
  7819. * Represents a scene to be rendered by the engine.
  7820. * @see http://doc.babylonjs.com/page.php?p=21911
  7821. */
  7822. var Scene = (function () {
  7823. /**
  7824. * @constructor
  7825. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7826. */
  7827. function Scene(engine) {
  7828. // Members
  7829. this.autoClear = true;
  7830. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7831. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7832. this.forceWireframe = false;
  7833. this.forcePointsCloud = false;
  7834. this.forceShowBoundingBoxes = false;
  7835. this.animationsEnabled = true;
  7836. 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
  7837. // Fog
  7838. /**
  7839. * is fog enabled on this scene.
  7840. * @type {boolean}
  7841. */
  7842. this.fogEnabled = true;
  7843. this.fogMode = Scene.FOGMODE_NONE;
  7844. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7845. this.fogDensity = 0.1;
  7846. this.fogStart = 0;
  7847. this.fogEnd = 1000.0;
  7848. // Lights
  7849. /**
  7850. * is shadow enabled on this scene.
  7851. * @type {boolean}
  7852. */
  7853. this.shadowsEnabled = true;
  7854. /**
  7855. * is light enabled on this scene.
  7856. * @type {boolean}
  7857. */
  7858. this.lightsEnabled = true;
  7859. /**
  7860. * All of the lights added to this scene.
  7861. * @see BABYLON.Light
  7862. * @type {BABYLON.Light[]}
  7863. */
  7864. this.lights = new Array();
  7865. // Cameras
  7866. /**
  7867. * All of the cameras added to this scene.
  7868. * @see BABYLON.Camera
  7869. * @type {BABYLON.Camera[]}
  7870. */
  7871. this.cameras = new Array();
  7872. this.activeCameras = new Array();
  7873. // Meshes
  7874. /**
  7875. * All of the (abstract) meshes added to this scene.
  7876. * @see BABYLON.AbstractMesh
  7877. * @type {BABYLON.AbstractMesh[]}
  7878. */
  7879. this.meshes = new Array();
  7880. // Geometries
  7881. this._geometries = new Array();
  7882. this.materials = new Array();
  7883. this.multiMaterials = new Array();
  7884. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7885. // Textures
  7886. this.texturesEnabled = true;
  7887. this.textures = new Array();
  7888. // Particles
  7889. this.particlesEnabled = true;
  7890. this.particleSystems = new Array();
  7891. // Sprites
  7892. this.spritesEnabled = true;
  7893. this.spriteManagers = new Array();
  7894. // Layers
  7895. this.layers = new Array();
  7896. // Skeletons
  7897. this.skeletonsEnabled = true;
  7898. this.skeletons = new Array();
  7899. // Lens flares
  7900. this.lensFlaresEnabled = true;
  7901. this.lensFlareSystems = new Array();
  7902. // Collisions
  7903. this.collisionsEnabled = true;
  7904. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7905. // Postprocesses
  7906. this.postProcessesEnabled = true;
  7907. // Customs render targets
  7908. this.renderTargetsEnabled = true;
  7909. this.dumpNextRenderTargets = false;
  7910. this.customRenderTargets = new Array();
  7911. // Imported meshes
  7912. this.importedMeshesFiles = new Array();
  7913. this._actionManagers = new Array();
  7914. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7915. // Procedural textures
  7916. this.proceduralTexturesEnabled = true;
  7917. this._proceduralTextures = new Array();
  7918. this.soundTracks = new Array();
  7919. this._audioEnabled = true;
  7920. this._headphone = false;
  7921. this._totalVertices = 0;
  7922. this._activeVertices = 0;
  7923. this._activeParticles = 0;
  7924. this._lastFrameDuration = 0;
  7925. this._evaluateActiveMeshesDuration = 0;
  7926. this._renderTargetsDuration = 0;
  7927. this._particlesDuration = 0;
  7928. this._renderDuration = 0;
  7929. this._spritesDuration = 0;
  7930. this._animationRatio = 0;
  7931. this._renderId = 0;
  7932. this._executeWhenReadyTimeoutId = -1;
  7933. this._toBeDisposed = new BABYLON.SmartArray(256);
  7934. this._onReadyCallbacks = new Array();
  7935. this._pendingData = []; //ANY
  7936. this._onBeforeRenderCallbacks = new Array();
  7937. this._onAfterRenderCallbacks = new Array();
  7938. this._activeMeshes = new BABYLON.SmartArray(256);
  7939. this._processedMaterials = new BABYLON.SmartArray(256);
  7940. this._renderTargets = new BABYLON.SmartArray(256);
  7941. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7942. this._activeSkeletons = new BABYLON.SmartArray(32);
  7943. this._activeBones = 0;
  7944. this._activeAnimatables = new Array();
  7945. this._transformMatrix = BABYLON.Matrix.Zero();
  7946. this._scaledPosition = BABYLON.Vector3.Zero();
  7947. this._scaledVelocity = BABYLON.Vector3.Zero();
  7948. this._engine = engine;
  7949. engine.scenes.push(this);
  7950. this._renderingManager = new BABYLON.RenderingManager(this);
  7951. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7952. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7953. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7954. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7955. this.attachControl();
  7956. this._debugLayer = new BABYLON.DebugLayer(this);
  7957. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7958. //simplification queue
  7959. this.simplificationQueue = new BABYLON.SimplificationQueue();
  7960. }
  7961. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7962. get: function () {
  7963. return Scene._FOGMODE_NONE;
  7964. },
  7965. enumerable: true,
  7966. configurable: true
  7967. });
  7968. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7969. get: function () {
  7970. return Scene._FOGMODE_EXP;
  7971. },
  7972. enumerable: true,
  7973. configurable: true
  7974. });
  7975. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7976. get: function () {
  7977. return Scene._FOGMODE_EXP2;
  7978. },
  7979. enumerable: true,
  7980. configurable: true
  7981. });
  7982. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7983. get: function () {
  7984. return Scene._FOGMODE_LINEAR;
  7985. },
  7986. enumerable: true,
  7987. configurable: true
  7988. });
  7989. Object.defineProperty(Scene.prototype, "debugLayer", {
  7990. // Properties
  7991. get: function () {
  7992. return this._debugLayer;
  7993. },
  7994. enumerable: true,
  7995. configurable: true
  7996. });
  7997. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7998. /**
  7999. * The mesh that is currently under the pointer.
  8000. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  8001. */
  8002. get: function () {
  8003. return this._meshUnderPointer;
  8004. },
  8005. enumerable: true,
  8006. configurable: true
  8007. });
  8008. Object.defineProperty(Scene.prototype, "pointerX", {
  8009. /**
  8010. * Current on-screen X position of the pointer
  8011. * @return {number} X position of the pointer
  8012. */
  8013. get: function () {
  8014. return this._pointerX;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Scene.prototype, "pointerY", {
  8020. /**
  8021. * Current on-screen Y position of the pointer
  8022. * @return {number} Y position of the pointer
  8023. */
  8024. get: function () {
  8025. return this._pointerY;
  8026. },
  8027. enumerable: true,
  8028. configurable: true
  8029. });
  8030. Scene.prototype.getCachedMaterial = function () {
  8031. return this._cachedMaterial;
  8032. };
  8033. Scene.prototype.getBoundingBoxRenderer = function () {
  8034. return this._boundingBoxRenderer;
  8035. };
  8036. Scene.prototype.getOutlineRenderer = function () {
  8037. return this._outlineRenderer;
  8038. };
  8039. Scene.prototype.getEngine = function () {
  8040. return this._engine;
  8041. };
  8042. Scene.prototype.getTotalVertices = function () {
  8043. return this._totalVertices;
  8044. };
  8045. Scene.prototype.getActiveVertices = function () {
  8046. return this._activeVertices;
  8047. };
  8048. Scene.prototype.getActiveParticles = function () {
  8049. return this._activeParticles;
  8050. };
  8051. Scene.prototype.getActiveBones = function () {
  8052. return this._activeBones;
  8053. };
  8054. // Stats
  8055. Scene.prototype.getLastFrameDuration = function () {
  8056. return this._lastFrameDuration;
  8057. };
  8058. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  8059. return this._evaluateActiveMeshesDuration;
  8060. };
  8061. Scene.prototype.getActiveMeshes = function () {
  8062. return this._activeMeshes;
  8063. };
  8064. Scene.prototype.getRenderTargetsDuration = function () {
  8065. return this._renderTargetsDuration;
  8066. };
  8067. Scene.prototype.getRenderDuration = function () {
  8068. return this._renderDuration;
  8069. };
  8070. Scene.prototype.getParticlesDuration = function () {
  8071. return this._particlesDuration;
  8072. };
  8073. Scene.prototype.getSpritesDuration = function () {
  8074. return this._spritesDuration;
  8075. };
  8076. Scene.prototype.getAnimationRatio = function () {
  8077. return this._animationRatio;
  8078. };
  8079. Scene.prototype.getRenderId = function () {
  8080. return this._renderId;
  8081. };
  8082. Scene.prototype.incrementRenderId = function () {
  8083. this._renderId++;
  8084. };
  8085. Scene.prototype._updatePointerPosition = function (evt) {
  8086. var canvasRect = this._engine.getRenderingCanvasClientRect();
  8087. this._pointerX = evt.clientX - canvasRect.left;
  8088. this._pointerY = evt.clientY - canvasRect.top;
  8089. if (this.cameraToUseForPointers) {
  8090. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  8091. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  8092. }
  8093. };
  8094. // Pointers handling
  8095. Scene.prototype.attachControl = function () {
  8096. var _this = this;
  8097. this._onPointerMove = function (evt) {
  8098. var canvas = _this._engine.getRenderingCanvas();
  8099. _this._updatePointerPosition(evt);
  8100. 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);
  8101. if (pickResult.hit) {
  8102. _this._meshUnderPointer = pickResult.pickedMesh;
  8103. _this.setPointerOverMesh(pickResult.pickedMesh);
  8104. canvas.style.cursor = "pointer";
  8105. }
  8106. else {
  8107. _this.setPointerOverMesh(null);
  8108. canvas.style.cursor = "";
  8109. _this._meshUnderPointer = null;
  8110. }
  8111. };
  8112. this._onPointerDown = function (evt) {
  8113. var predicate = null;
  8114. if (!_this.onPointerDown) {
  8115. predicate = function (mesh) {
  8116. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  8117. };
  8118. }
  8119. _this._updatePointerPosition(evt);
  8120. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  8121. if (pickResult.hit) {
  8122. if (pickResult.pickedMesh.actionManager) {
  8123. switch (evt.button) {
  8124. case 0:
  8125. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8126. break;
  8127. case 1:
  8128. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8129. break;
  8130. case 2:
  8131. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8132. break;
  8133. }
  8134. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  8135. }
  8136. }
  8137. if (_this.onPointerDown) {
  8138. _this.onPointerDown(evt, pickResult);
  8139. }
  8140. };
  8141. this._onKeyDown = function (evt) {
  8142. if (_this.actionManager) {
  8143. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8144. }
  8145. };
  8146. this._onKeyUp = function (evt) {
  8147. if (_this.actionManager) {
  8148. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8149. }
  8150. };
  8151. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8152. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8153. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8154. BABYLON.Tools.RegisterTopRootEvents([
  8155. { name: "keydown", handler: this._onKeyDown },
  8156. { name: "keyup", handler: this._onKeyUp }
  8157. ]);
  8158. };
  8159. Scene.prototype.detachControl = function () {
  8160. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8161. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8162. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8163. BABYLON.Tools.UnregisterTopRootEvents([
  8164. { name: "keydown", handler: this._onKeyDown },
  8165. { name: "keyup", handler: this._onKeyUp }
  8166. ]);
  8167. };
  8168. // Ready
  8169. Scene.prototype.isReady = function () {
  8170. if (this._pendingData.length > 0) {
  8171. return false;
  8172. }
  8173. for (var index = 0; index < this._geometries.length; index++) {
  8174. var geometry = this._geometries[index];
  8175. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8176. return false;
  8177. }
  8178. }
  8179. for (index = 0; index < this.meshes.length; index++) {
  8180. var mesh = this.meshes[index];
  8181. if (!mesh.isReady()) {
  8182. return false;
  8183. }
  8184. var mat = mesh.material;
  8185. if (mat) {
  8186. if (!mat.isReady(mesh)) {
  8187. return false;
  8188. }
  8189. }
  8190. }
  8191. return true;
  8192. };
  8193. Scene.prototype.resetCachedMaterial = function () {
  8194. this._cachedMaterial = null;
  8195. };
  8196. Scene.prototype.registerBeforeRender = function (func) {
  8197. this._onBeforeRenderCallbacks.push(func);
  8198. };
  8199. Scene.prototype.unregisterBeforeRender = function (func) {
  8200. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8201. if (index > -1) {
  8202. this._onBeforeRenderCallbacks.splice(index, 1);
  8203. }
  8204. };
  8205. Scene.prototype.registerAfterRender = function (func) {
  8206. this._onAfterRenderCallbacks.push(func);
  8207. };
  8208. Scene.prototype.unregisterAfterRender = function (func) {
  8209. var index = this._onAfterRenderCallbacks.indexOf(func);
  8210. if (index > -1) {
  8211. this._onAfterRenderCallbacks.splice(index, 1);
  8212. }
  8213. };
  8214. Scene.prototype._addPendingData = function (data) {
  8215. this._pendingData.push(data);
  8216. };
  8217. Scene.prototype._removePendingData = function (data) {
  8218. var index = this._pendingData.indexOf(data);
  8219. if (index !== -1) {
  8220. this._pendingData.splice(index, 1);
  8221. }
  8222. };
  8223. Scene.prototype.getWaitingItemsCount = function () {
  8224. return this._pendingData.length;
  8225. };
  8226. /**
  8227. * Registers a function to be executed when the scene is ready.
  8228. * @param {Function} func - the function to be executed.
  8229. */
  8230. Scene.prototype.executeWhenReady = function (func) {
  8231. var _this = this;
  8232. this._onReadyCallbacks.push(func);
  8233. if (this._executeWhenReadyTimeoutId !== -1) {
  8234. return;
  8235. }
  8236. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8237. _this._checkIsReady();
  8238. }, 150);
  8239. };
  8240. Scene.prototype._checkIsReady = function () {
  8241. var _this = this;
  8242. if (this.isReady()) {
  8243. this._onReadyCallbacks.forEach(function (func) {
  8244. func();
  8245. });
  8246. this._onReadyCallbacks = [];
  8247. this._executeWhenReadyTimeoutId = -1;
  8248. return;
  8249. }
  8250. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8251. _this._checkIsReady();
  8252. }, 150);
  8253. };
  8254. // Animations
  8255. /**
  8256. * Will start the animation sequence of a given target
  8257. * @param target - the target
  8258. * @param {number} from - from which frame should animation start
  8259. * @param {number} to - till which frame should animation run.
  8260. * @param {boolean} [loop] - should the animation loop
  8261. * @param {number} [speedRatio] - the speed in which to run the animation
  8262. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8263. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8264. * @return {BABYLON.Animatable} the animatable object created for this animation
  8265. * @see BABYLON.Animatable
  8266. * @see http://doc.babylonjs.com/page.php?p=22081
  8267. */
  8268. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8269. if (speedRatio === undefined) {
  8270. speedRatio = 1.0;
  8271. }
  8272. this.stopAnimation(target);
  8273. if (!animatable) {
  8274. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8275. }
  8276. // Local animations
  8277. if (target.animations) {
  8278. animatable.appendAnimations(target, target.animations);
  8279. }
  8280. // Children animations
  8281. if (target.getAnimatables) {
  8282. var animatables = target.getAnimatables();
  8283. for (var index = 0; index < animatables.length; index++) {
  8284. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8285. }
  8286. }
  8287. return animatable;
  8288. };
  8289. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8290. if (speedRatio === undefined) {
  8291. speedRatio = 1.0;
  8292. }
  8293. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8294. return animatable;
  8295. };
  8296. Scene.prototype.getAnimatableByTarget = function (target) {
  8297. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8298. if (this._activeAnimatables[index].target === target) {
  8299. return this._activeAnimatables[index];
  8300. }
  8301. }
  8302. return null;
  8303. };
  8304. /**
  8305. * Will stop the animation of the given target
  8306. * @param target - the target
  8307. * @see beginAnimation
  8308. */
  8309. Scene.prototype.stopAnimation = function (target) {
  8310. var animatable = this.getAnimatableByTarget(target);
  8311. if (animatable) {
  8312. animatable.stop();
  8313. }
  8314. };
  8315. Scene.prototype._animate = function () {
  8316. if (!this.animationsEnabled) {
  8317. return;
  8318. }
  8319. if (!this._animationStartDate) {
  8320. this._animationStartDate = BABYLON.Tools.Now;
  8321. }
  8322. // Getting time
  8323. var now = BABYLON.Tools.Now;
  8324. var delay = now - this._animationStartDate;
  8325. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8326. if (!this._activeAnimatables[index]._animate(delay)) {
  8327. this._activeAnimatables.splice(index, 1);
  8328. index--;
  8329. }
  8330. }
  8331. };
  8332. // Matrix
  8333. Scene.prototype.getViewMatrix = function () {
  8334. return this._viewMatrix;
  8335. };
  8336. Scene.prototype.getProjectionMatrix = function () {
  8337. return this._projectionMatrix;
  8338. };
  8339. Scene.prototype.getTransformMatrix = function () {
  8340. return this._transformMatrix;
  8341. };
  8342. Scene.prototype.setTransformMatrix = function (view, projection) {
  8343. this._viewMatrix = view;
  8344. this._projectionMatrix = projection;
  8345. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8346. };
  8347. // Methods
  8348. /**
  8349. * sets the active camera of the scene using its ID
  8350. * @param {string} id - the camera's ID
  8351. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8352. * @see activeCamera
  8353. */
  8354. Scene.prototype.setActiveCameraByID = function (id) {
  8355. var camera = this.getCameraByID(id);
  8356. if (camera) {
  8357. this.activeCamera = camera;
  8358. return camera;
  8359. }
  8360. return null;
  8361. };
  8362. /**
  8363. * sets the active camera of the scene using its name
  8364. * @param {string} name - the camera's name
  8365. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8366. * @see activeCamera
  8367. */
  8368. Scene.prototype.setActiveCameraByName = function (name) {
  8369. var camera = this.getCameraByName(name);
  8370. if (camera) {
  8371. this.activeCamera = camera;
  8372. return camera;
  8373. }
  8374. return null;
  8375. };
  8376. /**
  8377. * get a material using its id
  8378. * @param {string} the material's ID
  8379. * @return {BABYLON.Material|null} the material or null if none found.
  8380. */
  8381. Scene.prototype.getMaterialByID = function (id) {
  8382. for (var index = 0; index < this.materials.length; index++) {
  8383. if (this.materials[index].id === id) {
  8384. return this.materials[index];
  8385. }
  8386. }
  8387. return null;
  8388. };
  8389. /**
  8390. * get a material using its name
  8391. * @param {string} the material's name
  8392. * @return {BABYLON.Material|null} the material or null if none found.
  8393. */
  8394. Scene.prototype.getMaterialByName = function (name) {
  8395. for (var index = 0; index < this.materials.length; index++) {
  8396. if (this.materials[index].name === name) {
  8397. return this.materials[index];
  8398. }
  8399. }
  8400. return null;
  8401. };
  8402. Scene.prototype.getCameraByID = function (id) {
  8403. for (var index = 0; index < this.cameras.length; index++) {
  8404. if (this.cameras[index].id === id) {
  8405. return this.cameras[index];
  8406. }
  8407. }
  8408. return null;
  8409. };
  8410. /**
  8411. * get a camera using its name
  8412. * @param {string} the camera's name
  8413. * @return {BABYLON.Camera|null} the camera or null if none found.
  8414. */
  8415. Scene.prototype.getCameraByName = function (name) {
  8416. for (var index = 0; index < this.cameras.length; index++) {
  8417. if (this.cameras[index].name === name) {
  8418. return this.cameras[index];
  8419. }
  8420. }
  8421. return null;
  8422. };
  8423. /**
  8424. * get a light node using its name
  8425. * @param {string} the light's name
  8426. * @return {BABYLON.Light|null} the light or null if none found.
  8427. */
  8428. Scene.prototype.getLightByName = function (name) {
  8429. for (var index = 0; index < this.lights.length; index++) {
  8430. if (this.lights[index].name === name) {
  8431. return this.lights[index];
  8432. }
  8433. }
  8434. return null;
  8435. };
  8436. /**
  8437. * get a light node using its ID
  8438. * @param {string} the light's id
  8439. * @return {BABYLON.Light|null} the light or null if none found.
  8440. */
  8441. Scene.prototype.getLightByID = function (id) {
  8442. for (var index = 0; index < this.lights.length; index++) {
  8443. if (this.lights[index].id === id) {
  8444. return this.lights[index];
  8445. }
  8446. }
  8447. return null;
  8448. };
  8449. /**
  8450. * get a geometry using its ID
  8451. * @param {string} the geometry's id
  8452. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8453. */
  8454. Scene.prototype.getGeometryByID = function (id) {
  8455. for (var index = 0; index < this._geometries.length; index++) {
  8456. if (this._geometries[index].id === id) {
  8457. return this._geometries[index];
  8458. }
  8459. }
  8460. return null;
  8461. };
  8462. /**
  8463. * add a new geometry to this scene.
  8464. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8465. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8466. * @return {boolean} was the geometry added or not
  8467. */
  8468. Scene.prototype.pushGeometry = function (geometry, force) {
  8469. if (!force && this.getGeometryByID(geometry.id)) {
  8470. return false;
  8471. }
  8472. this._geometries.push(geometry);
  8473. return true;
  8474. };
  8475. Scene.prototype.getGeometries = function () {
  8476. return this._geometries;
  8477. };
  8478. /**
  8479. * Get a the first added mesh found of a given ID
  8480. * @param {string} id - the id to search for
  8481. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8482. */
  8483. Scene.prototype.getMeshByID = function (id) {
  8484. for (var index = 0; index < this.meshes.length; index++) {
  8485. if (this.meshes[index].id === id) {
  8486. return this.meshes[index];
  8487. }
  8488. }
  8489. return null;
  8490. };
  8491. /**
  8492. * Get a the last added mesh found of a given ID
  8493. * @param {string} id - the id to search for
  8494. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8495. */
  8496. Scene.prototype.getLastMeshByID = function (id) {
  8497. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8498. if (this.meshes[index].id === id) {
  8499. return this.meshes[index];
  8500. }
  8501. }
  8502. return null;
  8503. };
  8504. /**
  8505. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8506. * @param {string} id - the id to search for
  8507. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8508. */
  8509. Scene.prototype.getLastEntryByID = function (id) {
  8510. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8511. if (this.meshes[index].id === id) {
  8512. return this.meshes[index];
  8513. }
  8514. }
  8515. for (index = this.cameras.length - 1; index >= 0; index--) {
  8516. if (this.cameras[index].id === id) {
  8517. return this.cameras[index];
  8518. }
  8519. }
  8520. for (index = this.lights.length - 1; index >= 0; index--) {
  8521. if (this.lights[index].id === id) {
  8522. return this.lights[index];
  8523. }
  8524. }
  8525. return null;
  8526. };
  8527. Scene.prototype.getNodeByName = function (name) {
  8528. var mesh = this.getMeshByName(name);
  8529. if (mesh) {
  8530. return mesh;
  8531. }
  8532. var light = this.getLightByName(name);
  8533. if (light) {
  8534. return light;
  8535. }
  8536. return this.getCameraByName(name);
  8537. };
  8538. Scene.prototype.getMeshByName = function (name) {
  8539. for (var index = 0; index < this.meshes.length; index++) {
  8540. if (this.meshes[index].name === name) {
  8541. return this.meshes[index];
  8542. }
  8543. }
  8544. return null;
  8545. };
  8546. Scene.prototype.getSoundByName = function (name) {
  8547. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8548. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8549. return this.mainSoundTrack.soundCollection[index];
  8550. }
  8551. }
  8552. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8553. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8554. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8555. return this.soundTracks[sdIndex].soundCollection[index];
  8556. }
  8557. }
  8558. }
  8559. return null;
  8560. };
  8561. Scene.prototype.getLastSkeletonByID = function (id) {
  8562. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8563. if (this.skeletons[index].id === id) {
  8564. return this.skeletons[index];
  8565. }
  8566. }
  8567. return null;
  8568. };
  8569. Scene.prototype.getSkeletonById = function (id) {
  8570. for (var index = 0; index < this.skeletons.length; index++) {
  8571. if (this.skeletons[index].id === id) {
  8572. return this.skeletons[index];
  8573. }
  8574. }
  8575. return null;
  8576. };
  8577. Scene.prototype.getSkeletonByName = function (name) {
  8578. for (var index = 0; index < this.skeletons.length; index++) {
  8579. if (this.skeletons[index].name === name) {
  8580. return this.skeletons[index];
  8581. }
  8582. }
  8583. return null;
  8584. };
  8585. Scene.prototype.isActiveMesh = function (mesh) {
  8586. return (this._activeMeshes.indexOf(mesh) !== -1);
  8587. };
  8588. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8589. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8590. var material = subMesh.getMaterial();
  8591. if (mesh.showSubMeshesBoundingBox) {
  8592. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8593. }
  8594. if (material) {
  8595. // Render targets
  8596. if (material.getRenderTargetTextures) {
  8597. if (this._processedMaterials.indexOf(material) === -1) {
  8598. this._processedMaterials.push(material);
  8599. this._renderTargets.concat(material.getRenderTargetTextures());
  8600. }
  8601. }
  8602. // Dispatch
  8603. this._activeVertices += subMesh.indexCount;
  8604. this._renderingManager.dispatch(subMesh);
  8605. }
  8606. }
  8607. };
  8608. Scene.prototype._evaluateActiveMeshes = function () {
  8609. this.activeCamera._activeMeshes.reset();
  8610. this._activeMeshes.reset();
  8611. this._renderingManager.reset();
  8612. this._processedMaterials.reset();
  8613. this._activeParticleSystems.reset();
  8614. this._activeSkeletons.reset();
  8615. this._boundingBoxRenderer.reset();
  8616. if (!this._frustumPlanes) {
  8617. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8618. }
  8619. else {
  8620. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8621. }
  8622. // Meshes
  8623. var meshes;
  8624. var len;
  8625. if (this._selectionOctree) {
  8626. var selection = this._selectionOctree.select(this._frustumPlanes);
  8627. meshes = selection.data;
  8628. len = selection.length;
  8629. }
  8630. else {
  8631. len = this.meshes.length;
  8632. meshes = this.meshes;
  8633. }
  8634. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8635. var mesh = meshes[meshIndex];
  8636. if (mesh.isBlocked) {
  8637. continue;
  8638. }
  8639. this._totalVertices += mesh.getTotalVertices();
  8640. if (!mesh.isReady()) {
  8641. continue;
  8642. }
  8643. mesh.computeWorldMatrix();
  8644. // Intersections
  8645. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8646. this._meshesForIntersections.pushNoDuplicate(mesh);
  8647. }
  8648. // Switch to current LOD
  8649. var meshLOD = mesh.getLOD(this.activeCamera);
  8650. if (!meshLOD) {
  8651. continue;
  8652. }
  8653. mesh._preActivate();
  8654. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8655. this._activeMeshes.push(mesh);
  8656. this.activeCamera._activeMeshes.push(mesh);
  8657. mesh._activate(this._renderId);
  8658. this._activeMesh(meshLOD);
  8659. }
  8660. }
  8661. // Particle systems
  8662. var beforeParticlesDate = BABYLON.Tools.Now;
  8663. if (this.particlesEnabled) {
  8664. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8665. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8666. var particleSystem = this.particleSystems[particleIndex];
  8667. if (!particleSystem.isStarted()) {
  8668. continue;
  8669. }
  8670. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8671. this._activeParticleSystems.push(particleSystem);
  8672. particleSystem.animate();
  8673. }
  8674. }
  8675. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8676. }
  8677. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8678. };
  8679. Scene.prototype._activeMesh = function (mesh) {
  8680. if (mesh.skeleton && this.skeletonsEnabled) {
  8681. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8682. }
  8683. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8684. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8685. }
  8686. if (mesh && mesh.subMeshes) {
  8687. // Submeshes Octrees
  8688. var len;
  8689. var subMeshes;
  8690. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8691. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8692. len = intersections.length;
  8693. subMeshes = intersections.data;
  8694. }
  8695. else {
  8696. subMeshes = mesh.subMeshes;
  8697. len = subMeshes.length;
  8698. }
  8699. for (var subIndex = 0; subIndex < len; subIndex++) {
  8700. var subMesh = subMeshes[subIndex];
  8701. this._evaluateSubMesh(subMesh, mesh);
  8702. }
  8703. }
  8704. };
  8705. Scene.prototype.updateTransformMatrix = function (force) {
  8706. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8707. };
  8708. Scene.prototype._renderForCamera = function (camera) {
  8709. var engine = this._engine;
  8710. this.activeCamera = camera;
  8711. if (!this.activeCamera)
  8712. throw new Error("Active camera not set");
  8713. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8714. // Viewport
  8715. engine.setViewport(this.activeCamera.viewport);
  8716. // Camera
  8717. this._renderId++;
  8718. this.updateTransformMatrix();
  8719. if (this.beforeCameraRender) {
  8720. this.beforeCameraRender(this.activeCamera);
  8721. }
  8722. // Meshes
  8723. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8724. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8725. this._evaluateActiveMeshes();
  8726. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8727. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8728. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8729. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8730. skeleton.prepare();
  8731. }
  8732. // Render targets
  8733. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8734. if (this.renderTargetsEnabled) {
  8735. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8736. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8737. var renderTarget = this._renderTargets.data[renderIndex];
  8738. if (renderTarget._shouldRender()) {
  8739. this._renderId++;
  8740. renderTarget.render(false, this.dumpNextRenderTargets);
  8741. }
  8742. }
  8743. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8744. this._renderId++;
  8745. }
  8746. if (this._renderTargets.length > 0) {
  8747. engine.restoreDefaultFramebuffer();
  8748. }
  8749. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8750. // Prepare Frame
  8751. this.postProcessManager._prepareFrame();
  8752. var beforeRenderDate = BABYLON.Tools.Now;
  8753. // Backgrounds
  8754. if (this.layers.length) {
  8755. engine.setDepthBuffer(false);
  8756. var layerIndex;
  8757. var layer;
  8758. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8759. layer = this.layers[layerIndex];
  8760. if (layer.isBackground) {
  8761. layer.render();
  8762. }
  8763. }
  8764. engine.setDepthBuffer(true);
  8765. }
  8766. // Render
  8767. BABYLON.Tools.StartPerformanceCounter("Main render");
  8768. this._renderingManager.render(null, null, true, true);
  8769. BABYLON.Tools.EndPerformanceCounter("Main render");
  8770. // Bounding boxes
  8771. this._boundingBoxRenderer.render();
  8772. // Lens flares
  8773. if (this.lensFlaresEnabled) {
  8774. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8775. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8776. this.lensFlareSystems[lensFlareSystemIndex].render();
  8777. }
  8778. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8779. }
  8780. // Foregrounds
  8781. if (this.layers.length) {
  8782. engine.setDepthBuffer(false);
  8783. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8784. layer = this.layers[layerIndex];
  8785. if (!layer.isBackground) {
  8786. layer.render();
  8787. }
  8788. }
  8789. engine.setDepthBuffer(true);
  8790. }
  8791. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8792. // Finalize frame
  8793. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8794. // Update camera
  8795. this.activeCamera._updateFromScene();
  8796. // Reset some special arrays
  8797. this._renderTargets.reset();
  8798. if (this.afterCameraRender) {
  8799. this.afterCameraRender(this.activeCamera);
  8800. }
  8801. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8802. };
  8803. Scene.prototype._processSubCameras = function (camera) {
  8804. if (camera.subCameras.length === 0) {
  8805. this._renderForCamera(camera);
  8806. return;
  8807. }
  8808. for (var index = 0; index < camera.subCameras.length; index++) {
  8809. this._renderForCamera(camera.subCameras[index]);
  8810. }
  8811. this.activeCamera = camera;
  8812. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8813. // Update camera
  8814. this.activeCamera._updateFromScene();
  8815. };
  8816. Scene.prototype._checkIntersections = function () {
  8817. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8818. var sourceMesh = this._meshesForIntersections.data[index];
  8819. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8820. var action = sourceMesh.actionManager.actions[actionIndex];
  8821. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8822. var parameters = action.getTriggerParameter();
  8823. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8824. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8825. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8826. if (areIntersecting && currentIntersectionInProgress === -1) {
  8827. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8828. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8829. sourceMesh._intersectionsInProgress.push(otherMesh);
  8830. }
  8831. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8832. sourceMesh._intersectionsInProgress.push(otherMesh);
  8833. }
  8834. }
  8835. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8836. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8837. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8838. if (indexOfOther > -1) {
  8839. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8840. }
  8841. }
  8842. }
  8843. }
  8844. }
  8845. };
  8846. Scene.prototype.render = function () {
  8847. var startDate = BABYLON.Tools.Now;
  8848. this._particlesDuration = 0;
  8849. this._spritesDuration = 0;
  8850. this._activeParticles = 0;
  8851. this._renderDuration = 0;
  8852. this._renderTargetsDuration = 0;
  8853. this._evaluateActiveMeshesDuration = 0;
  8854. this._totalVertices = 0;
  8855. this._activeVertices = 0;
  8856. this._activeBones = 0;
  8857. this.getEngine().resetDrawCalls();
  8858. this._meshesForIntersections.reset();
  8859. this.resetCachedMaterial();
  8860. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8861. // Actions
  8862. if (this.actionManager) {
  8863. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8864. }
  8865. //Simplification Queue
  8866. if (!this.simplificationQueue.running) {
  8867. this.simplificationQueue.executeNext();
  8868. }
  8869. // Before render
  8870. if (this.beforeRender) {
  8871. this.beforeRender();
  8872. }
  8873. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8874. this._onBeforeRenderCallbacks[callbackIndex]();
  8875. }
  8876. // Animations
  8877. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8878. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8879. this._animate();
  8880. // Physics
  8881. if (this._physicsEngine) {
  8882. BABYLON.Tools.StartPerformanceCounter("Physics");
  8883. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8884. BABYLON.Tools.EndPerformanceCounter("Physics");
  8885. }
  8886. // Customs render targets
  8887. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8888. var engine = this.getEngine();
  8889. var currentActiveCamera = this.activeCamera;
  8890. if (this.renderTargetsEnabled) {
  8891. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8892. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8893. var renderTarget = this.customRenderTargets[customIndex];
  8894. if (renderTarget._shouldRender()) {
  8895. this._renderId++;
  8896. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8897. if (!this.activeCamera)
  8898. throw new Error("Active camera not set");
  8899. // Viewport
  8900. engine.setViewport(this.activeCamera.viewport);
  8901. // Camera
  8902. this.updateTransformMatrix();
  8903. renderTarget.render(false, this.dumpNextRenderTargets);
  8904. }
  8905. }
  8906. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8907. this._renderId++;
  8908. }
  8909. if (this.customRenderTargets.length > 0) {
  8910. engine.restoreDefaultFramebuffer();
  8911. }
  8912. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8913. this.activeCamera = currentActiveCamera;
  8914. // Procedural textures
  8915. if (this.proceduralTexturesEnabled) {
  8916. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8917. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8918. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8919. if (proceduralTexture._shouldRender()) {
  8920. proceduralTexture.render();
  8921. }
  8922. }
  8923. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8924. }
  8925. // Clear
  8926. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8927. // Shadows
  8928. if (this.shadowsEnabled) {
  8929. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8930. var light = this.lights[lightIndex];
  8931. var shadowGenerator = light.getShadowGenerator();
  8932. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8933. this._renderTargets.push(shadowGenerator.getShadowMap());
  8934. }
  8935. }
  8936. }
  8937. // Depth renderer
  8938. if (this._depthRenderer) {
  8939. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8940. }
  8941. // RenderPipeline
  8942. this.postProcessRenderPipelineManager.update();
  8943. // Multi-cameras?
  8944. if (this.activeCameras.length > 0) {
  8945. var currentRenderId = this._renderId;
  8946. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8947. this._renderId = currentRenderId;
  8948. this._processSubCameras(this.activeCameras[cameraIndex]);
  8949. }
  8950. }
  8951. else {
  8952. if (!this.activeCamera) {
  8953. throw new Error("No camera defined");
  8954. }
  8955. this._processSubCameras(this.activeCamera);
  8956. }
  8957. // Intersection checks
  8958. this._checkIntersections();
  8959. // Update the audio listener attached to the camera
  8960. this._updateAudioParameters();
  8961. // After render
  8962. if (this.afterRender) {
  8963. this.afterRender();
  8964. }
  8965. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8966. this._onAfterRenderCallbacks[callbackIndex]();
  8967. }
  8968. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8969. this._toBeDisposed.data[index].dispose();
  8970. this._toBeDisposed[index] = null;
  8971. }
  8972. this._toBeDisposed.reset();
  8973. if (this.dumpNextRenderTargets) {
  8974. this.dumpNextRenderTargets = false;
  8975. }
  8976. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8977. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8978. };
  8979. Scene.prototype._updateAudioParameters = function () {
  8980. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8981. return;
  8982. }
  8983. var listeningCamera;
  8984. var audioEngine = BABYLON.Engine.audioEngine;
  8985. if (this.activeCameras.length > 0) {
  8986. listeningCamera = this.activeCameras[0];
  8987. }
  8988. else {
  8989. listeningCamera = this.activeCamera;
  8990. }
  8991. if (listeningCamera && audioEngine.canUseWebAudio) {
  8992. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8993. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8994. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8995. cameraDirection.normalize();
  8996. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8997. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8998. var sound = this.mainSoundTrack.soundCollection[i];
  8999. if (sound.useCustomAttenuation) {
  9000. sound.updateDistanceFromListener();
  9001. }
  9002. }
  9003. for (i = 0; i < this.soundTracks.length; i++) {
  9004. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9005. sound = this.soundTracks[i].soundCollection[j];
  9006. if (sound.useCustomAttenuation) {
  9007. sound.updateDistanceFromListener();
  9008. }
  9009. }
  9010. }
  9011. }
  9012. };
  9013. Object.defineProperty(Scene.prototype, "audioEnabled", {
  9014. // Audio
  9015. get: function () {
  9016. return this._audioEnabled;
  9017. },
  9018. set: function (value) {
  9019. this._audioEnabled = value;
  9020. if (this._audioEnabled) {
  9021. this._enableAudio();
  9022. }
  9023. else {
  9024. this._disableAudio();
  9025. }
  9026. },
  9027. enumerable: true,
  9028. configurable: true
  9029. });
  9030. Scene.prototype._disableAudio = function () {
  9031. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9032. this.mainSoundTrack.soundCollection[i].pause();
  9033. }
  9034. for (i = 0; i < this.soundTracks.length; i++) {
  9035. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9036. this.soundTracks[i].soundCollection[j].pause();
  9037. }
  9038. }
  9039. };
  9040. Scene.prototype._enableAudio = function () {
  9041. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  9042. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  9043. this.mainSoundTrack.soundCollection[i].play();
  9044. }
  9045. }
  9046. for (i = 0; i < this.soundTracks.length; i++) {
  9047. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  9048. if (this.soundTracks[i].soundCollection[j].isPaused) {
  9049. this.soundTracks[i].soundCollection[j].play();
  9050. }
  9051. }
  9052. }
  9053. };
  9054. Object.defineProperty(Scene.prototype, "headphone", {
  9055. get: function () {
  9056. return this._headphone;
  9057. },
  9058. set: function (value) {
  9059. this._headphone = value;
  9060. if (this._headphone) {
  9061. this._switchAudioModeForHeadphones();
  9062. }
  9063. else {
  9064. this._switchAudioModeForNormalSpeakers();
  9065. }
  9066. },
  9067. enumerable: true,
  9068. configurable: true
  9069. });
  9070. Scene.prototype._switchAudioModeForHeadphones = function () {
  9071. this.mainSoundTrack.switchPanningModelToHRTF();
  9072. for (var i = 0; i < this.soundTracks.length; i++) {
  9073. this.soundTracks[i].switchPanningModelToHRTF();
  9074. }
  9075. };
  9076. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  9077. this.mainSoundTrack.switchPanningModelToEqualPower();
  9078. for (var i = 0; i < this.soundTracks.length; i++) {
  9079. this.soundTracks[i].switchPanningModelToEqualPower();
  9080. }
  9081. };
  9082. Scene.prototype.enableDepthRenderer = function () {
  9083. if (this._depthRenderer) {
  9084. return this._depthRenderer;
  9085. }
  9086. this._depthRenderer = new BABYLON.DepthRenderer(this);
  9087. return this._depthRenderer;
  9088. };
  9089. Scene.prototype.disableDepthRenderer = function () {
  9090. if (!this._depthRenderer) {
  9091. return;
  9092. }
  9093. this._depthRenderer.dispose();
  9094. this._depthRenderer = null;
  9095. };
  9096. Scene.prototype.dispose = function () {
  9097. this.beforeRender = null;
  9098. this.afterRender = null;
  9099. this.skeletons = [];
  9100. this._boundingBoxRenderer.dispose();
  9101. if (this._depthRenderer) {
  9102. this._depthRenderer.dispose();
  9103. }
  9104. // Debug layer
  9105. this.debugLayer.hide();
  9106. // Events
  9107. if (this.onDispose) {
  9108. this.onDispose();
  9109. }
  9110. this._onBeforeRenderCallbacks = [];
  9111. this._onAfterRenderCallbacks = [];
  9112. this.detachControl();
  9113. // Release sounds & sounds tracks
  9114. this.disposeSounds();
  9115. // Detach cameras
  9116. var canvas = this._engine.getRenderingCanvas();
  9117. var index;
  9118. for (index = 0; index < this.cameras.length; index++) {
  9119. this.cameras[index].detachControl(canvas);
  9120. }
  9121. while (this.lights.length) {
  9122. this.lights[0].dispose();
  9123. }
  9124. while (this.meshes.length) {
  9125. this.meshes[0].dispose(true);
  9126. }
  9127. while (this.cameras.length) {
  9128. this.cameras[0].dispose();
  9129. }
  9130. while (this.materials.length) {
  9131. this.materials[0].dispose();
  9132. }
  9133. while (this.particleSystems.length) {
  9134. this.particleSystems[0].dispose();
  9135. }
  9136. while (this.spriteManagers.length) {
  9137. this.spriteManagers[0].dispose();
  9138. }
  9139. while (this.layers.length) {
  9140. this.layers[0].dispose();
  9141. }
  9142. while (this.textures.length) {
  9143. this.textures[0].dispose();
  9144. }
  9145. // Post-processes
  9146. this.postProcessManager.dispose();
  9147. // Physics
  9148. if (this._physicsEngine) {
  9149. this.disablePhysicsEngine();
  9150. }
  9151. // Remove from engine
  9152. index = this._engine.scenes.indexOf(this);
  9153. if (index > -1) {
  9154. this._engine.scenes.splice(index, 1);
  9155. }
  9156. this._engine.wipeCaches();
  9157. };
  9158. // Release sounds & sounds tracks
  9159. Scene.prototype.disposeSounds = function () {
  9160. this.mainSoundTrack.dispose();
  9161. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  9162. this.soundTracks[scIndex].dispose();
  9163. }
  9164. };
  9165. // Collisions
  9166. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9167. if (excludedMesh === void 0) { excludedMesh = null; }
  9168. position.divideToRef(collider.radius, this._scaledPosition);
  9169. velocity.divideToRef(collider.radius, this._scaledVelocity);
  9170. collider.retry = 0;
  9171. collider.initialVelocity = this._scaledVelocity;
  9172. collider.initialPosition = this._scaledPosition;
  9173. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  9174. finalPosition.multiplyInPlace(collider.radius);
  9175. };
  9176. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9177. if (excludedMesh === void 0) { excludedMesh = null; }
  9178. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9179. if (collider.retry >= maximumRetry) {
  9180. finalPosition.copyFrom(position);
  9181. return;
  9182. }
  9183. collider._initialize(position, velocity, closeDistance);
  9184. for (var index = 0; index < this.meshes.length; index++) {
  9185. var mesh = this.meshes[index];
  9186. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9187. mesh._checkCollision(collider);
  9188. }
  9189. }
  9190. if (!collider.collisionFound) {
  9191. position.addToRef(velocity, finalPosition);
  9192. return;
  9193. }
  9194. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9195. collider._getResponse(position, velocity);
  9196. }
  9197. if (velocity.length() <= closeDistance) {
  9198. finalPosition.copyFrom(position);
  9199. return;
  9200. }
  9201. collider.retry++;
  9202. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9203. };
  9204. // Octrees
  9205. Scene.prototype.getWorldExtends = function () {
  9206. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9207. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9208. for (var index = 0; index < this.meshes.length; index++) {
  9209. var mesh = this.meshes[index];
  9210. mesh.computeWorldMatrix(true);
  9211. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9212. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9213. BABYLON.Tools.CheckExtends(minBox, min, max);
  9214. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9215. }
  9216. return {
  9217. min: min,
  9218. max: max
  9219. };
  9220. };
  9221. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9222. if (maxCapacity === void 0) { maxCapacity = 64; }
  9223. if (maxDepth === void 0) { maxDepth = 2; }
  9224. if (!this._selectionOctree) {
  9225. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9226. }
  9227. var worldExtends = this.getWorldExtends();
  9228. // Update octree
  9229. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9230. return this._selectionOctree;
  9231. };
  9232. // Picking
  9233. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9234. var engine = this._engine;
  9235. if (!camera) {
  9236. if (!this.activeCamera)
  9237. throw new Error("Active camera not set");
  9238. camera = this.activeCamera;
  9239. }
  9240. var cameraViewport = camera.viewport;
  9241. var viewport = cameraViewport.toGlobal(engine);
  9242. // Moving coordinates to local viewport world
  9243. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9244. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9245. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9246. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9247. };
  9248. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9249. var pickingInfo = null;
  9250. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9251. var mesh = this.meshes[meshIndex];
  9252. if (predicate) {
  9253. if (!predicate(mesh)) {
  9254. continue;
  9255. }
  9256. }
  9257. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9258. continue;
  9259. }
  9260. var world = mesh.getWorldMatrix();
  9261. var ray = rayFunction(world);
  9262. var result = mesh.intersects(ray, fastCheck);
  9263. if (!result || !result.hit)
  9264. continue;
  9265. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9266. continue;
  9267. pickingInfo = result;
  9268. if (fastCheck) {
  9269. break;
  9270. }
  9271. }
  9272. return pickingInfo || new BABYLON.PickingInfo();
  9273. };
  9274. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9275. var _this = this;
  9276. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9277. /// <param name="x">X position on screen</param>
  9278. /// <param name="y">Y position on screen</param>
  9279. /// <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>
  9280. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9281. /// <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>
  9282. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9283. };
  9284. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9285. var _this = this;
  9286. return this._internalPick(function (world) {
  9287. if (!_this._pickWithRayInverseMatrix) {
  9288. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9289. }
  9290. world.invertToRef(_this._pickWithRayInverseMatrix);
  9291. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9292. }, predicate, fastCheck);
  9293. };
  9294. Scene.prototype.setPointerOverMesh = function (mesh) {
  9295. if (this._pointerOverMesh === mesh) {
  9296. return;
  9297. }
  9298. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9299. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9300. }
  9301. this._pointerOverMesh = mesh;
  9302. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9303. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9304. }
  9305. };
  9306. Scene.prototype.getPointerOverMesh = function () {
  9307. return this._pointerOverMesh;
  9308. };
  9309. // Physics
  9310. Scene.prototype.getPhysicsEngine = function () {
  9311. return this._physicsEngine;
  9312. };
  9313. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9314. if (this._physicsEngine) {
  9315. return true;
  9316. }
  9317. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9318. if (!this._physicsEngine.isSupported()) {
  9319. this._physicsEngine = null;
  9320. return false;
  9321. }
  9322. this._physicsEngine._initialize(gravity);
  9323. return true;
  9324. };
  9325. Scene.prototype.disablePhysicsEngine = function () {
  9326. if (!this._physicsEngine) {
  9327. return;
  9328. }
  9329. this._physicsEngine.dispose();
  9330. this._physicsEngine = undefined;
  9331. };
  9332. Scene.prototype.isPhysicsEnabled = function () {
  9333. return this._physicsEngine !== undefined;
  9334. };
  9335. Scene.prototype.setGravity = function (gravity) {
  9336. if (!this._physicsEngine) {
  9337. return;
  9338. }
  9339. this._physicsEngine._setGravity(gravity);
  9340. };
  9341. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9342. if (parts.parts) {
  9343. options = parts;
  9344. parts = parts.parts;
  9345. }
  9346. if (!this._physicsEngine) {
  9347. return null;
  9348. }
  9349. for (var index = 0; index < parts.length; index++) {
  9350. var mesh = parts[index].mesh;
  9351. mesh._physicImpostor = parts[index].impostor;
  9352. mesh._physicsMass = options.mass / parts.length;
  9353. mesh._physicsFriction = options.friction;
  9354. mesh._physicRestitution = options.restitution;
  9355. }
  9356. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9357. };
  9358. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9359. for (var index = 0; index < compound.parts.length; index++) {
  9360. var mesh = compound.parts[index].mesh;
  9361. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9362. this._physicsEngine._unregisterMesh(mesh);
  9363. }
  9364. };
  9365. // Misc.
  9366. Scene.prototype.createDefaultCameraOrLight = function () {
  9367. // Light
  9368. if (this.lights.length === 0) {
  9369. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9370. }
  9371. // Camera
  9372. if (!this.activeCamera) {
  9373. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9374. // Compute position
  9375. var worldExtends = this.getWorldExtends();
  9376. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9377. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9378. camera.setTarget(worldCenter);
  9379. this.activeCamera = camera;
  9380. }
  9381. };
  9382. // Tags
  9383. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9384. if (tagsQuery === undefined) {
  9385. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9386. return list;
  9387. }
  9388. var listByTags = [];
  9389. forEach = forEach || (function (item) {
  9390. return;
  9391. });
  9392. for (var i in list) {
  9393. var item = list[i];
  9394. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9395. listByTags.push(item);
  9396. forEach(item);
  9397. }
  9398. }
  9399. return listByTags;
  9400. };
  9401. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9402. return this._getByTags(this.meshes, tagsQuery, forEach);
  9403. };
  9404. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9405. return this._getByTags(this.cameras, tagsQuery, forEach);
  9406. };
  9407. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9408. return this._getByTags(this.lights, tagsQuery, forEach);
  9409. };
  9410. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9411. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9412. };
  9413. // Statics
  9414. Scene._FOGMODE_NONE = 0;
  9415. Scene._FOGMODE_EXP = 1;
  9416. Scene._FOGMODE_EXP2 = 2;
  9417. Scene._FOGMODE_LINEAR = 3;
  9418. Scene.MinDeltaTime = 1.0;
  9419. Scene.MaxDeltaTime = 1000.0;
  9420. return Scene;
  9421. })();
  9422. BABYLON.Scene = Scene;
  9423. })(BABYLON || (BABYLON = {}));
  9424. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9425. (function (BABYLON) {
  9426. var VertexBuffer = (function () {
  9427. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9428. if (engine instanceof BABYLON.Mesh) {
  9429. this._engine = engine.getScene().getEngine();
  9430. }
  9431. else {
  9432. this._engine = engine;
  9433. }
  9434. this._updatable = updatable;
  9435. this._data = data;
  9436. if (!postponeInternalCreation) {
  9437. this.create();
  9438. }
  9439. this._kind = kind;
  9440. if (stride) {
  9441. this._strideSize = stride;
  9442. return;
  9443. }
  9444. switch (kind) {
  9445. case VertexBuffer.PositionKind:
  9446. this._strideSize = 3;
  9447. break;
  9448. case VertexBuffer.NormalKind:
  9449. this._strideSize = 3;
  9450. break;
  9451. case VertexBuffer.UVKind:
  9452. this._strideSize = 2;
  9453. break;
  9454. case VertexBuffer.UV2Kind:
  9455. this._strideSize = 2;
  9456. break;
  9457. case VertexBuffer.ColorKind:
  9458. this._strideSize = 4;
  9459. break;
  9460. case VertexBuffer.MatricesIndicesKind:
  9461. this._strideSize = 4;
  9462. break;
  9463. case VertexBuffer.MatricesWeightsKind:
  9464. this._strideSize = 4;
  9465. break;
  9466. }
  9467. }
  9468. // Properties
  9469. VertexBuffer.prototype.isUpdatable = function () {
  9470. return this._updatable;
  9471. };
  9472. VertexBuffer.prototype.getData = function () {
  9473. return this._data;
  9474. };
  9475. VertexBuffer.prototype.getBuffer = function () {
  9476. return this._buffer;
  9477. };
  9478. VertexBuffer.prototype.getStrideSize = function () {
  9479. return this._strideSize;
  9480. };
  9481. // Methods
  9482. VertexBuffer.prototype.create = function (data) {
  9483. if (!data && this._buffer) {
  9484. return; // nothing to do
  9485. }
  9486. data = data || this._data;
  9487. if (!this._buffer) {
  9488. if (this._updatable) {
  9489. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9490. }
  9491. else {
  9492. this._buffer = this._engine.createVertexBuffer(data);
  9493. }
  9494. }
  9495. if (this._updatable) {
  9496. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9497. this._data = data;
  9498. }
  9499. };
  9500. VertexBuffer.prototype.update = function (data) {
  9501. this.create(data);
  9502. };
  9503. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9504. if (!this._buffer) {
  9505. return;
  9506. }
  9507. if (this._updatable) {
  9508. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9509. this._data = null;
  9510. }
  9511. };
  9512. VertexBuffer.prototype.dispose = function () {
  9513. if (!this._buffer) {
  9514. return;
  9515. }
  9516. if (this._engine._releaseBuffer(this._buffer)) {
  9517. this._buffer = null;
  9518. }
  9519. };
  9520. Object.defineProperty(VertexBuffer, "PositionKind", {
  9521. get: function () {
  9522. return VertexBuffer._PositionKind;
  9523. },
  9524. enumerable: true,
  9525. configurable: true
  9526. });
  9527. Object.defineProperty(VertexBuffer, "NormalKind", {
  9528. get: function () {
  9529. return VertexBuffer._NormalKind;
  9530. },
  9531. enumerable: true,
  9532. configurable: true
  9533. });
  9534. Object.defineProperty(VertexBuffer, "UVKind", {
  9535. get: function () {
  9536. return VertexBuffer._UVKind;
  9537. },
  9538. enumerable: true,
  9539. configurable: true
  9540. });
  9541. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9542. get: function () {
  9543. return VertexBuffer._UV2Kind;
  9544. },
  9545. enumerable: true,
  9546. configurable: true
  9547. });
  9548. Object.defineProperty(VertexBuffer, "ColorKind", {
  9549. get: function () {
  9550. return VertexBuffer._ColorKind;
  9551. },
  9552. enumerable: true,
  9553. configurable: true
  9554. });
  9555. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9556. get: function () {
  9557. return VertexBuffer._MatricesIndicesKind;
  9558. },
  9559. enumerable: true,
  9560. configurable: true
  9561. });
  9562. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9563. get: function () {
  9564. return VertexBuffer._MatricesWeightsKind;
  9565. },
  9566. enumerable: true,
  9567. configurable: true
  9568. });
  9569. // Enums
  9570. VertexBuffer._PositionKind = "position";
  9571. VertexBuffer._NormalKind = "normal";
  9572. VertexBuffer._UVKind = "uv";
  9573. VertexBuffer._UV2Kind = "uv2";
  9574. VertexBuffer._ColorKind = "color";
  9575. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9576. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9577. return VertexBuffer;
  9578. })();
  9579. BABYLON.VertexBuffer = VertexBuffer;
  9580. })(BABYLON || (BABYLON = {}));
  9581. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9582. var BABYLON;
  9583. (function (BABYLON) {
  9584. var AbstractMesh = (function (_super) {
  9585. __extends(AbstractMesh, _super);
  9586. function AbstractMesh(name, scene) {
  9587. _super.call(this, name, scene);
  9588. // Properties
  9589. this.definedFacingForward = true; // orientation for POV movement & rotation
  9590. this.position = new BABYLON.Vector3(0, 0, 0);
  9591. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9592. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9593. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9594. this.visibility = 1.0;
  9595. this.alphaIndex = Number.MAX_VALUE;
  9596. this.infiniteDistance = false;
  9597. this.isVisible = true;
  9598. this.isPickable = true;
  9599. this.showBoundingBox = false;
  9600. this.showSubMeshesBoundingBox = false;
  9601. this.onDispose = null;
  9602. this.checkCollisions = false;
  9603. this.isBlocker = false;
  9604. this.renderingGroupId = 0;
  9605. this.receiveShadows = false;
  9606. this.renderOutline = false;
  9607. this.outlineColor = BABYLON.Color3.Red();
  9608. this.outlineWidth = 0.02;
  9609. this.renderOverlay = false;
  9610. this.overlayColor = BABYLON.Color3.Red();
  9611. this.overlayAlpha = 0.5;
  9612. this.hasVertexAlpha = false;
  9613. this.useVertexColors = true;
  9614. this.applyFog = true;
  9615. this.useOctreeForRenderingSelection = true;
  9616. this.useOctreeForPicking = true;
  9617. this.useOctreeForCollisions = true;
  9618. this.layerMask = 0xFFFFFFFF;
  9619. // Physics
  9620. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9621. // Collisions
  9622. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9623. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9624. this._collider = new BABYLON.Collider();
  9625. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9626. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9627. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9628. // Cache
  9629. this._localScaling = BABYLON.Matrix.Zero();
  9630. this._localRotation = BABYLON.Matrix.Zero();
  9631. this._localTranslation = BABYLON.Matrix.Zero();
  9632. this._localBillboard = BABYLON.Matrix.Zero();
  9633. this._localPivotScaling = BABYLON.Matrix.Zero();
  9634. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9635. this._localWorld = BABYLON.Matrix.Zero();
  9636. this._worldMatrix = BABYLON.Matrix.Zero();
  9637. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9638. this._absolutePosition = BABYLON.Vector3.Zero();
  9639. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9640. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9641. this._isDirty = false;
  9642. this._pivotMatrix = BABYLON.Matrix.Identity();
  9643. this._isDisposed = false;
  9644. this._renderId = 0;
  9645. this._intersectionsInProgress = new Array();
  9646. this._onAfterWorldMatrixUpdate = new Array();
  9647. scene.meshes.push(this);
  9648. }
  9649. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9650. get: function () {
  9651. return AbstractMesh._BILLBOARDMODE_NONE;
  9652. },
  9653. enumerable: true,
  9654. configurable: true
  9655. });
  9656. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9657. get: function () {
  9658. return AbstractMesh._BILLBOARDMODE_X;
  9659. },
  9660. enumerable: true,
  9661. configurable: true
  9662. });
  9663. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9664. get: function () {
  9665. return AbstractMesh._BILLBOARDMODE_Y;
  9666. },
  9667. enumerable: true,
  9668. configurable: true
  9669. });
  9670. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9671. get: function () {
  9672. return AbstractMesh._BILLBOARDMODE_Z;
  9673. },
  9674. enumerable: true,
  9675. configurable: true
  9676. });
  9677. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9678. get: function () {
  9679. return AbstractMesh._BILLBOARDMODE_ALL;
  9680. },
  9681. enumerable: true,
  9682. configurable: true
  9683. });
  9684. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9685. // Methods
  9686. get: function () {
  9687. return false;
  9688. },
  9689. enumerable: true,
  9690. configurable: true
  9691. });
  9692. AbstractMesh.prototype.getLOD = function (camera) {
  9693. return this;
  9694. };
  9695. AbstractMesh.prototype.getTotalVertices = function () {
  9696. return 0;
  9697. };
  9698. AbstractMesh.prototype.getIndices = function () {
  9699. return null;
  9700. };
  9701. AbstractMesh.prototype.getVerticesData = function (kind) {
  9702. return null;
  9703. };
  9704. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9705. return false;
  9706. };
  9707. AbstractMesh.prototype.getBoundingInfo = function () {
  9708. if (this._masterMesh) {
  9709. return this._masterMesh.getBoundingInfo();
  9710. }
  9711. if (!this._boundingInfo) {
  9712. this._updateBoundingInfo();
  9713. }
  9714. return this._boundingInfo;
  9715. };
  9716. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9717. get: function () {
  9718. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9719. },
  9720. enumerable: true,
  9721. configurable: true
  9722. });
  9723. AbstractMesh.prototype._preActivate = function () {
  9724. };
  9725. AbstractMesh.prototype._activate = function (renderId) {
  9726. this._renderId = renderId;
  9727. };
  9728. AbstractMesh.prototype.getWorldMatrix = function () {
  9729. if (this._masterMesh) {
  9730. return this._masterMesh.getWorldMatrix();
  9731. }
  9732. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9733. this.computeWorldMatrix();
  9734. }
  9735. return this._worldMatrix;
  9736. };
  9737. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9738. get: function () {
  9739. return this._worldMatrix;
  9740. },
  9741. enumerable: true,
  9742. configurable: true
  9743. });
  9744. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9745. get: function () {
  9746. return this._absolutePosition;
  9747. },
  9748. enumerable: true,
  9749. configurable: true
  9750. });
  9751. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9752. if (!this.rotationQuaternion) {
  9753. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9754. this.rotation = BABYLON.Vector3.Zero();
  9755. }
  9756. if (!space || space == 0 /* LOCAL */) {
  9757. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9758. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9759. }
  9760. else {
  9761. if (this.parent) {
  9762. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9763. invertParentWorldMatrix.invert();
  9764. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9765. }
  9766. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9767. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9768. }
  9769. };
  9770. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9771. var displacementVector = axis.scale(distance);
  9772. if (!space || space == 0 /* LOCAL */) {
  9773. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9774. this.setPositionWithLocalVector(tempV3);
  9775. }
  9776. else {
  9777. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9778. }
  9779. };
  9780. AbstractMesh.prototype.getAbsolutePosition = function () {
  9781. this.computeWorldMatrix();
  9782. return this._absolutePosition;
  9783. };
  9784. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9785. if (!absolutePosition) {
  9786. return;
  9787. }
  9788. var absolutePositionX;
  9789. var absolutePositionY;
  9790. var absolutePositionZ;
  9791. if (absolutePosition.x === undefined) {
  9792. if (arguments.length < 3) {
  9793. return;
  9794. }
  9795. absolutePositionX = arguments[0];
  9796. absolutePositionY = arguments[1];
  9797. absolutePositionZ = arguments[2];
  9798. }
  9799. else {
  9800. absolutePositionX = absolutePosition.x;
  9801. absolutePositionY = absolutePosition.y;
  9802. absolutePositionZ = absolutePosition.z;
  9803. }
  9804. if (this.parent) {
  9805. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9806. invertParentWorldMatrix.invert();
  9807. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9808. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9809. }
  9810. else {
  9811. this.position.x = absolutePositionX;
  9812. this.position.y = absolutePositionY;
  9813. this.position.z = absolutePositionZ;
  9814. }
  9815. };
  9816. // ================================== Point of View Movement =================================
  9817. /**
  9818. * Perform relative position change from the point of view of behind the front of the mesh.
  9819. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9820. * Supports definition of mesh facing forward or backward.
  9821. * @param {number} amountRight
  9822. * @param {number} amountUp
  9823. * @param {number} amountForward
  9824. */
  9825. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9826. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9827. };
  9828. /**
  9829. * Calculate relative position change from the point of view of behind the front of the mesh.
  9830. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9831. * Supports definition of mesh facing forward or backward.
  9832. * @param {number} amountRight
  9833. * @param {number} amountUp
  9834. * @param {number} amountForward
  9835. */
  9836. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9837. var rotMatrix = new BABYLON.Matrix();
  9838. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9839. rotQuaternion.toRotationMatrix(rotMatrix);
  9840. var translationDelta = BABYLON.Vector3.Zero();
  9841. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9842. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9843. return translationDelta;
  9844. };
  9845. // ================================== Point of View Rotation =================================
  9846. /**
  9847. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9848. * Supports definition of mesh facing forward or backward.
  9849. * @param {number} flipBack
  9850. * @param {number} twirlClockwise
  9851. * @param {number} tiltRight
  9852. */
  9853. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9854. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9855. };
  9856. /**
  9857. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9858. * Supports definition of mesh facing forward or backward.
  9859. * @param {number} flipBack
  9860. * @param {number} twirlClockwise
  9861. * @param {number} tiltRight
  9862. */
  9863. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9864. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9865. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9866. };
  9867. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9868. this._pivotMatrix = matrix;
  9869. this._cache.pivotMatrixUpdated = true;
  9870. };
  9871. AbstractMesh.prototype.getPivotMatrix = function () {
  9872. return this._pivotMatrix;
  9873. };
  9874. AbstractMesh.prototype._isSynchronized = function () {
  9875. if (this._isDirty) {
  9876. return false;
  9877. }
  9878. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9879. return false;
  9880. if (this._cache.pivotMatrixUpdated) {
  9881. return false;
  9882. }
  9883. if (this.infiniteDistance) {
  9884. return false;
  9885. }
  9886. if (!this._cache.position.equals(this.position))
  9887. return false;
  9888. if (this.rotationQuaternion) {
  9889. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9890. return false;
  9891. }
  9892. else {
  9893. if (!this._cache.rotation.equals(this.rotation))
  9894. return false;
  9895. }
  9896. if (!this._cache.scaling.equals(this.scaling))
  9897. return false;
  9898. return true;
  9899. };
  9900. AbstractMesh.prototype._initCache = function () {
  9901. _super.prototype._initCache.call(this);
  9902. this._cache.localMatrixUpdated = false;
  9903. this._cache.position = BABYLON.Vector3.Zero();
  9904. this._cache.scaling = BABYLON.Vector3.Zero();
  9905. this._cache.rotation = BABYLON.Vector3.Zero();
  9906. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9907. };
  9908. AbstractMesh.prototype.markAsDirty = function (property) {
  9909. if (property === "rotation") {
  9910. this.rotationQuaternion = null;
  9911. }
  9912. this._currentRenderId = Number.MAX_VALUE;
  9913. this._isDirty = true;
  9914. };
  9915. AbstractMesh.prototype._updateBoundingInfo = function () {
  9916. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9917. this._boundingInfo._update(this.worldMatrixFromCache);
  9918. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9919. };
  9920. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9921. if (!this.subMeshes) {
  9922. return;
  9923. }
  9924. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9925. var subMesh = this.subMeshes[subIndex];
  9926. subMesh.updateBoundingInfo(matrix);
  9927. }
  9928. };
  9929. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9930. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9931. return this._worldMatrix;
  9932. }
  9933. this._cache.position.copyFrom(this.position);
  9934. this._cache.scaling.copyFrom(this.scaling);
  9935. this._cache.pivotMatrixUpdated = false;
  9936. this._currentRenderId = this.getScene().getRenderId();
  9937. this._isDirty = false;
  9938. // Scaling
  9939. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9940. // Rotation
  9941. if (this.rotationQuaternion) {
  9942. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9943. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9944. }
  9945. else {
  9946. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9947. this._cache.rotation.copyFrom(this.rotation);
  9948. }
  9949. // Translation
  9950. if (this.infiniteDistance && !this.parent) {
  9951. var camera = this.getScene().activeCamera;
  9952. var cameraWorldMatrix = camera.getWorldMatrix();
  9953. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9954. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9955. }
  9956. else {
  9957. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9958. }
  9959. // Composing transformations
  9960. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9961. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9962. // Billboarding
  9963. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9964. var localPosition = this.position.clone();
  9965. var zero = this.getScene().activeCamera.position.clone();
  9966. if (this.parent && this.parent.position) {
  9967. localPosition.addInPlace(this.parent.position);
  9968. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9969. }
  9970. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9971. zero = this.getScene().activeCamera.position;
  9972. }
  9973. else {
  9974. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9975. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9976. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9977. zero.y = localPosition.y + 0.001;
  9978. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9979. zero.z = localPosition.z + 0.001;
  9980. }
  9981. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9982. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9983. this._localBillboard.invert();
  9984. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9985. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9986. }
  9987. // Local world
  9988. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9989. // Parent
  9990. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9991. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9992. }
  9993. else {
  9994. this._worldMatrix.copyFrom(this._localWorld);
  9995. }
  9996. // Bounding info
  9997. this._updateBoundingInfo();
  9998. // Absolute position
  9999. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10000. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  10001. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  10002. }
  10003. return this._worldMatrix;
  10004. };
  10005. /**
  10006. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10007. * @param func: callback function to add
  10008. */
  10009. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10010. this._onAfterWorldMatrixUpdate.push(func);
  10011. };
  10012. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10013. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  10014. if (index > -1) {
  10015. this._onAfterWorldMatrixUpdate.splice(index, 1);
  10016. }
  10017. };
  10018. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10019. this.computeWorldMatrix();
  10020. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10021. };
  10022. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10023. this.computeWorldMatrix();
  10024. var invLocalWorldMatrix = this._localWorld.clone();
  10025. invLocalWorldMatrix.invert();
  10026. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10027. };
  10028. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10029. this.computeWorldMatrix();
  10030. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10031. };
  10032. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  10033. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10034. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  10035. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10036. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10037. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10038. /// <returns>Mesh oriented towards targetMesh</returns>
  10039. yawCor = yawCor || 0; // default to zero if undefined
  10040. pitchCor = pitchCor || 0;
  10041. rollCor = rollCor || 0;
  10042. var dv = targetPoint.subtract(this.position);
  10043. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10044. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10045. var pitch = Math.atan2(dv.y, len);
  10046. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  10047. };
  10048. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10049. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  10050. return false;
  10051. }
  10052. return true;
  10053. };
  10054. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  10055. if (!camera) {
  10056. camera = this.getScene().activeCamera;
  10057. }
  10058. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  10059. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  10060. return false;
  10061. }
  10062. return true;
  10063. };
  10064. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10065. if (!this._boundingInfo || !mesh._boundingInfo) {
  10066. return false;
  10067. }
  10068. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10069. };
  10070. AbstractMesh.prototype.intersectsPoint = function (point) {
  10071. if (!this._boundingInfo) {
  10072. return false;
  10073. }
  10074. return this._boundingInfo.intersectsPoint(point);
  10075. };
  10076. // Physics
  10077. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10078. var physicsEngine = this.getScene().getPhysicsEngine();
  10079. if (!physicsEngine) {
  10080. return;
  10081. }
  10082. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  10083. if (impostor.impostor) {
  10084. // Old API
  10085. options = impostor;
  10086. impostor = impostor.impostor;
  10087. }
  10088. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  10089. physicsEngine._unregisterMesh(this);
  10090. return;
  10091. }
  10092. if (!options) {
  10093. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  10094. }
  10095. else {
  10096. if (!options.mass && options.mass !== 0)
  10097. options.mass = 0;
  10098. if (!options.friction && options.friction !== 0)
  10099. options.friction = 0.2;
  10100. if (!options.restitution && options.restitution !== 0)
  10101. options.restitution = 0.2;
  10102. }
  10103. this._physicImpostor = impostor;
  10104. this._physicsMass = options.mass;
  10105. this._physicsFriction = options.friction;
  10106. this._physicRestitution = options.restitution;
  10107. return physicsEngine._registerMesh(this, impostor, options);
  10108. };
  10109. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10110. if (!this._physicImpostor) {
  10111. return BABYLON.PhysicsEngine.NoImpostor;
  10112. }
  10113. return this._physicImpostor;
  10114. };
  10115. AbstractMesh.prototype.getPhysicsMass = function () {
  10116. if (!this._physicsMass) {
  10117. return 0;
  10118. }
  10119. return this._physicsMass;
  10120. };
  10121. AbstractMesh.prototype.getPhysicsFriction = function () {
  10122. if (!this._physicsFriction) {
  10123. return 0;
  10124. }
  10125. return this._physicsFriction;
  10126. };
  10127. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10128. if (!this._physicRestitution) {
  10129. return 0;
  10130. }
  10131. return this._physicRestitution;
  10132. };
  10133. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10134. if (!camera) {
  10135. camera = this.getScene().activeCamera;
  10136. }
  10137. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10138. };
  10139. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10140. if (!camera) {
  10141. camera = this.getScene().activeCamera;
  10142. }
  10143. return this.absolutePosition.subtract(camera.position).length();
  10144. };
  10145. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10146. if (!this._physicImpostor) {
  10147. return;
  10148. }
  10149. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  10150. };
  10151. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10152. if (!this._physicImpostor) {
  10153. return;
  10154. }
  10155. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  10156. };
  10157. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10158. if (!this._physicImpostor) {
  10159. return;
  10160. }
  10161. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  10162. };
  10163. // Collisions
  10164. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10165. var globalPosition = this.getAbsolutePosition();
  10166. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10167. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10168. this._collider.radius = this.ellipsoid;
  10169. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10170. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10171. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10172. this.position.addInPlace(this._diffPositionForCollisions);
  10173. }
  10174. };
  10175. // Submeshes octree
  10176. /**
  10177. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10178. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10179. */
  10180. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10181. if (maxCapacity === void 0) { maxCapacity = 64; }
  10182. if (maxDepth === void 0) { maxDepth = 2; }
  10183. if (!this._submeshesOctree) {
  10184. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10185. }
  10186. this.computeWorldMatrix(true);
  10187. // Update octree
  10188. var bbox = this.getBoundingInfo().boundingBox;
  10189. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10190. return this._submeshesOctree;
  10191. };
  10192. // Collisions
  10193. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10194. this._generatePointsArray();
  10195. // Transformation
  10196. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10197. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10198. subMesh._lastColliderWorldVertices = [];
  10199. subMesh._trianglePlanes = [];
  10200. var start = subMesh.verticesStart;
  10201. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10202. for (var i = start; i < end; i++) {
  10203. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10204. }
  10205. }
  10206. // Collide
  10207. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10208. };
  10209. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10210. var subMeshes;
  10211. var len;
  10212. // Octrees
  10213. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10214. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10215. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10216. len = intersections.length;
  10217. subMeshes = intersections.data;
  10218. }
  10219. else {
  10220. subMeshes = this.subMeshes;
  10221. len = subMeshes.length;
  10222. }
  10223. for (var index = 0; index < len; index++) {
  10224. var subMesh = subMeshes[index];
  10225. // Bounding test
  10226. if (len > 1 && !subMesh._checkCollision(collider))
  10227. continue;
  10228. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10229. }
  10230. };
  10231. AbstractMesh.prototype._checkCollision = function (collider) {
  10232. // Bounding box test
  10233. if (!this._boundingInfo._checkCollision(collider))
  10234. return;
  10235. // Transformation matrix
  10236. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10237. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10238. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10239. };
  10240. // Picking
  10241. AbstractMesh.prototype._generatePointsArray = function () {
  10242. return false;
  10243. };
  10244. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10245. var pickingInfo = new BABYLON.PickingInfo();
  10246. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10247. return pickingInfo;
  10248. }
  10249. if (!this._generatePointsArray()) {
  10250. return pickingInfo;
  10251. }
  10252. var intersectInfo = null;
  10253. // Octrees
  10254. var subMeshes;
  10255. var len;
  10256. if (this._submeshesOctree && this.useOctreeForPicking) {
  10257. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10258. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10259. len = intersections.length;
  10260. subMeshes = intersections.data;
  10261. }
  10262. else {
  10263. subMeshes = this.subMeshes;
  10264. len = subMeshes.length;
  10265. }
  10266. for (var index = 0; index < len; index++) {
  10267. var subMesh = subMeshes[index];
  10268. // Bounding test
  10269. if (len > 1 && !subMesh.canIntersects(ray))
  10270. continue;
  10271. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10272. if (currentIntersectInfo) {
  10273. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10274. intersectInfo = currentIntersectInfo;
  10275. intersectInfo.subMeshId = index;
  10276. if (fastCheck) {
  10277. break;
  10278. }
  10279. }
  10280. }
  10281. }
  10282. if (intersectInfo) {
  10283. // Get picked point
  10284. var world = this.getWorldMatrix();
  10285. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10286. var direction = ray.direction.clone();
  10287. direction = direction.scale(intersectInfo.distance);
  10288. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10289. var pickedPoint = worldOrigin.add(worldDirection);
  10290. // Return result
  10291. pickingInfo.hit = true;
  10292. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10293. pickingInfo.pickedPoint = pickedPoint;
  10294. pickingInfo.pickedMesh = this;
  10295. pickingInfo.bu = intersectInfo.bu;
  10296. pickingInfo.bv = intersectInfo.bv;
  10297. pickingInfo.faceId = intersectInfo.faceId;
  10298. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10299. return pickingInfo;
  10300. }
  10301. return pickingInfo;
  10302. };
  10303. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10304. return null;
  10305. };
  10306. AbstractMesh.prototype.releaseSubMeshes = function () {
  10307. if (this.subMeshes) {
  10308. while (this.subMeshes.length) {
  10309. this.subMeshes[0].dispose();
  10310. }
  10311. }
  10312. else {
  10313. this.subMeshes = new Array();
  10314. }
  10315. };
  10316. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10317. // Physics
  10318. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10319. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10320. }
  10321. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10322. var other = this._intersectionsInProgress[index];
  10323. var pos = other._intersectionsInProgress.indexOf(this);
  10324. other._intersectionsInProgress.splice(pos, 1);
  10325. }
  10326. this._intersectionsInProgress = [];
  10327. // SubMeshes
  10328. this.releaseSubMeshes();
  10329. // Remove from scene
  10330. var index = this.getScene().meshes.indexOf(this);
  10331. if (index != -1) {
  10332. // Remove from the scene if mesh found
  10333. this.getScene().meshes.splice(index, 1);
  10334. }
  10335. if (!doNotRecurse) {
  10336. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10337. if (this.getScene().particleSystems[index].emitter == this) {
  10338. this.getScene().particleSystems[index].dispose();
  10339. index--;
  10340. }
  10341. }
  10342. // Children
  10343. var objects = this.getScene().meshes.slice(0);
  10344. for (index = 0; index < objects.length; index++) {
  10345. if (objects[index].parent == this) {
  10346. objects[index].dispose();
  10347. }
  10348. }
  10349. }
  10350. else {
  10351. for (index = 0; index < this.getScene().meshes.length; index++) {
  10352. var obj = this.getScene().meshes[index];
  10353. if (obj.parent === this) {
  10354. obj.parent = null;
  10355. obj.computeWorldMatrix(true);
  10356. }
  10357. }
  10358. }
  10359. this._onAfterWorldMatrixUpdate = [];
  10360. this._isDisposed = true;
  10361. // Callback
  10362. if (this.onDispose) {
  10363. this.onDispose();
  10364. }
  10365. };
  10366. // Statics
  10367. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10368. AbstractMesh._BILLBOARDMODE_X = 1;
  10369. AbstractMesh._BILLBOARDMODE_Y = 2;
  10370. AbstractMesh._BILLBOARDMODE_Z = 4;
  10371. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10372. return AbstractMesh;
  10373. })(BABYLON.Node);
  10374. BABYLON.AbstractMesh = AbstractMesh;
  10375. })(BABYLON || (BABYLON = {}));
  10376. //# sourceMappingURL=babylon.abstractMesh.js.map
  10377. var BABYLON;
  10378. (function (BABYLON) {
  10379. var _InstancesBatch = (function () {
  10380. function _InstancesBatch() {
  10381. this.mustReturn = false;
  10382. this.visibleInstances = new Array();
  10383. this.renderSelf = new Array();
  10384. }
  10385. return _InstancesBatch;
  10386. })();
  10387. BABYLON._InstancesBatch = _InstancesBatch;
  10388. var Mesh = (function (_super) {
  10389. __extends(Mesh, _super);
  10390. /**
  10391. * @constructor
  10392. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10393. * @param {Scene} scene - The scene to add this mesh to.
  10394. * @param {Node} parent - The parent of this mesh, if it has one
  10395. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10396. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10397. * When false, achieved by calling a clone(), also passing False.
  10398. * This will make creation of children, recursive.
  10399. */
  10400. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10401. if (parent === void 0) { parent = null; }
  10402. _super.call(this, name, scene);
  10403. // Members
  10404. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10405. this.instances = new Array();
  10406. this._LODLevels = new Array();
  10407. this._onBeforeRenderCallbacks = new Array();
  10408. this._onAfterRenderCallbacks = new Array();
  10409. this._visibleInstances = {};
  10410. this._renderIdForInstances = new Array();
  10411. this._batchCache = new _InstancesBatch();
  10412. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10413. if (source) {
  10414. // Geometry
  10415. if (source._geometry) {
  10416. source._geometry.applyToMesh(this);
  10417. }
  10418. // Deep copy
  10419. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10420. // Material
  10421. this.material = source.material;
  10422. if (!doNotCloneChildren) {
  10423. for (var index = 0; index < scene.meshes.length; index++) {
  10424. var mesh = scene.meshes[index];
  10425. if (mesh.parent === source) {
  10426. // doNotCloneChildren is always going to be False
  10427. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10428. }
  10429. }
  10430. }
  10431. for (index = 0; index < scene.particleSystems.length; index++) {
  10432. var system = scene.particleSystems[index];
  10433. if (system.emitter === source) {
  10434. system.clone(system.name, this);
  10435. }
  10436. }
  10437. this.computeWorldMatrix(true);
  10438. }
  10439. // Parent
  10440. if (parent !== null) {
  10441. this.parent = parent;
  10442. }
  10443. }
  10444. Object.defineProperty(Mesh, "FRONTSIDE", {
  10445. get: function () {
  10446. return Mesh._FRONTSIDE;
  10447. },
  10448. enumerable: true,
  10449. configurable: true
  10450. });
  10451. Object.defineProperty(Mesh, "BACKSIDE", {
  10452. get: function () {
  10453. return Mesh._BACKSIDE;
  10454. },
  10455. enumerable: true,
  10456. configurable: true
  10457. });
  10458. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10459. get: function () {
  10460. return Mesh._DOUBLESIDE;
  10461. },
  10462. enumerable: true,
  10463. configurable: true
  10464. });
  10465. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10466. get: function () {
  10467. return Mesh._DEFAULTSIDE;
  10468. },
  10469. enumerable: true,
  10470. configurable: true
  10471. });
  10472. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10473. // Methods
  10474. get: function () {
  10475. return this._LODLevels.length > 0;
  10476. },
  10477. enumerable: true,
  10478. configurable: true
  10479. });
  10480. Mesh.prototype._sortLODLevels = function () {
  10481. this._LODLevels.sort(function (a, b) {
  10482. if (a.distance < b.distance) {
  10483. return 1;
  10484. }
  10485. if (a.distance > b.distance) {
  10486. return -1;
  10487. }
  10488. return 0;
  10489. });
  10490. };
  10491. /**
  10492. * Add a mesh as LOD level triggered at the given distance.
  10493. * @param {number} distance - the distance from the center of the object to show this level
  10494. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10495. * @return {BABYLON.Mesh} this mesh (for chaining)
  10496. */
  10497. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10498. if (mesh && mesh._masterMesh) {
  10499. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10500. return this;
  10501. }
  10502. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10503. this._LODLevels.push(level);
  10504. if (mesh) {
  10505. mesh._masterMesh = this;
  10506. }
  10507. this._sortLODLevels();
  10508. return this;
  10509. };
  10510. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  10511. for (var index = 0; index < this._LODLevels.length; index++) {
  10512. var level = this._LODLevels[index];
  10513. if (level.distance === distance) {
  10514. return level.mesh;
  10515. }
  10516. }
  10517. return null;
  10518. };
  10519. /**
  10520. * Remove a mesh from the LOD array
  10521. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10522. * @return {BABYLON.Mesh} this mesh (for chaining)
  10523. */
  10524. Mesh.prototype.removeLODLevel = function (mesh) {
  10525. for (var index = 0; index < this._LODLevels.length; index++) {
  10526. if (this._LODLevels[index].mesh === mesh) {
  10527. this._LODLevels.splice(index, 1);
  10528. if (mesh) {
  10529. mesh._masterMesh = null;
  10530. }
  10531. }
  10532. }
  10533. this._sortLODLevels();
  10534. return this;
  10535. };
  10536. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10537. if (!this._LODLevels || this._LODLevels.length === 0) {
  10538. return this;
  10539. }
  10540. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10541. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10542. return this;
  10543. }
  10544. for (var index = 0; index < this._LODLevels.length; index++) {
  10545. var level = this._LODLevels[index];
  10546. if (level.distance < distanceToCamera) {
  10547. if (level.mesh) {
  10548. level.mesh._preActivate();
  10549. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10550. }
  10551. return level.mesh;
  10552. }
  10553. }
  10554. return this;
  10555. };
  10556. Object.defineProperty(Mesh.prototype, "geometry", {
  10557. get: function () {
  10558. return this._geometry;
  10559. },
  10560. enumerable: true,
  10561. configurable: true
  10562. });
  10563. Mesh.prototype.getTotalVertices = function () {
  10564. if (!this._geometry) {
  10565. return 0;
  10566. }
  10567. return this._geometry.getTotalVertices();
  10568. };
  10569. Mesh.prototype.getVerticesData = function (kind) {
  10570. if (!this._geometry) {
  10571. return null;
  10572. }
  10573. return this._geometry.getVerticesData(kind);
  10574. };
  10575. Mesh.prototype.getVertexBuffer = function (kind) {
  10576. if (!this._geometry) {
  10577. return undefined;
  10578. }
  10579. return this._geometry.getVertexBuffer(kind);
  10580. };
  10581. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10582. if (!this._geometry) {
  10583. if (this._delayInfo) {
  10584. return this._delayInfo.indexOf(kind) !== -1;
  10585. }
  10586. return false;
  10587. }
  10588. return this._geometry.isVerticesDataPresent(kind);
  10589. };
  10590. Mesh.prototype.getVerticesDataKinds = function () {
  10591. if (!this._geometry) {
  10592. var result = [];
  10593. if (this._delayInfo) {
  10594. for (var kind in this._delayInfo) {
  10595. result.push(kind);
  10596. }
  10597. }
  10598. return result;
  10599. }
  10600. return this._geometry.getVerticesDataKinds();
  10601. };
  10602. Mesh.prototype.getTotalIndices = function () {
  10603. if (!this._geometry) {
  10604. return 0;
  10605. }
  10606. return this._geometry.getTotalIndices();
  10607. };
  10608. Mesh.prototype.getIndices = function () {
  10609. if (!this._geometry) {
  10610. return [];
  10611. }
  10612. return this._geometry.getIndices();
  10613. };
  10614. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10615. get: function () {
  10616. return this._masterMesh !== null && this._masterMesh !== undefined;
  10617. },
  10618. enumerable: true,
  10619. configurable: true
  10620. });
  10621. Mesh.prototype.isReady = function () {
  10622. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10623. return false;
  10624. }
  10625. return _super.prototype.isReady.call(this);
  10626. };
  10627. Mesh.prototype.isDisposed = function () {
  10628. return this._isDisposed;
  10629. };
  10630. // Methods
  10631. Mesh.prototype._preActivate = function () {
  10632. var sceneRenderId = this.getScene().getRenderId();
  10633. if (this._preActivateId === sceneRenderId) {
  10634. return;
  10635. }
  10636. this._preActivateId = sceneRenderId;
  10637. this._visibleInstances = null;
  10638. };
  10639. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10640. if (!this._visibleInstances) {
  10641. this._visibleInstances = {};
  10642. this._visibleInstances.defaultRenderId = renderId;
  10643. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10644. }
  10645. if (!this._visibleInstances[renderId]) {
  10646. this._visibleInstances[renderId] = new Array();
  10647. }
  10648. this._visibleInstances[renderId].push(instance);
  10649. };
  10650. Mesh.prototype.refreshBoundingInfo = function () {
  10651. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10652. if (data) {
  10653. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10654. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10655. }
  10656. if (this.subMeshes) {
  10657. for (var index = 0; index < this.subMeshes.length; index++) {
  10658. this.subMeshes[index].refreshBoundingInfo();
  10659. }
  10660. }
  10661. this._updateBoundingInfo();
  10662. };
  10663. Mesh.prototype._createGlobalSubMesh = function () {
  10664. var totalVertices = this.getTotalVertices();
  10665. if (!totalVertices || !this.getIndices()) {
  10666. return null;
  10667. }
  10668. this.releaseSubMeshes();
  10669. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10670. };
  10671. Mesh.prototype.subdivide = function (count) {
  10672. if (count < 1) {
  10673. return;
  10674. }
  10675. var totalIndices = this.getTotalIndices();
  10676. var subdivisionSize = (totalIndices / count) | 0;
  10677. var offset = 0;
  10678. while (subdivisionSize % 3 !== 0) {
  10679. subdivisionSize++;
  10680. }
  10681. this.releaseSubMeshes();
  10682. for (var index = 0; index < count; index++) {
  10683. if (offset >= totalIndices) {
  10684. break;
  10685. }
  10686. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10687. offset += subdivisionSize;
  10688. }
  10689. this.synchronizeInstances();
  10690. };
  10691. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10692. if (kind instanceof Array) {
  10693. var temp = data;
  10694. data = kind;
  10695. kind = temp;
  10696. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10697. }
  10698. if (!this._geometry) {
  10699. var vertexData = new BABYLON.VertexData();
  10700. vertexData.set(data, kind);
  10701. var scene = this.getScene();
  10702. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10703. }
  10704. else {
  10705. this._geometry.setVerticesData(kind, data, updatable, stride);
  10706. }
  10707. };
  10708. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10709. if (!this._geometry) {
  10710. return;
  10711. }
  10712. if (!makeItUnique) {
  10713. this._geometry.updateVerticesData(kind, data, updateExtends);
  10714. }
  10715. else {
  10716. this.makeGeometryUnique();
  10717. this.updateVerticesData(kind, data, updateExtends, false);
  10718. }
  10719. };
  10720. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10721. if (!this._geometry) {
  10722. return;
  10723. }
  10724. if (!makeItUnique) {
  10725. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10726. }
  10727. else {
  10728. this.makeGeometryUnique();
  10729. this.updateVerticesDataDirectly(kind, data, offset, false);
  10730. }
  10731. };
  10732. Mesh.prototype.makeGeometryUnique = function () {
  10733. if (!this._geometry) {
  10734. return;
  10735. }
  10736. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10737. geometry.applyToMesh(this);
  10738. };
  10739. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10740. if (!this._geometry) {
  10741. var vertexData = new BABYLON.VertexData();
  10742. vertexData.indices = indices;
  10743. var scene = this.getScene();
  10744. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10745. }
  10746. else {
  10747. this._geometry.setIndices(indices, totalVertices);
  10748. }
  10749. };
  10750. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10751. var engine = this.getScene().getEngine();
  10752. // Wireframe
  10753. var indexToBind;
  10754. switch (fillMode) {
  10755. case BABYLON.Material.PointFillMode:
  10756. indexToBind = null;
  10757. break;
  10758. case BABYLON.Material.WireFrameFillMode:
  10759. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10760. break;
  10761. default:
  10762. case BABYLON.Material.TriangleFillMode:
  10763. indexToBind = this._geometry.getIndexBuffer();
  10764. break;
  10765. }
  10766. // VBOs
  10767. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10768. };
  10769. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10770. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10771. return;
  10772. }
  10773. var engine = this.getScene().getEngine();
  10774. switch (fillMode) {
  10775. case BABYLON.Material.PointFillMode:
  10776. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10777. break;
  10778. case BABYLON.Material.WireFrameFillMode:
  10779. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10780. break;
  10781. default:
  10782. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10783. }
  10784. };
  10785. Mesh.prototype.registerBeforeRender = function (func) {
  10786. this._onBeforeRenderCallbacks.push(func);
  10787. };
  10788. Mesh.prototype.unregisterBeforeRender = function (func) {
  10789. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10790. if (index > -1) {
  10791. this._onBeforeRenderCallbacks.splice(index, 1);
  10792. }
  10793. };
  10794. Mesh.prototype.registerAfterRender = function (func) {
  10795. this._onAfterRenderCallbacks.push(func);
  10796. };
  10797. Mesh.prototype.unregisterAfterRender = function (func) {
  10798. var index = this._onAfterRenderCallbacks.indexOf(func);
  10799. if (index > -1) {
  10800. this._onAfterRenderCallbacks.splice(index, 1);
  10801. }
  10802. };
  10803. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10804. var scene = this.getScene();
  10805. this._batchCache.mustReturn = false;
  10806. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10807. this._batchCache.visibleInstances[subMeshId] = null;
  10808. if (this._visibleInstances) {
  10809. var currentRenderId = scene.getRenderId();
  10810. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10811. var selfRenderId = this._renderId;
  10812. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10813. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10814. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10815. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10816. }
  10817. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10818. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10819. this._batchCache.mustReturn = true;
  10820. return this._batchCache;
  10821. }
  10822. if (currentRenderId !== selfRenderId) {
  10823. this._batchCache.renderSelf[subMeshId] = false;
  10824. }
  10825. }
  10826. this._renderIdForInstances[subMeshId] = currentRenderId;
  10827. }
  10828. return this._batchCache;
  10829. };
  10830. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10831. var visibleInstances = batch.visibleInstances[subMesh._id];
  10832. var matricesCount = visibleInstances.length + 1;
  10833. var bufferSize = matricesCount * 16 * 4;
  10834. while (this._instancesBufferSize < bufferSize) {
  10835. this._instancesBufferSize *= 2;
  10836. }
  10837. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10838. if (this._worldMatricesInstancesBuffer) {
  10839. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10840. }
  10841. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10842. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10843. }
  10844. var offset = 0;
  10845. var instancesCount = 0;
  10846. var world = this.getWorldMatrix();
  10847. if (batch.renderSelf[subMesh._id]) {
  10848. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10849. offset += 16;
  10850. instancesCount++;
  10851. }
  10852. if (visibleInstances) {
  10853. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10854. var instance = visibleInstances[instanceIndex];
  10855. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10856. offset += 16;
  10857. instancesCount++;
  10858. }
  10859. }
  10860. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10861. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10862. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10863. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10864. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10865. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10866. this._draw(subMesh, fillMode, instancesCount);
  10867. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10868. };
  10869. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10870. var scene = this.getScene();
  10871. var engine = scene.getEngine();
  10872. if (hardwareInstancedRendering) {
  10873. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10874. }
  10875. else {
  10876. if (batch.renderSelf[subMesh._id]) {
  10877. // Draw
  10878. if (onBeforeDraw) {
  10879. onBeforeDraw(false, this.getWorldMatrix());
  10880. }
  10881. this._draw(subMesh, fillMode);
  10882. }
  10883. if (batch.visibleInstances[subMesh._id]) {
  10884. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10885. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10886. // World
  10887. var world = instance.getWorldMatrix();
  10888. if (onBeforeDraw) {
  10889. onBeforeDraw(true, world);
  10890. }
  10891. // Draw
  10892. this._draw(subMesh, fillMode);
  10893. }
  10894. }
  10895. }
  10896. };
  10897. Mesh.prototype.render = function (subMesh) {
  10898. var scene = this.getScene();
  10899. // Managing instances
  10900. var batch = this._getInstancesRenderList(subMesh._id);
  10901. if (batch.mustReturn) {
  10902. return;
  10903. }
  10904. // Checking geometry state
  10905. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10906. return;
  10907. }
  10908. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10909. this._onBeforeRenderCallbacks[callbackIndex](this);
  10910. }
  10911. var engine = scene.getEngine();
  10912. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10913. // Material
  10914. var effectiveMaterial = subMesh.getMaterial();
  10915. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10916. return;
  10917. }
  10918. // Outline - step 1
  10919. var savedDepthWrite = engine.getDepthWrite();
  10920. if (this.renderOutline) {
  10921. engine.setDepthWrite(false);
  10922. scene.getOutlineRenderer().render(subMesh, batch);
  10923. engine.setDepthWrite(savedDepthWrite);
  10924. }
  10925. effectiveMaterial._preBind();
  10926. var effect = effectiveMaterial.getEffect();
  10927. // Bind
  10928. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10929. this._bind(subMesh, effect, fillMode);
  10930. var world = this.getWorldMatrix();
  10931. effectiveMaterial.bind(world, this);
  10932. // Draw
  10933. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10934. if (isInstance) {
  10935. effectiveMaterial.bindOnlyWorldMatrix(world);
  10936. }
  10937. });
  10938. // Unbind
  10939. effectiveMaterial.unbind();
  10940. // Outline - step 2
  10941. if (this.renderOutline && savedDepthWrite) {
  10942. engine.setDepthWrite(true);
  10943. engine.setColorWrite(false);
  10944. scene.getOutlineRenderer().render(subMesh, batch);
  10945. engine.setColorWrite(true);
  10946. }
  10947. // Overlay
  10948. if (this.renderOverlay) {
  10949. var currentMode = engine.getAlphaMode();
  10950. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10951. scene.getOutlineRenderer().render(subMesh, batch, true);
  10952. engine.setAlphaMode(currentMode);
  10953. }
  10954. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10955. this._onAfterRenderCallbacks[callbackIndex](this);
  10956. }
  10957. };
  10958. Mesh.prototype.getEmittedParticleSystems = function () {
  10959. var results = new Array();
  10960. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10961. var particleSystem = this.getScene().particleSystems[index];
  10962. if (particleSystem.emitter === this) {
  10963. results.push(particleSystem);
  10964. }
  10965. }
  10966. return results;
  10967. };
  10968. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10969. var results = new Array();
  10970. var descendants = this.getDescendants();
  10971. descendants.push(this);
  10972. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10973. var particleSystem = this.getScene().particleSystems[index];
  10974. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10975. results.push(particleSystem);
  10976. }
  10977. }
  10978. return results;
  10979. };
  10980. Mesh.prototype.getChildren = function () {
  10981. var results = [];
  10982. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10983. var mesh = this.getScene().meshes[index];
  10984. if (mesh.parent === this) {
  10985. results.push(mesh);
  10986. }
  10987. }
  10988. return results;
  10989. };
  10990. Mesh.prototype._checkDelayState = function () {
  10991. var _this = this;
  10992. var that = this;
  10993. var scene = this.getScene();
  10994. if (this._geometry) {
  10995. this._geometry.load(scene);
  10996. }
  10997. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10998. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10999. scene._addPendingData(that);
  11000. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  11001. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  11002. if (data instanceof ArrayBuffer) {
  11003. _this._delayLoadingFunction(data, _this);
  11004. }
  11005. else {
  11006. _this._delayLoadingFunction(JSON.parse(data), _this);
  11007. }
  11008. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  11009. scene._removePendingData(_this);
  11010. }, function () {
  11011. }, scene.database, getBinaryData);
  11012. }
  11013. };
  11014. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  11015. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  11016. return false;
  11017. }
  11018. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  11019. return false;
  11020. }
  11021. this._checkDelayState();
  11022. return true;
  11023. };
  11024. Mesh.prototype.setMaterialByID = function (id) {
  11025. var materials = this.getScene().materials;
  11026. for (var index = 0; index < materials.length; index++) {
  11027. if (materials[index].id === id) {
  11028. this.material = materials[index];
  11029. return;
  11030. }
  11031. }
  11032. // Multi
  11033. var multiMaterials = this.getScene().multiMaterials;
  11034. for (index = 0; index < multiMaterials.length; index++) {
  11035. if (multiMaterials[index].id === id) {
  11036. this.material = multiMaterials[index];
  11037. return;
  11038. }
  11039. }
  11040. };
  11041. Mesh.prototype.getAnimatables = function () {
  11042. var results = [];
  11043. if (this.material) {
  11044. results.push(this.material);
  11045. }
  11046. if (this.skeleton) {
  11047. results.push(this.skeleton);
  11048. }
  11049. return results;
  11050. };
  11051. // Geometry
  11052. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  11053. // Position
  11054. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  11055. return;
  11056. }
  11057. this._resetPointsArrayCache();
  11058. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11059. var temp = [];
  11060. for (var index = 0; index < data.length; index += 3) {
  11061. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11062. }
  11063. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  11064. // Normals
  11065. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  11066. return;
  11067. }
  11068. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11069. for (index = 0; index < data.length; index += 3) {
  11070. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  11071. }
  11072. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  11073. };
  11074. // Cache
  11075. Mesh.prototype._resetPointsArrayCache = function () {
  11076. this._positions = null;
  11077. };
  11078. Mesh.prototype._generatePointsArray = function () {
  11079. if (this._positions)
  11080. return true;
  11081. this._positions = [];
  11082. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11083. if (!data) {
  11084. return false;
  11085. }
  11086. for (var index = 0; index < data.length; index += 3) {
  11087. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  11088. }
  11089. return true;
  11090. };
  11091. // Clone
  11092. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11093. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  11094. };
  11095. // Dispose
  11096. Mesh.prototype.dispose = function (doNotRecurse) {
  11097. if (this._geometry) {
  11098. this._geometry.releaseForMesh(this, true);
  11099. }
  11100. // Instances
  11101. if (this._worldMatricesInstancesBuffer) {
  11102. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  11103. this._worldMatricesInstancesBuffer = null;
  11104. }
  11105. while (this.instances.length) {
  11106. this.instances[0].dispose();
  11107. }
  11108. _super.prototype.dispose.call(this, doNotRecurse);
  11109. };
  11110. // Geometric tools
  11111. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  11112. var _this = this;
  11113. var scene = this.getScene();
  11114. var onload = function (img) {
  11115. // Getting height map data
  11116. var canvas = document.createElement("canvas");
  11117. var context = canvas.getContext("2d");
  11118. var heightMapWidth = img.width;
  11119. var heightMapHeight = img.height;
  11120. canvas.width = heightMapWidth;
  11121. canvas.height = heightMapHeight;
  11122. context.drawImage(img, 0, 0);
  11123. // Create VertexData from map data
  11124. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11125. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11126. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  11127. //execute success callback, if set
  11128. if (onSuccess) {
  11129. onSuccess(_this);
  11130. }
  11131. };
  11132. BABYLON.Tools.LoadImage(url, onload, function () {
  11133. }, scene.database);
  11134. };
  11135. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  11136. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11137. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  11138. return;
  11139. }
  11140. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11141. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  11142. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  11143. var position = BABYLON.Vector3.Zero();
  11144. var normal = BABYLON.Vector3.Zero();
  11145. var uv = BABYLON.Vector2.Zero();
  11146. for (var index = 0; index < positions.length; index += 3) {
  11147. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  11148. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  11149. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  11150. // Compute height
  11151. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  11152. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  11153. var pos = (u + v * heightMapWidth) * 4;
  11154. var r = buffer[pos] / 255.0;
  11155. var g = buffer[pos + 1] / 255.0;
  11156. var b = buffer[pos + 2] / 255.0;
  11157. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  11158. normal.normalize();
  11159. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  11160. position = position.add(normal);
  11161. position.toArray(positions, index);
  11162. }
  11163. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  11164. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  11165. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  11166. };
  11167. Mesh.prototype.convertToFlatShadedMesh = function () {
  11168. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  11169. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  11170. var kinds = this.getVerticesDataKinds();
  11171. var vbs = [];
  11172. var data = [];
  11173. var newdata = [];
  11174. var updatableNormals = false;
  11175. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11176. var kind = kinds[kindIndex];
  11177. var vertexBuffer = this.getVertexBuffer(kind);
  11178. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11179. updatableNormals = vertexBuffer.isUpdatable();
  11180. kinds.splice(kindIndex, 1);
  11181. kindIndex--;
  11182. continue;
  11183. }
  11184. vbs[kind] = vertexBuffer;
  11185. data[kind] = vbs[kind].getData();
  11186. newdata[kind] = [];
  11187. }
  11188. // Save previous submeshes
  11189. var previousSubmeshes = this.subMeshes.slice(0);
  11190. var indices = this.getIndices();
  11191. var totalIndices = this.getTotalIndices();
  11192. for (var index = 0; index < totalIndices; index++) {
  11193. var vertexIndex = indices[index];
  11194. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11195. kind = kinds[kindIndex];
  11196. var stride = vbs[kind].getStrideSize();
  11197. for (var offset = 0; offset < stride; offset++) {
  11198. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11199. }
  11200. }
  11201. }
  11202. // Updating faces & normal
  11203. var normals = [];
  11204. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11205. for (index = 0; index < totalIndices; index += 3) {
  11206. indices[index] = index;
  11207. indices[index + 1] = index + 1;
  11208. indices[index + 2] = index + 2;
  11209. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11210. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11211. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11212. var p1p2 = p1.subtract(p2);
  11213. var p3p2 = p3.subtract(p2);
  11214. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11215. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11216. normals.push(normal.x);
  11217. normals.push(normal.y);
  11218. normals.push(normal.z);
  11219. }
  11220. }
  11221. this.setIndices(indices);
  11222. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11223. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11224. kind = kinds[kindIndex];
  11225. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11226. }
  11227. // Updating submeshes
  11228. this.releaseSubMeshes();
  11229. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11230. var previousOne = previousSubmeshes[submeshIndex];
  11231. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11232. }
  11233. this.synchronizeInstances();
  11234. };
  11235. // Instances
  11236. Mesh.prototype.createInstance = function (name) {
  11237. return new BABYLON.InstancedMesh(name, this);
  11238. };
  11239. Mesh.prototype.synchronizeInstances = function () {
  11240. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11241. var instance = this.instances[instanceIndex];
  11242. instance._syncSubMeshes();
  11243. }
  11244. };
  11245. /**
  11246. * Simplify the mesh according to the given array of settings.
  11247. * Function will return immediately and will simplify async.
  11248. * @param settings a collection of simplification settings.
  11249. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11250. * @param type the type of simplification to run.
  11251. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11252. */
  11253. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  11254. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11255. if (simplificationType === void 0) { simplificationType = 0 /* QUADRATIC */; }
  11256. this.getScene().simplificationQueue.addTask({
  11257. settings: settings,
  11258. parallelProcessing: parallelProcessing,
  11259. mesh: this,
  11260. simplificationType: simplificationType,
  11261. successCallback: successCallback
  11262. });
  11263. };
  11264. // Statics
  11265. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11266. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11267. var ribbon = new Mesh(name, scene);
  11268. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11269. vertexData.applyToMesh(ribbon, updatable);
  11270. return ribbon;
  11271. };
  11272. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11273. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11274. var box = new Mesh(name, scene);
  11275. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11276. vertexData.applyToMesh(box, updatable);
  11277. return box;
  11278. };
  11279. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11280. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11281. var sphere = new Mesh(name, scene);
  11282. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11283. vertexData.applyToMesh(sphere, updatable);
  11284. return sphere;
  11285. };
  11286. // Cylinder and cone (Code inspired by SharpDX.org)
  11287. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11288. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11289. // subdivisions is a new parameter, we need to support old signature
  11290. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11291. if (scene !== undefined) {
  11292. updatable = scene;
  11293. }
  11294. scene = subdivisions;
  11295. subdivisions = 1;
  11296. }
  11297. var cylinder = new Mesh(name, scene);
  11298. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11299. vertexData.applyToMesh(cylinder, updatable);
  11300. return cylinder;
  11301. };
  11302. // Torus (Code from SharpDX.org)
  11303. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11304. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11305. var torus = new Mesh(name, scene);
  11306. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11307. vertexData.applyToMesh(torus, updatable);
  11308. return torus;
  11309. };
  11310. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11311. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11312. var torusKnot = new Mesh(name, scene);
  11313. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11314. vertexData.applyToMesh(torusKnot, updatable);
  11315. return torusKnot;
  11316. };
  11317. // Lines
  11318. Mesh.CreateLines = function (name, points, scene, updatable) {
  11319. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11320. var vertexData = BABYLON.VertexData.CreateLines(points);
  11321. vertexData.applyToMesh(lines, updatable);
  11322. return lines;
  11323. };
  11324. // Extrusion
  11325. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, scene, updatable, sideOrientation) {
  11326. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11327. scale = scale || 1;
  11328. rotation = rotation || 0;
  11329. var extruded = Mesh._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, false, scene, updatable, sideOrientation);
  11330. return extruded;
  11331. };
  11332. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, scene, updatable, sideOrientation) {
  11333. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11334. var extrudedCustom = Mesh._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, true, scene, updatable, sideOrientation);
  11335. return extrudedCustom;
  11336. };
  11337. Mesh._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotationFunction, rbCA, rbCP, custom, scene, updtbl, side) {
  11338. var path3D = new BABYLON.Path3D(curve);
  11339. var shapePaths = [];
  11340. var extrudedGeneric = Mesh.CreateRibbon(name, shapePaths, rbCA, rbCP, 0, scene, updtbl, side);
  11341. return extrudedGeneric;
  11342. };
  11343. // Plane & ground
  11344. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11345. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11346. var plane = new Mesh(name, scene);
  11347. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11348. vertexData.applyToMesh(plane, updatable);
  11349. return plane;
  11350. };
  11351. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11352. var ground = new BABYLON.GroundMesh(name, scene);
  11353. ground._setReady(false);
  11354. ground._subdivisions = subdivisions;
  11355. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11356. vertexData.applyToMesh(ground, updatable);
  11357. ground._setReady(true);
  11358. return ground;
  11359. };
  11360. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11361. var tiledGround = new Mesh(name, scene);
  11362. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11363. vertexData.applyToMesh(tiledGround, updatable);
  11364. return tiledGround;
  11365. };
  11366. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11367. var ground = new BABYLON.GroundMesh(name, scene);
  11368. ground._subdivisions = subdivisions;
  11369. ground._setReady(false);
  11370. var onload = function (img) {
  11371. // Getting height map data
  11372. var canvas = document.createElement("canvas");
  11373. var context = canvas.getContext("2d");
  11374. var heightMapWidth = img.width;
  11375. var heightMapHeight = img.height;
  11376. canvas.width = heightMapWidth;
  11377. canvas.height = heightMapHeight;
  11378. context.drawImage(img, 0, 0);
  11379. // Create VertexData from map data
  11380. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11381. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11382. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11383. vertexData.applyToMesh(ground, updatable);
  11384. ground._setReady(true);
  11385. //execute ready callback, if set
  11386. if (onReady) {
  11387. onReady(ground);
  11388. }
  11389. };
  11390. BABYLON.Tools.LoadImage(url, onload, function () {
  11391. }, scene.database);
  11392. return ground;
  11393. };
  11394. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11395. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11396. var path3D = new BABYLON.Path3D(path);
  11397. var tangents = path3D.getTangents();
  11398. var normals = path3D.getNormals();
  11399. var distances = path3D.getDistances();
  11400. var pi2 = Math.PI * 2;
  11401. var step = pi2 / tesselation;
  11402. var returnRadius = function (i, distance) { return radius; };
  11403. var radiusFunctionFinal = radiusFunction || returnRadius;
  11404. var circlePaths = new Array();
  11405. var circlePath;
  11406. var rad;
  11407. var normal;
  11408. var rotated;
  11409. var rotationMatrix;
  11410. for (var i = 0; i < path.length; i++) {
  11411. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11412. circlePath = Array(); // current circle array
  11413. normal = normals[i]; // current normal
  11414. for (var ang = 0; ang < pi2; ang += step) {
  11415. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11416. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11417. circlePath.push(rotated);
  11418. }
  11419. circlePaths.push(circlePath);
  11420. }
  11421. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11422. return tube;
  11423. };
  11424. // Tools
  11425. Mesh.MinMax = function (meshes) {
  11426. var minVector = null;
  11427. var maxVector = null;
  11428. for (var i in meshes) {
  11429. var mesh = meshes[i];
  11430. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11431. if (!minVector) {
  11432. minVector = boundingBox.minimumWorld;
  11433. maxVector = boundingBox.maximumWorld;
  11434. continue;
  11435. }
  11436. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11437. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11438. }
  11439. return {
  11440. min: minVector,
  11441. max: maxVector
  11442. };
  11443. };
  11444. Mesh.Center = function (meshesOrMinMaxVector) {
  11445. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11446. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11447. };
  11448. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11449. if (disposeSource === void 0) { disposeSource = true; }
  11450. var source = meshes[0];
  11451. var material = source.material;
  11452. var scene = source.getScene();
  11453. if (!allow32BitsIndices) {
  11454. var totalVertices = 0;
  11455. for (var index = 0; index < meshes.length; index++) {
  11456. totalVertices += meshes[index].getTotalVertices();
  11457. if (totalVertices > 65536) {
  11458. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11459. return null;
  11460. }
  11461. }
  11462. }
  11463. // Merge
  11464. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11465. vertexData.transform(source.getWorldMatrix());
  11466. for (index = 1; index < meshes.length; index++) {
  11467. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11468. otherVertexData.transform(meshes[index].getWorldMatrix());
  11469. vertexData.merge(otherVertexData);
  11470. }
  11471. var newMesh = new Mesh(source.name + "_merged", scene);
  11472. vertexData.applyToMesh(newMesh);
  11473. // Setting properties
  11474. newMesh.material = material;
  11475. newMesh.checkCollisions = source.checkCollisions;
  11476. // Cleaning
  11477. if (disposeSource) {
  11478. for (index = 0; index < meshes.length; index++) {
  11479. meshes[index].dispose();
  11480. }
  11481. }
  11482. return newMesh;
  11483. };
  11484. // Consts
  11485. Mesh._FRONTSIDE = 0;
  11486. Mesh._BACKSIDE = 1;
  11487. Mesh._DOUBLESIDE = 2;
  11488. Mesh._DEFAULTSIDE = 0;
  11489. return Mesh;
  11490. })(BABYLON.AbstractMesh);
  11491. BABYLON.Mesh = Mesh;
  11492. })(BABYLON || (BABYLON = {}));
  11493. //# sourceMappingURL=babylon.mesh.js.map
  11494. var BABYLON;
  11495. (function (BABYLON) {
  11496. var GroundMesh = (function (_super) {
  11497. __extends(GroundMesh, _super);
  11498. function GroundMesh(name, scene) {
  11499. _super.call(this, name, scene);
  11500. this.generateOctree = false;
  11501. this._worldInverse = new BABYLON.Matrix();
  11502. }
  11503. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11504. get: function () {
  11505. return this._subdivisions;
  11506. },
  11507. enumerable: true,
  11508. configurable: true
  11509. });
  11510. GroundMesh.prototype.optimize = function (chunksCount) {
  11511. this.subdivide(this._subdivisions);
  11512. this.createOrUpdateSubmeshesOctree(32);
  11513. };
  11514. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11515. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11516. this.getWorldMatrix().invertToRef(this._worldInverse);
  11517. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11518. var pickInfo = this.intersects(ray);
  11519. if (pickInfo.hit) {
  11520. return pickInfo.pickedPoint.y;
  11521. }
  11522. return 0;
  11523. };
  11524. return GroundMesh;
  11525. })(BABYLON.Mesh);
  11526. BABYLON.GroundMesh = GroundMesh;
  11527. })(BABYLON || (BABYLON = {}));
  11528. //# sourceMappingURL=babylon.groundMesh.js.map
  11529. var BABYLON;
  11530. (function (BABYLON) {
  11531. /**
  11532. * Creates an instance based on a source mesh.
  11533. */
  11534. var InstancedMesh = (function (_super) {
  11535. __extends(InstancedMesh, _super);
  11536. function InstancedMesh(name, source) {
  11537. _super.call(this, name, source.getScene());
  11538. source.instances.push(this);
  11539. this._sourceMesh = source;
  11540. this.position.copyFrom(source.position);
  11541. this.rotation.copyFrom(source.rotation);
  11542. this.scaling.copyFrom(source.scaling);
  11543. if (source.rotationQuaternion) {
  11544. this.rotationQuaternion = source.rotationQuaternion.clone();
  11545. }
  11546. this.infiniteDistance = source.infiniteDistance;
  11547. this.setPivotMatrix(source.getPivotMatrix());
  11548. this.refreshBoundingInfo();
  11549. this._syncSubMeshes();
  11550. }
  11551. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11552. // Methods
  11553. get: function () {
  11554. return this._sourceMesh.receiveShadows;
  11555. },
  11556. enumerable: true,
  11557. configurable: true
  11558. });
  11559. Object.defineProperty(InstancedMesh.prototype, "material", {
  11560. get: function () {
  11561. return this._sourceMesh.material;
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11567. get: function () {
  11568. return this._sourceMesh.visibility;
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11574. get: function () {
  11575. return this._sourceMesh.skeleton;
  11576. },
  11577. enumerable: true,
  11578. configurable: true
  11579. });
  11580. InstancedMesh.prototype.getTotalVertices = function () {
  11581. return this._sourceMesh.getTotalVertices();
  11582. };
  11583. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11584. get: function () {
  11585. return this._sourceMesh;
  11586. },
  11587. enumerable: true,
  11588. configurable: true
  11589. });
  11590. InstancedMesh.prototype.getVerticesData = function (kind) {
  11591. return this._sourceMesh.getVerticesData(kind);
  11592. };
  11593. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11594. return this._sourceMesh.isVerticesDataPresent(kind);
  11595. };
  11596. InstancedMesh.prototype.getIndices = function () {
  11597. return this._sourceMesh.getIndices();
  11598. };
  11599. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11600. get: function () {
  11601. return this._sourceMesh._positions;
  11602. },
  11603. enumerable: true,
  11604. configurable: true
  11605. });
  11606. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11607. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11608. if (data) {
  11609. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11610. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11611. }
  11612. this._updateBoundingInfo();
  11613. };
  11614. InstancedMesh.prototype._preActivate = function () {
  11615. if (this._currentLOD) {
  11616. this._currentLOD._preActivate();
  11617. }
  11618. };
  11619. InstancedMesh.prototype._activate = function (renderId) {
  11620. if (this._currentLOD) {
  11621. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11622. }
  11623. };
  11624. InstancedMesh.prototype.getLOD = function (camera) {
  11625. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11626. if (this._currentLOD === this.sourceMesh) {
  11627. return this;
  11628. }
  11629. return this._currentLOD;
  11630. };
  11631. InstancedMesh.prototype._syncSubMeshes = function () {
  11632. this.releaseSubMeshes();
  11633. if (this._sourceMesh.subMeshes) {
  11634. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11635. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11636. }
  11637. }
  11638. };
  11639. InstancedMesh.prototype._generatePointsArray = function () {
  11640. return this._sourceMesh._generatePointsArray();
  11641. };
  11642. // Clone
  11643. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11644. var result = this._sourceMesh.createInstance(name);
  11645. // Deep copy
  11646. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11647. // Bounding info
  11648. this.refreshBoundingInfo();
  11649. // Parent
  11650. if (newParent) {
  11651. result.parent = newParent;
  11652. }
  11653. if (!doNotCloneChildren) {
  11654. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11655. var mesh = this.getScene().meshes[index];
  11656. if (mesh.parent === this) {
  11657. mesh.clone(mesh.name, result);
  11658. }
  11659. }
  11660. }
  11661. result.computeWorldMatrix(true);
  11662. return result;
  11663. };
  11664. // Dispoe
  11665. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11666. // Remove from mesh
  11667. var index = this._sourceMesh.instances.indexOf(this);
  11668. this._sourceMesh.instances.splice(index, 1);
  11669. _super.prototype.dispose.call(this, doNotRecurse);
  11670. };
  11671. return InstancedMesh;
  11672. })(BABYLON.AbstractMesh);
  11673. BABYLON.InstancedMesh = InstancedMesh;
  11674. })(BABYLON || (BABYLON = {}));
  11675. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11676. (function (BABYLON) {
  11677. var SubMesh = (function () {
  11678. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11679. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11680. this.materialIndex = materialIndex;
  11681. this.verticesStart = verticesStart;
  11682. this.verticesCount = verticesCount;
  11683. this.indexStart = indexStart;
  11684. this.indexCount = indexCount;
  11685. this._renderId = 0;
  11686. this._mesh = mesh;
  11687. this._renderingMesh = renderingMesh || mesh;
  11688. mesh.subMeshes.push(this);
  11689. this._id = mesh.subMeshes.length - 1;
  11690. if (createBoundingBox) {
  11691. this.refreshBoundingInfo();
  11692. }
  11693. }
  11694. SubMesh.prototype.getBoundingInfo = function () {
  11695. return this._boundingInfo;
  11696. };
  11697. SubMesh.prototype.getMesh = function () {
  11698. return this._mesh;
  11699. };
  11700. SubMesh.prototype.getRenderingMesh = function () {
  11701. return this._renderingMesh;
  11702. };
  11703. SubMesh.prototype.getMaterial = function () {
  11704. var rootMaterial = this._renderingMesh.material;
  11705. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11706. var multiMaterial = rootMaterial;
  11707. return multiMaterial.getSubMaterial(this.materialIndex);
  11708. }
  11709. if (!rootMaterial) {
  11710. return this._mesh.getScene().defaultMaterial;
  11711. }
  11712. return rootMaterial;
  11713. };
  11714. // Methods
  11715. SubMesh.prototype.refreshBoundingInfo = function () {
  11716. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11717. if (!data) {
  11718. this._boundingInfo = this._mesh._boundingInfo;
  11719. return;
  11720. }
  11721. var indices = this._renderingMesh.getIndices();
  11722. var extend;
  11723. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11724. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11725. }
  11726. else {
  11727. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11728. }
  11729. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11730. };
  11731. SubMesh.prototype._checkCollision = function (collider) {
  11732. return this._boundingInfo._checkCollision(collider);
  11733. };
  11734. SubMesh.prototype.updateBoundingInfo = function (world) {
  11735. if (!this._boundingInfo) {
  11736. this.refreshBoundingInfo();
  11737. }
  11738. this._boundingInfo._update(world);
  11739. };
  11740. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11741. return this._boundingInfo.isInFrustum(frustumPlanes);
  11742. };
  11743. SubMesh.prototype.render = function () {
  11744. this._renderingMesh.render(this);
  11745. };
  11746. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11747. if (!this._linesIndexBuffer) {
  11748. var linesIndices = [];
  11749. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11750. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11751. }
  11752. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11753. this.linesIndexCount = linesIndices.length;
  11754. }
  11755. return this._linesIndexBuffer;
  11756. };
  11757. SubMesh.prototype.canIntersects = function (ray) {
  11758. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11759. };
  11760. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11761. var intersectInfo = null;
  11762. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11763. var p0 = positions[indices[index]];
  11764. var p1 = positions[indices[index + 1]];
  11765. var p2 = positions[indices[index + 2]];
  11766. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11767. if (currentIntersectInfo) {
  11768. if (currentIntersectInfo.distance < 0) {
  11769. continue;
  11770. }
  11771. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11772. intersectInfo = currentIntersectInfo;
  11773. intersectInfo.faceId = index / 3;
  11774. if (fastCheck) {
  11775. break;
  11776. }
  11777. }
  11778. }
  11779. }
  11780. return intersectInfo;
  11781. };
  11782. // Clone
  11783. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11784. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11785. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11786. return result;
  11787. };
  11788. // Dispose
  11789. SubMesh.prototype.dispose = function () {
  11790. if (this._linesIndexBuffer) {
  11791. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11792. this._linesIndexBuffer = null;
  11793. }
  11794. // Remove from mesh
  11795. var index = this._mesh.subMeshes.indexOf(this);
  11796. this._mesh.subMeshes.splice(index, 1);
  11797. };
  11798. // Statics
  11799. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11800. var minVertexIndex = Number.MAX_VALUE;
  11801. var maxVertexIndex = -Number.MAX_VALUE;
  11802. renderingMesh = renderingMesh || mesh;
  11803. var indices = renderingMesh.getIndices();
  11804. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11805. var vertexIndex = indices[index];
  11806. if (vertexIndex < minVertexIndex)
  11807. minVertexIndex = vertexIndex;
  11808. if (vertexIndex > maxVertexIndex)
  11809. maxVertexIndex = vertexIndex;
  11810. }
  11811. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11812. };
  11813. return SubMesh;
  11814. })();
  11815. BABYLON.SubMesh = SubMesh;
  11816. })(BABYLON || (BABYLON = {}));
  11817. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11818. (function (BABYLON) {
  11819. var BaseTexture = (function () {
  11820. function BaseTexture(scene) {
  11821. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11822. this.hasAlpha = false;
  11823. this.getAlphaFromRGB = false;
  11824. this.level = 1;
  11825. this.isCube = false;
  11826. this.isRenderTarget = false;
  11827. this.animations = new Array();
  11828. this.coordinatesIndex = 0;
  11829. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11830. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11831. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11832. this.anisotropicFilteringLevel = 4;
  11833. this._scene = scene;
  11834. this._scene.textures.push(this);
  11835. }
  11836. BaseTexture.prototype.getScene = function () {
  11837. return this._scene;
  11838. };
  11839. BaseTexture.prototype.getTextureMatrix = function () {
  11840. return null;
  11841. };
  11842. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11843. return null;
  11844. };
  11845. BaseTexture.prototype.getInternalTexture = function () {
  11846. return this._texture;
  11847. };
  11848. BaseTexture.prototype.isReady = function () {
  11849. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11850. return true;
  11851. }
  11852. if (this._texture) {
  11853. return this._texture.isReady;
  11854. }
  11855. return false;
  11856. };
  11857. BaseTexture.prototype.getSize = function () {
  11858. if (this._texture._width) {
  11859. return { width: this._texture._width, height: this._texture._height };
  11860. }
  11861. if (this._texture._size) {
  11862. return { width: this._texture._size, height: this._texture._size };
  11863. }
  11864. return { width: 0, height: 0 };
  11865. };
  11866. BaseTexture.prototype.getBaseSize = function () {
  11867. if (!this.isReady())
  11868. return { width: 0, height: 0 };
  11869. if (this._texture._size) {
  11870. return { width: this._texture._size, height: this._texture._size };
  11871. }
  11872. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11873. };
  11874. BaseTexture.prototype.scale = function (ratio) {
  11875. };
  11876. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11877. get: function () {
  11878. return false;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11884. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11885. for (var index = 0; index < texturesCache.length; index++) {
  11886. var texturesCacheEntry = texturesCache[index];
  11887. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11888. texturesCache.splice(index, 1);
  11889. return;
  11890. }
  11891. }
  11892. };
  11893. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11894. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11895. for (var index = 0; index < texturesCache.length; index++) {
  11896. var texturesCacheEntry = texturesCache[index];
  11897. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11898. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11899. texturesCacheEntry.references++;
  11900. return texturesCacheEntry;
  11901. }
  11902. }
  11903. }
  11904. return null;
  11905. };
  11906. BaseTexture.prototype.delayLoad = function () {
  11907. };
  11908. BaseTexture.prototype.releaseInternalTexture = function () {
  11909. if (!this._texture) {
  11910. return;
  11911. }
  11912. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11913. this._texture.references--;
  11914. // Final reference ?
  11915. if (this._texture.references === 0) {
  11916. var index = texturesCache.indexOf(this._texture);
  11917. texturesCache.splice(index, 1);
  11918. this._scene.getEngine()._releaseTexture(this._texture);
  11919. delete this._texture;
  11920. }
  11921. };
  11922. BaseTexture.prototype.clone = function () {
  11923. return null;
  11924. };
  11925. BaseTexture.prototype.dispose = function () {
  11926. // Remove from scene
  11927. var index = this._scene.textures.indexOf(this);
  11928. if (index >= 0) {
  11929. this._scene.textures.splice(index, 1);
  11930. }
  11931. if (this._texture === undefined) {
  11932. return;
  11933. }
  11934. this.releaseInternalTexture();
  11935. // Callback
  11936. if (this.onDispose) {
  11937. this.onDispose();
  11938. }
  11939. };
  11940. return BaseTexture;
  11941. })();
  11942. BABYLON.BaseTexture = BaseTexture;
  11943. })(BABYLON || (BABYLON = {}));
  11944. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11945. (function (BABYLON) {
  11946. var RenderingGroup = (function () {
  11947. function RenderingGroup(index, scene) {
  11948. this.index = index;
  11949. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11950. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11951. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11952. this._scene = scene;
  11953. }
  11954. RenderingGroup.prototype.render = function (customRenderFunction) {
  11955. if (customRenderFunction) {
  11956. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11957. return true;
  11958. }
  11959. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11960. return false;
  11961. }
  11962. var engine = this._scene.getEngine();
  11963. // Opaque
  11964. var subIndex;
  11965. var submesh;
  11966. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11967. submesh = this._opaqueSubMeshes.data[subIndex];
  11968. submesh.render();
  11969. }
  11970. // Alpha test
  11971. engine.setAlphaTesting(true);
  11972. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11973. submesh = this._alphaTestSubMeshes.data[subIndex];
  11974. submesh.render();
  11975. }
  11976. engine.setAlphaTesting(false);
  11977. // Transparent
  11978. if (this._transparentSubMeshes.length) {
  11979. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11980. submesh = this._transparentSubMeshes.data[subIndex];
  11981. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11982. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11983. }
  11984. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11985. sortedArray.sort(function (a, b) {
  11986. // Alpha index first
  11987. if (a._alphaIndex > b._alphaIndex) {
  11988. return 1;
  11989. }
  11990. if (a._alphaIndex < b._alphaIndex) {
  11991. return -1;
  11992. }
  11993. // Then distance to camera
  11994. if (a._distanceToCamera < b._distanceToCamera) {
  11995. return 1;
  11996. }
  11997. if (a._distanceToCamera > b._distanceToCamera) {
  11998. return -1;
  11999. }
  12000. return 0;
  12001. });
  12002. // Rendering
  12003. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  12004. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  12005. submesh = sortedArray[subIndex];
  12006. submesh.render();
  12007. }
  12008. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  12009. }
  12010. return true;
  12011. };
  12012. RenderingGroup.prototype.prepare = function () {
  12013. this._opaqueSubMeshes.reset();
  12014. this._transparentSubMeshes.reset();
  12015. this._alphaTestSubMeshes.reset();
  12016. };
  12017. RenderingGroup.prototype.dispatch = function (subMesh) {
  12018. var material = subMesh.getMaterial();
  12019. var mesh = subMesh.getMesh();
  12020. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  12021. this._transparentSubMeshes.push(subMesh);
  12022. }
  12023. else if (material.needAlphaTesting()) {
  12024. this._alphaTestSubMeshes.push(subMesh);
  12025. }
  12026. else {
  12027. this._opaqueSubMeshes.push(subMesh); // Opaque
  12028. }
  12029. };
  12030. return RenderingGroup;
  12031. })();
  12032. BABYLON.RenderingGroup = RenderingGroup;
  12033. })(BABYLON || (BABYLON = {}));
  12034. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  12035. (function (BABYLON) {
  12036. var RenderingManager = (function () {
  12037. function RenderingManager(scene) {
  12038. this._renderingGroups = new Array();
  12039. this._scene = scene;
  12040. }
  12041. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  12042. if (this._scene._activeParticleSystems.length === 0) {
  12043. return;
  12044. }
  12045. // Particles
  12046. var beforeParticlesDate = BABYLON.Tools.Now;
  12047. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  12048. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  12049. if (particleSystem.renderingGroupId !== index) {
  12050. continue;
  12051. }
  12052. this._clearDepthBuffer();
  12053. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  12054. this._scene._activeParticles += particleSystem.render();
  12055. }
  12056. }
  12057. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  12058. };
  12059. RenderingManager.prototype._renderSprites = function (index) {
  12060. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  12061. return;
  12062. }
  12063. // Sprites
  12064. var beforeSpritessDate = BABYLON.Tools.Now;
  12065. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  12066. var spriteManager = this._scene.spriteManagers[id];
  12067. if (spriteManager.renderingGroupId === index) {
  12068. this._clearDepthBuffer();
  12069. spriteManager.render();
  12070. }
  12071. }
  12072. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  12073. };
  12074. RenderingManager.prototype._clearDepthBuffer = function () {
  12075. if (this._depthBufferAlreadyCleaned) {
  12076. return;
  12077. }
  12078. this._scene.getEngine().clear(0, false, true);
  12079. this._depthBufferAlreadyCleaned = true;
  12080. };
  12081. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  12082. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  12083. this._depthBufferAlreadyCleaned = false;
  12084. var renderingGroup = this._renderingGroups[index];
  12085. var needToStepBack = false;
  12086. if (renderingGroup) {
  12087. this._clearDepthBuffer();
  12088. if (!renderingGroup.render(customRenderFunction)) {
  12089. this._renderingGroups.splice(index, 1);
  12090. needToStepBack = true;
  12091. }
  12092. }
  12093. if (renderSprites) {
  12094. this._renderSprites(index);
  12095. }
  12096. if (renderParticles) {
  12097. this._renderParticles(index, activeMeshes);
  12098. }
  12099. if (needToStepBack) {
  12100. index--;
  12101. }
  12102. }
  12103. };
  12104. RenderingManager.prototype.reset = function () {
  12105. for (var index in this._renderingGroups) {
  12106. var renderingGroup = this._renderingGroups[index];
  12107. renderingGroup.prepare();
  12108. }
  12109. };
  12110. RenderingManager.prototype.dispatch = function (subMesh) {
  12111. var mesh = subMesh.getMesh();
  12112. var renderingGroupId = mesh.renderingGroupId || 0;
  12113. if (!this._renderingGroups[renderingGroupId]) {
  12114. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  12115. }
  12116. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  12117. };
  12118. RenderingManager.MAX_RENDERINGGROUPS = 4;
  12119. return RenderingManager;
  12120. })();
  12121. BABYLON.RenderingManager = RenderingManager;
  12122. })(BABYLON || (BABYLON = {}));
  12123. //# sourceMappingURL=babylon.renderingManager.js.map
  12124. var BABYLON;
  12125. (function (BABYLON) {
  12126. var Texture = (function (_super) {
  12127. __extends(Texture, _super);
  12128. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  12129. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12130. if (onLoad === void 0) { onLoad = null; }
  12131. if (onError === void 0) { onError = null; }
  12132. if (buffer === void 0) { buffer = null; }
  12133. if (deleteBuffer === void 0) { deleteBuffer = false; }
  12134. _super.call(this, scene);
  12135. this.uOffset = 0;
  12136. this.vOffset = 0;
  12137. this.uScale = 1.0;
  12138. this.vScale = 1.0;
  12139. this.uAng = 0;
  12140. this.vAng = 0;
  12141. this.wAng = 0;
  12142. this.name = url;
  12143. this.url = url;
  12144. this._noMipmap = noMipmap;
  12145. this._invertY = invertY;
  12146. this._samplingMode = samplingMode;
  12147. this._buffer = buffer;
  12148. this._deleteBuffer = deleteBuffer;
  12149. if (!url) {
  12150. return;
  12151. }
  12152. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  12153. if (!this._texture) {
  12154. if (!scene.useDelayedTextureLoading) {
  12155. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12156. if (deleteBuffer) {
  12157. delete this._buffer;
  12158. }
  12159. }
  12160. else {
  12161. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12162. }
  12163. }
  12164. }
  12165. Texture.prototype.delayLoad = function () {
  12166. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12167. return;
  12168. }
  12169. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12170. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12171. if (!this._texture) {
  12172. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12173. if (this._deleteBuffer) {
  12174. delete this._buffer;
  12175. }
  12176. }
  12177. };
  12178. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12179. x -= this.uOffset + 0.5;
  12180. y -= this.vOffset + 0.5;
  12181. z -= 0.5;
  12182. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12183. t.x *= this.uScale;
  12184. t.y *= this.vScale;
  12185. t.x += 0.5;
  12186. t.y += 0.5;
  12187. t.z += 0.5;
  12188. };
  12189. Texture.prototype.getTextureMatrix = function () {
  12190. 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) {
  12191. return this._cachedTextureMatrix;
  12192. }
  12193. this._cachedUOffset = this.uOffset;
  12194. this._cachedVOffset = this.vOffset;
  12195. this._cachedUScale = this.uScale;
  12196. this._cachedVScale = this.vScale;
  12197. this._cachedUAng = this.uAng;
  12198. this._cachedVAng = this.vAng;
  12199. this._cachedWAng = this.wAng;
  12200. if (!this._cachedTextureMatrix) {
  12201. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12202. this._rowGenerationMatrix = new BABYLON.Matrix();
  12203. this._t0 = BABYLON.Vector3.Zero();
  12204. this._t1 = BABYLON.Vector3.Zero();
  12205. this._t2 = BABYLON.Vector3.Zero();
  12206. }
  12207. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12208. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12209. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12210. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12211. this._t1.subtractInPlace(this._t0);
  12212. this._t2.subtractInPlace(this._t0);
  12213. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12214. this._cachedTextureMatrix.m[0] = this._t1.x;
  12215. this._cachedTextureMatrix.m[1] = this._t1.y;
  12216. this._cachedTextureMatrix.m[2] = this._t1.z;
  12217. this._cachedTextureMatrix.m[4] = this._t2.x;
  12218. this._cachedTextureMatrix.m[5] = this._t2.y;
  12219. this._cachedTextureMatrix.m[6] = this._t2.z;
  12220. this._cachedTextureMatrix.m[8] = this._t0.x;
  12221. this._cachedTextureMatrix.m[9] = this._t0.y;
  12222. this._cachedTextureMatrix.m[10] = this._t0.z;
  12223. return this._cachedTextureMatrix;
  12224. };
  12225. Texture.prototype.getReflectionTextureMatrix = function () {
  12226. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12227. return this._cachedTextureMatrix;
  12228. }
  12229. if (!this._cachedTextureMatrix) {
  12230. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12231. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12232. }
  12233. this._cachedCoordinatesMode = this.coordinatesMode;
  12234. switch (this.coordinatesMode) {
  12235. case BABYLON.Texture.SPHERICAL_MODE:
  12236. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12237. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12238. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12239. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12240. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12241. break;
  12242. case BABYLON.Texture.PLANAR_MODE:
  12243. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12244. this._cachedTextureMatrix[0] = this.uScale;
  12245. this._cachedTextureMatrix[5] = this.vScale;
  12246. this._cachedTextureMatrix[12] = this.uOffset;
  12247. this._cachedTextureMatrix[13] = this.vOffset;
  12248. break;
  12249. case BABYLON.Texture.PROJECTION_MODE:
  12250. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12251. this._projectionModeMatrix.m[0] = 0.5;
  12252. this._projectionModeMatrix.m[5] = -0.5;
  12253. this._projectionModeMatrix.m[10] = 0.0;
  12254. this._projectionModeMatrix.m[12] = 0.5;
  12255. this._projectionModeMatrix.m[13] = 0.5;
  12256. this._projectionModeMatrix.m[14] = 1.0;
  12257. this._projectionModeMatrix.m[15] = 1.0;
  12258. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12259. break;
  12260. default:
  12261. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12262. break;
  12263. }
  12264. return this._cachedTextureMatrix;
  12265. };
  12266. Texture.prototype.clone = function () {
  12267. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12268. // Base texture
  12269. newTexture.hasAlpha = this.hasAlpha;
  12270. newTexture.level = this.level;
  12271. newTexture.wrapU = this.wrapU;
  12272. newTexture.wrapV = this.wrapV;
  12273. newTexture.coordinatesIndex = this.coordinatesIndex;
  12274. newTexture.coordinatesMode = this.coordinatesMode;
  12275. // Texture
  12276. newTexture.uOffset = this.uOffset;
  12277. newTexture.vOffset = this.vOffset;
  12278. newTexture.uScale = this.uScale;
  12279. newTexture.vScale = this.vScale;
  12280. newTexture.uAng = this.uAng;
  12281. newTexture.vAng = this.vAng;
  12282. newTexture.wAng = this.wAng;
  12283. return newTexture;
  12284. };
  12285. // Statics
  12286. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12287. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12288. if (onLoad === void 0) { onLoad = null; }
  12289. if (onError === void 0) { onError = null; }
  12290. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12291. };
  12292. // Constants
  12293. Texture.NEAREST_SAMPLINGMODE = 1;
  12294. Texture.BILINEAR_SAMPLINGMODE = 2;
  12295. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12296. Texture.EXPLICIT_MODE = 0;
  12297. Texture.SPHERICAL_MODE = 1;
  12298. Texture.PLANAR_MODE = 2;
  12299. Texture.CUBIC_MODE = 3;
  12300. Texture.PROJECTION_MODE = 4;
  12301. Texture.SKYBOX_MODE = 5;
  12302. Texture.CLAMP_ADDRESSMODE = 0;
  12303. Texture.WRAP_ADDRESSMODE = 1;
  12304. Texture.MIRROR_ADDRESSMODE = 2;
  12305. return Texture;
  12306. })(BABYLON.BaseTexture);
  12307. BABYLON.Texture = Texture;
  12308. })(BABYLON || (BABYLON = {}));
  12309. //# sourceMappingURL=babylon.texture.js.map
  12310. var BABYLON;
  12311. (function (BABYLON) {
  12312. var CubeTexture = (function (_super) {
  12313. __extends(CubeTexture, _super);
  12314. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12315. _super.call(this, scene);
  12316. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12317. this.name = rootUrl;
  12318. this.url = rootUrl;
  12319. this._noMipmap = noMipmap;
  12320. this.hasAlpha = false;
  12321. this._texture = this._getFromCache(rootUrl, noMipmap);
  12322. if (!extensions) {
  12323. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12324. }
  12325. this._extensions = extensions;
  12326. if (!this._texture) {
  12327. if (!scene.useDelayedTextureLoading) {
  12328. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12329. }
  12330. else {
  12331. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12332. }
  12333. }
  12334. this.isCube = true;
  12335. this._textureMatrix = BABYLON.Matrix.Identity();
  12336. }
  12337. CubeTexture.prototype.clone = function () {
  12338. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12339. // Base texture
  12340. newTexture.level = this.level;
  12341. newTexture.wrapU = this.wrapU;
  12342. newTexture.wrapV = this.wrapV;
  12343. newTexture.coordinatesIndex = this.coordinatesIndex;
  12344. newTexture.coordinatesMode = this.coordinatesMode;
  12345. return newTexture;
  12346. };
  12347. // Methods
  12348. CubeTexture.prototype.delayLoad = function () {
  12349. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12350. return;
  12351. }
  12352. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12353. this._texture = this._getFromCache(this.url, this._noMipmap);
  12354. if (!this._texture) {
  12355. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12356. }
  12357. };
  12358. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12359. return this._textureMatrix;
  12360. };
  12361. return CubeTexture;
  12362. })(BABYLON.BaseTexture);
  12363. BABYLON.CubeTexture = CubeTexture;
  12364. })(BABYLON || (BABYLON = {}));
  12365. //# sourceMappingURL=babylon.cubeTexture.js.map
  12366. var BABYLON;
  12367. (function (BABYLON) {
  12368. var RenderTargetTexture = (function (_super) {
  12369. __extends(RenderTargetTexture, _super);
  12370. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12371. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12372. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12373. _super.call(this, null, scene, !generateMipMaps);
  12374. this.renderList = new Array();
  12375. this.renderParticles = true;
  12376. this.renderSprites = false;
  12377. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12378. this._currentRefreshId = -1;
  12379. this._refreshRate = 1;
  12380. this.name = name;
  12381. this.isRenderTarget = true;
  12382. this._size = size;
  12383. this._generateMipMaps = generateMipMaps;
  12384. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12385. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12386. // Rendering groups
  12387. this._renderingManager = new BABYLON.RenderingManager(scene);
  12388. }
  12389. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12390. this._currentRefreshId = -1;
  12391. };
  12392. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12393. get: function () {
  12394. return this._refreshRate;
  12395. },
  12396. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12397. set: function (value) {
  12398. this._refreshRate = value;
  12399. this.resetRefreshCounter();
  12400. },
  12401. enumerable: true,
  12402. configurable: true
  12403. });
  12404. RenderTargetTexture.prototype._shouldRender = function () {
  12405. if (this._currentRefreshId === -1) {
  12406. this._currentRefreshId = 1;
  12407. return true;
  12408. }
  12409. if (this.refreshRate === this._currentRefreshId) {
  12410. this._currentRefreshId = 1;
  12411. return true;
  12412. }
  12413. this._currentRefreshId++;
  12414. return false;
  12415. };
  12416. RenderTargetTexture.prototype.isReady = function () {
  12417. if (!this.getScene().renderTargetsEnabled) {
  12418. return false;
  12419. }
  12420. return _super.prototype.isReady.call(this);
  12421. };
  12422. RenderTargetTexture.prototype.getRenderSize = function () {
  12423. return this._size;
  12424. };
  12425. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12426. get: function () {
  12427. return true;
  12428. },
  12429. enumerable: true,
  12430. configurable: true
  12431. });
  12432. RenderTargetTexture.prototype.scale = function (ratio) {
  12433. var newSize = this._size * ratio;
  12434. this.resize(newSize, this._generateMipMaps);
  12435. };
  12436. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12437. this.releaseInternalTexture();
  12438. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12439. };
  12440. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12441. var scene = this.getScene();
  12442. var engine = scene.getEngine();
  12443. if (this._waitingRenderList) {
  12444. this.renderList = [];
  12445. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12446. var id = this._waitingRenderList[index];
  12447. this.renderList.push(scene.getMeshByID(id));
  12448. }
  12449. delete this._waitingRenderList;
  12450. }
  12451. if (this.renderList && this.renderList.length === 0) {
  12452. return;
  12453. }
  12454. // Bind
  12455. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12456. engine.bindFramebuffer(this._texture);
  12457. }
  12458. this._renderingManager.reset();
  12459. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12460. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12461. var mesh = currentRenderList[meshIndex];
  12462. if (mesh) {
  12463. if (!mesh.isReady()) {
  12464. // Reset _currentRefreshId
  12465. this.resetRefreshCounter();
  12466. continue;
  12467. }
  12468. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12469. mesh._activate(scene.getRenderId());
  12470. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12471. var subMesh = mesh.subMeshes[subIndex];
  12472. scene._activeVertices += subMesh.indexCount;
  12473. this._renderingManager.dispatch(subMesh);
  12474. }
  12475. }
  12476. }
  12477. }
  12478. if (this.onBeforeRender) {
  12479. this.onBeforeRender();
  12480. }
  12481. // Clear
  12482. if (this.onClear) {
  12483. this.onClear(engine);
  12484. }
  12485. else {
  12486. engine.clear(scene.clearColor, true, true);
  12487. }
  12488. if (!this._doNotChangeAspectRatio) {
  12489. scene.updateTransformMatrix(true);
  12490. }
  12491. // Render
  12492. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12493. if (useCameraPostProcess) {
  12494. scene.postProcessManager._finalizeFrame(false, this._texture);
  12495. }
  12496. if (!this._doNotChangeAspectRatio) {
  12497. scene.updateTransformMatrix(true);
  12498. }
  12499. if (this.onAfterRender) {
  12500. this.onAfterRender();
  12501. }
  12502. // Dump ?
  12503. if (dumpForDebug) {
  12504. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12505. }
  12506. // Unbind
  12507. engine.unBindFramebuffer(this._texture);
  12508. if (this.onAfterUnbind) {
  12509. this.onAfterUnbind();
  12510. }
  12511. };
  12512. RenderTargetTexture.prototype.clone = function () {
  12513. var textureSize = this.getSize();
  12514. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12515. // Base texture
  12516. newTexture.hasAlpha = this.hasAlpha;
  12517. newTexture.level = this.level;
  12518. // RenderTarget Texture
  12519. newTexture.coordinatesMode = this.coordinatesMode;
  12520. newTexture.renderList = this.renderList.slice(0);
  12521. return newTexture;
  12522. };
  12523. return RenderTargetTexture;
  12524. })(BABYLON.Texture);
  12525. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12526. })(BABYLON || (BABYLON = {}));
  12527. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12528. var BABYLON;
  12529. (function (BABYLON) {
  12530. var ProceduralTexture = (function (_super) {
  12531. __extends(ProceduralTexture, _super);
  12532. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12533. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12534. _super.call(this, null, scene, !generateMipMaps);
  12535. this._currentRefreshId = -1;
  12536. this._refreshRate = 1;
  12537. this._vertexDeclaration = [2];
  12538. this._vertexStrideSize = 2 * 4;
  12539. this._uniforms = new Array();
  12540. this._samplers = new Array();
  12541. this._textures = new Array();
  12542. this._floats = new Array();
  12543. this._floatsArrays = {};
  12544. this._colors3 = new Array();
  12545. this._colors4 = new Array();
  12546. this._vectors2 = new Array();
  12547. this._vectors3 = new Array();
  12548. this._matrices = new Array();
  12549. this._fallbackTextureUsed = false;
  12550. scene._proceduralTextures.push(this);
  12551. this.name = name;
  12552. this.isRenderTarget = true;
  12553. this._size = size;
  12554. this._generateMipMaps = generateMipMaps;
  12555. this.setFragment(fragment);
  12556. this._fallbackTexture = fallbackTexture;
  12557. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12558. // VBO
  12559. var vertices = [];
  12560. vertices.push(1, 1);
  12561. vertices.push(-1, 1);
  12562. vertices.push(-1, -1);
  12563. vertices.push(1, -1);
  12564. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12565. // Indices
  12566. var indices = [];
  12567. indices.push(0);
  12568. indices.push(1);
  12569. indices.push(2);
  12570. indices.push(0);
  12571. indices.push(2);
  12572. indices.push(3);
  12573. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12574. }
  12575. ProceduralTexture.prototype.reset = function () {
  12576. if (this._effect === undefined) {
  12577. return;
  12578. }
  12579. var engine = this.getScene().getEngine();
  12580. engine._releaseEffect(this._effect);
  12581. };
  12582. ProceduralTexture.prototype.isReady = function () {
  12583. var _this = this;
  12584. var engine = this.getScene().getEngine();
  12585. var shaders;
  12586. if (!this._fragment) {
  12587. return false;
  12588. }
  12589. if (this._fallbackTextureUsed) {
  12590. return true;
  12591. }
  12592. if (this._fragment.fragmentElement !== undefined) {
  12593. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12594. }
  12595. else {
  12596. shaders = { vertex: "procedural", fragment: this._fragment };
  12597. }
  12598. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12599. _this.releaseInternalTexture();
  12600. if (_this._fallbackTexture) {
  12601. _this._texture = _this._fallbackTexture._texture;
  12602. _this._texture.references++;
  12603. }
  12604. _this._fallbackTextureUsed = true;
  12605. });
  12606. return this._effect.isReady();
  12607. };
  12608. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12609. this._currentRefreshId = -1;
  12610. };
  12611. ProceduralTexture.prototype.setFragment = function (fragment) {
  12612. this._fragment = fragment;
  12613. };
  12614. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12615. get: function () {
  12616. return this._refreshRate;
  12617. },
  12618. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12619. set: function (value) {
  12620. this._refreshRate = value;
  12621. this.resetRefreshCounter();
  12622. },
  12623. enumerable: true,
  12624. configurable: true
  12625. });
  12626. ProceduralTexture.prototype._shouldRender = function () {
  12627. if (!this.isReady() || !this._texture) {
  12628. return false;
  12629. }
  12630. if (this._fallbackTextureUsed) {
  12631. return false;
  12632. }
  12633. if (this._currentRefreshId === -1) {
  12634. this._currentRefreshId = 1;
  12635. return true;
  12636. }
  12637. if (this.refreshRate === this._currentRefreshId) {
  12638. this._currentRefreshId = 1;
  12639. return true;
  12640. }
  12641. this._currentRefreshId++;
  12642. return false;
  12643. };
  12644. ProceduralTexture.prototype.getRenderSize = function () {
  12645. return this._size;
  12646. };
  12647. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12648. if (this._fallbackTextureUsed) {
  12649. return;
  12650. }
  12651. this.releaseInternalTexture();
  12652. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12653. };
  12654. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12655. if (this._uniforms.indexOf(uniformName) === -1) {
  12656. this._uniforms.push(uniformName);
  12657. }
  12658. };
  12659. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12660. if (this._samplers.indexOf(name) === -1) {
  12661. this._samplers.push(name);
  12662. }
  12663. this._textures[name] = texture;
  12664. return this;
  12665. };
  12666. ProceduralTexture.prototype.setFloat = function (name, value) {
  12667. this._checkUniform(name);
  12668. this._floats[name] = value;
  12669. return this;
  12670. };
  12671. ProceduralTexture.prototype.setFloats = function (name, value) {
  12672. this._checkUniform(name);
  12673. this._floatsArrays[name] = value;
  12674. return this;
  12675. };
  12676. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12677. this._checkUniform(name);
  12678. this._colors3[name] = value;
  12679. return this;
  12680. };
  12681. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12682. this._checkUniform(name);
  12683. this._colors4[name] = value;
  12684. return this;
  12685. };
  12686. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12687. this._checkUniform(name);
  12688. this._vectors2[name] = value;
  12689. return this;
  12690. };
  12691. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12692. this._checkUniform(name);
  12693. this._vectors3[name] = value;
  12694. return this;
  12695. };
  12696. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12697. this._checkUniform(name);
  12698. this._matrices[name] = value;
  12699. return this;
  12700. };
  12701. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12702. var scene = this.getScene();
  12703. var engine = scene.getEngine();
  12704. engine.bindFramebuffer(this._texture);
  12705. // Clear
  12706. engine.clear(scene.clearColor, true, true);
  12707. // Render
  12708. engine.enableEffect(this._effect);
  12709. engine.setState(false);
  12710. for (var name in this._textures) {
  12711. this._effect.setTexture(name, this._textures[name]);
  12712. }
  12713. for (name in this._floats) {
  12714. this._effect.setFloat(name, this._floats[name]);
  12715. }
  12716. for (name in this._floatsArrays) {
  12717. this._effect.setArray(name, this._floatsArrays[name]);
  12718. }
  12719. for (name in this._colors3) {
  12720. this._effect.setColor3(name, this._colors3[name]);
  12721. }
  12722. for (name in this._colors4) {
  12723. var color = this._colors4[name];
  12724. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12725. }
  12726. for (name in this._vectors2) {
  12727. this._effect.setVector2(name, this._vectors2[name]);
  12728. }
  12729. for (name in this._vectors3) {
  12730. this._effect.setVector3(name, this._vectors3[name]);
  12731. }
  12732. for (name in this._matrices) {
  12733. this._effect.setMatrix(name, this._matrices[name]);
  12734. }
  12735. // VBOs
  12736. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12737. // Draw order
  12738. engine.draw(true, 0, 6);
  12739. // Unbind
  12740. engine.unBindFramebuffer(this._texture);
  12741. };
  12742. ProceduralTexture.prototype.clone = function () {
  12743. var textureSize = this.getSize();
  12744. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12745. // Base texture
  12746. newTexture.hasAlpha = this.hasAlpha;
  12747. newTexture.level = this.level;
  12748. // RenderTarget Texture
  12749. newTexture.coordinatesMode = this.coordinatesMode;
  12750. return newTexture;
  12751. };
  12752. ProceduralTexture.prototype.dispose = function () {
  12753. var index = this.getScene()._proceduralTextures.indexOf(this);
  12754. if (index >= 0) {
  12755. this.getScene()._proceduralTextures.splice(index, 1);
  12756. }
  12757. _super.prototype.dispose.call(this);
  12758. };
  12759. return ProceduralTexture;
  12760. })(BABYLON.Texture);
  12761. BABYLON.ProceduralTexture = ProceduralTexture;
  12762. })(BABYLON || (BABYLON = {}));
  12763. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12764. var BABYLON;
  12765. (function (BABYLON) {
  12766. var WoodProceduralTexture = (function (_super) {
  12767. __extends(WoodProceduralTexture, _super);
  12768. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12769. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12770. this._ampScale = 100.0;
  12771. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12772. this.updateShaderUniforms();
  12773. this.refreshRate = 0;
  12774. }
  12775. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12776. this.setFloat("ampScale", this._ampScale);
  12777. this.setColor3("woodColor", this._woodColor);
  12778. };
  12779. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12780. get: function () {
  12781. return this._ampScale;
  12782. },
  12783. set: function (value) {
  12784. this._ampScale = value;
  12785. this.updateShaderUniforms();
  12786. },
  12787. enumerable: true,
  12788. configurable: true
  12789. });
  12790. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12791. get: function () {
  12792. return this._woodColor;
  12793. },
  12794. set: function (value) {
  12795. this._woodColor = value;
  12796. this.updateShaderUniforms();
  12797. },
  12798. enumerable: true,
  12799. configurable: true
  12800. });
  12801. return WoodProceduralTexture;
  12802. })(BABYLON.ProceduralTexture);
  12803. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12804. var FireProceduralTexture = (function (_super) {
  12805. __extends(FireProceduralTexture, _super);
  12806. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12807. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12808. this._time = 0.0;
  12809. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12810. this._shift = 1.6;
  12811. this._autoGenerateTime = true;
  12812. this._alphaThreshold = 0.5;
  12813. this._fireColors = FireProceduralTexture.RedFireColors;
  12814. this.updateShaderUniforms();
  12815. this.refreshRate = 1;
  12816. }
  12817. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12818. this.setFloat("time", this._time);
  12819. this.setVector2("speed", this._speed);
  12820. this.setFloat("shift", this._shift);
  12821. this.setColor3("c1", this._fireColors[0]);
  12822. this.setColor3("c2", this._fireColors[1]);
  12823. this.setColor3("c3", this._fireColors[2]);
  12824. this.setColor3("c4", this._fireColors[3]);
  12825. this.setColor3("c5", this._fireColors[4]);
  12826. this.setColor3("c6", this._fireColors[5]);
  12827. this.setFloat("alphaThreshold", this._alphaThreshold);
  12828. };
  12829. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12830. if (this._autoGenerateTime) {
  12831. this._time += this.getScene().getAnimationRatio() * 0.03;
  12832. this.updateShaderUniforms();
  12833. }
  12834. _super.prototype.render.call(this, useCameraPostProcess);
  12835. };
  12836. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12837. get: function () {
  12838. return [
  12839. new BABYLON.Color3(0.5, 0.0, 1.0),
  12840. new BABYLON.Color3(0.9, 0.0, 1.0),
  12841. new BABYLON.Color3(0.2, 0.0, 1.0),
  12842. new BABYLON.Color3(1.0, 0.9, 1.0),
  12843. new BABYLON.Color3(0.1, 0.1, 1.0),
  12844. new BABYLON.Color3(0.9, 0.9, 1.0)
  12845. ];
  12846. },
  12847. enumerable: true,
  12848. configurable: true
  12849. });
  12850. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12851. get: function () {
  12852. return [
  12853. new BABYLON.Color3(0.5, 1.0, 0.0),
  12854. new BABYLON.Color3(0.5, 1.0, 0.0),
  12855. new BABYLON.Color3(0.3, 0.4, 0.0),
  12856. new BABYLON.Color3(0.5, 1.0, 0.0),
  12857. new BABYLON.Color3(0.2, 0.0, 0.0),
  12858. new BABYLON.Color3(0.5, 1.0, 0.0)
  12859. ];
  12860. },
  12861. enumerable: true,
  12862. configurable: true
  12863. });
  12864. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12865. get: function () {
  12866. return [
  12867. new BABYLON.Color3(0.5, 0.0, 0.1),
  12868. new BABYLON.Color3(0.9, 0.0, 0.0),
  12869. new BABYLON.Color3(0.2, 0.0, 0.0),
  12870. new BABYLON.Color3(1.0, 0.9, 0.0),
  12871. new BABYLON.Color3(0.1, 0.1, 0.1),
  12872. new BABYLON.Color3(0.9, 0.9, 0.9)
  12873. ];
  12874. },
  12875. enumerable: true,
  12876. configurable: true
  12877. });
  12878. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12879. get: function () {
  12880. return [
  12881. new BABYLON.Color3(0.1, 0.0, 0.5),
  12882. new BABYLON.Color3(0.0, 0.0, 0.5),
  12883. new BABYLON.Color3(0.1, 0.0, 0.2),
  12884. new BABYLON.Color3(0.0, 0.0, 1.0),
  12885. new BABYLON.Color3(0.1, 0.2, 0.3),
  12886. new BABYLON.Color3(0.0, 0.2, 0.9)
  12887. ];
  12888. },
  12889. enumerable: true,
  12890. configurable: true
  12891. });
  12892. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12893. get: function () {
  12894. return this._fireColors;
  12895. },
  12896. set: function (value) {
  12897. this._fireColors = value;
  12898. this.updateShaderUniforms();
  12899. },
  12900. enumerable: true,
  12901. configurable: true
  12902. });
  12903. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12904. get: function () {
  12905. return this._time;
  12906. },
  12907. set: function (value) {
  12908. this._time = value;
  12909. this.updateShaderUniforms();
  12910. },
  12911. enumerable: true,
  12912. configurable: true
  12913. });
  12914. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12915. get: function () {
  12916. return this._speed;
  12917. },
  12918. set: function (value) {
  12919. this._speed = value;
  12920. this.updateShaderUniforms();
  12921. },
  12922. enumerable: true,
  12923. configurable: true
  12924. });
  12925. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12926. get: function () {
  12927. return this._shift;
  12928. },
  12929. set: function (value) {
  12930. this._shift = value;
  12931. this.updateShaderUniforms();
  12932. },
  12933. enumerable: true,
  12934. configurable: true
  12935. });
  12936. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12937. get: function () {
  12938. return this._alphaThreshold;
  12939. },
  12940. set: function (value) {
  12941. this._alphaThreshold = value;
  12942. this.updateShaderUniforms();
  12943. },
  12944. enumerable: true,
  12945. configurable: true
  12946. });
  12947. return FireProceduralTexture;
  12948. })(BABYLON.ProceduralTexture);
  12949. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12950. var CloudProceduralTexture = (function (_super) {
  12951. __extends(CloudProceduralTexture, _super);
  12952. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12953. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12954. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12955. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12956. this.updateShaderUniforms();
  12957. this.refreshRate = 0;
  12958. }
  12959. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12960. this.setColor3("skyColor", this._skyColor);
  12961. this.setColor3("cloudColor", this._cloudColor);
  12962. };
  12963. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12964. get: function () {
  12965. return this._skyColor;
  12966. },
  12967. set: function (value) {
  12968. this._skyColor = value;
  12969. this.updateShaderUniforms();
  12970. },
  12971. enumerable: true,
  12972. configurable: true
  12973. });
  12974. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12975. get: function () {
  12976. return this._cloudColor;
  12977. },
  12978. set: function (value) {
  12979. this._cloudColor = value;
  12980. this.updateShaderUniforms();
  12981. },
  12982. enumerable: true,
  12983. configurable: true
  12984. });
  12985. return CloudProceduralTexture;
  12986. })(BABYLON.ProceduralTexture);
  12987. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12988. var GrassProceduralTexture = (function (_super) {
  12989. __extends(GrassProceduralTexture, _super);
  12990. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12991. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12992. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12993. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12994. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12995. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12996. this._grassColors = [
  12997. new BABYLON.Color3(0.29, 0.38, 0.02),
  12998. new BABYLON.Color3(0.36, 0.49, 0.09),
  12999. new BABYLON.Color3(0.51, 0.6, 0.28)
  13000. ];
  13001. this.updateShaderUniforms();
  13002. this.refreshRate = 0;
  13003. }
  13004. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  13005. this.setColor3("herb1Color", this._grassColors[0]);
  13006. this.setColor3("herb2Color", this._grassColors[1]);
  13007. this.setColor3("herb3Color", this._grassColors[2]);
  13008. this.setColor3("groundColor", this._groundColor);
  13009. };
  13010. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  13011. get: function () {
  13012. return this._grassColors;
  13013. },
  13014. set: function (value) {
  13015. this._grassColors = value;
  13016. this.updateShaderUniforms();
  13017. },
  13018. enumerable: true,
  13019. configurable: true
  13020. });
  13021. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  13022. get: function () {
  13023. return this._groundColor;
  13024. },
  13025. set: function (value) {
  13026. this.groundColor = value;
  13027. this.updateShaderUniforms();
  13028. },
  13029. enumerable: true,
  13030. configurable: true
  13031. });
  13032. return GrassProceduralTexture;
  13033. })(BABYLON.ProceduralTexture);
  13034. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  13035. var RoadProceduralTexture = (function (_super) {
  13036. __extends(RoadProceduralTexture, _super);
  13037. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13038. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  13039. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  13040. this.updateShaderUniforms();
  13041. this.refreshRate = 0;
  13042. }
  13043. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  13044. this.setColor3("roadColor", this._roadColor);
  13045. };
  13046. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  13047. get: function () {
  13048. return this._roadColor;
  13049. },
  13050. set: function (value) {
  13051. this._roadColor = value;
  13052. this.updateShaderUniforms();
  13053. },
  13054. enumerable: true,
  13055. configurable: true
  13056. });
  13057. return RoadProceduralTexture;
  13058. })(BABYLON.ProceduralTexture);
  13059. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  13060. var BrickProceduralTexture = (function (_super) {
  13061. __extends(BrickProceduralTexture, _super);
  13062. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13063. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  13064. this._numberOfBricksHeight = 15;
  13065. this._numberOfBricksWidth = 5;
  13066. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13067. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13068. this.updateShaderUniforms();
  13069. this.refreshRate = 0;
  13070. }
  13071. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  13072. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  13073. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  13074. this.setColor3("brickColor", this._brickColor);
  13075. this.setColor3("jointColor", this._jointColor);
  13076. };
  13077. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  13078. get: function () {
  13079. return this._numberOfBricksHeight;
  13080. },
  13081. enumerable: true,
  13082. configurable: true
  13083. });
  13084. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  13085. set: function (value) {
  13086. this._numberOfBricksHeight = value;
  13087. this.updateShaderUniforms();
  13088. },
  13089. enumerable: true,
  13090. configurable: true
  13091. });
  13092. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  13093. get: function () {
  13094. return this._numberOfBricksWidth;
  13095. },
  13096. set: function (value) {
  13097. this._numberOfBricksHeight = value;
  13098. this.updateShaderUniforms();
  13099. },
  13100. enumerable: true,
  13101. configurable: true
  13102. });
  13103. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  13104. get: function () {
  13105. return this._jointColor;
  13106. },
  13107. set: function (value) {
  13108. this._jointColor = value;
  13109. this.updateShaderUniforms();
  13110. },
  13111. enumerable: true,
  13112. configurable: true
  13113. });
  13114. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  13115. get: function () {
  13116. return this._brickColor;
  13117. },
  13118. set: function (value) {
  13119. this._brickColor = value;
  13120. this.updateShaderUniforms();
  13121. },
  13122. enumerable: true,
  13123. configurable: true
  13124. });
  13125. return BrickProceduralTexture;
  13126. })(BABYLON.ProceduralTexture);
  13127. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  13128. var MarbleProceduralTexture = (function (_super) {
  13129. __extends(MarbleProceduralTexture, _super);
  13130. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  13131. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  13132. this._numberOfTilesHeight = 3;
  13133. this._numberOfTilesWidth = 3;
  13134. this._amplitude = 9.0;
  13135. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  13136. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  13137. this.updateShaderUniforms();
  13138. this.refreshRate = 0;
  13139. }
  13140. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  13141. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  13142. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  13143. this.setFloat("amplitude", this._amplitude);
  13144. this.setColor3("marbleColor", this._marbleColor);
  13145. this.setColor3("jointColor", this._jointColor);
  13146. };
  13147. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  13148. get: function () {
  13149. return this._numberOfTilesHeight;
  13150. },
  13151. set: function (value) {
  13152. this._numberOfTilesHeight = value;
  13153. this.updateShaderUniforms();
  13154. },
  13155. enumerable: true,
  13156. configurable: true
  13157. });
  13158. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  13159. get: function () {
  13160. return this._numberOfTilesWidth;
  13161. },
  13162. set: function (value) {
  13163. this._numberOfTilesWidth = value;
  13164. this.updateShaderUniforms();
  13165. },
  13166. enumerable: true,
  13167. configurable: true
  13168. });
  13169. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13170. get: function () {
  13171. return this._jointColor;
  13172. },
  13173. set: function (value) {
  13174. this._jointColor = value;
  13175. this.updateShaderUniforms();
  13176. },
  13177. enumerable: true,
  13178. configurable: true
  13179. });
  13180. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13181. get: function () {
  13182. return this._marbleColor;
  13183. },
  13184. set: function (value) {
  13185. this._marbleColor = value;
  13186. this.updateShaderUniforms();
  13187. },
  13188. enumerable: true,
  13189. configurable: true
  13190. });
  13191. return MarbleProceduralTexture;
  13192. })(BABYLON.ProceduralTexture);
  13193. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13194. })(BABYLON || (BABYLON = {}));
  13195. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13196. var BABYLON;
  13197. (function (BABYLON) {
  13198. var CustomProceduralTexture = (function (_super) {
  13199. __extends(CustomProceduralTexture, _super);
  13200. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13201. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13202. this._animate = true;
  13203. this._time = 0;
  13204. this._texturePath = texturePath;
  13205. //Try to load json
  13206. this.loadJson(texturePath);
  13207. this.refreshRate = 1;
  13208. }
  13209. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13210. var _this = this;
  13211. var that = this;
  13212. function noConfigFile() {
  13213. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13214. try {
  13215. that.setFragment(that._texturePath);
  13216. }
  13217. catch (ex) {
  13218. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13219. }
  13220. }
  13221. var configFileUrl = jsonUrl + "/config.json";
  13222. var xhr = new XMLHttpRequest();
  13223. xhr.open("GET", configFileUrl, true);
  13224. xhr.addEventListener("load", function () {
  13225. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13226. try {
  13227. _this._config = JSON.parse(xhr.response);
  13228. _this.updateShaderUniforms();
  13229. _this.updateTextures();
  13230. _this.setFragment(_this._texturePath + "/custom");
  13231. _this._animate = _this._config.animate;
  13232. _this.refreshRate = _this._config.refreshrate;
  13233. }
  13234. catch (ex) {
  13235. noConfigFile();
  13236. }
  13237. }
  13238. else {
  13239. noConfigFile();
  13240. }
  13241. }, false);
  13242. xhr.addEventListener("error", function () {
  13243. noConfigFile();
  13244. }, false);
  13245. try {
  13246. xhr.send();
  13247. }
  13248. catch (ex) {
  13249. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13250. }
  13251. };
  13252. CustomProceduralTexture.prototype.isReady = function () {
  13253. if (!_super.prototype.isReady.call(this)) {
  13254. return false;
  13255. }
  13256. for (var name in this._textures) {
  13257. var texture = this._textures[name];
  13258. if (!texture.isReady()) {
  13259. return false;
  13260. }
  13261. }
  13262. return true;
  13263. };
  13264. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13265. if (this._animate) {
  13266. this._time += this.getScene().getAnimationRatio() * 0.03;
  13267. this.updateShaderUniforms();
  13268. }
  13269. _super.prototype.render.call(this, useCameraPostProcess);
  13270. };
  13271. CustomProceduralTexture.prototype.updateTextures = function () {
  13272. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13273. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13274. }
  13275. };
  13276. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13277. if (this._config) {
  13278. for (var j = 0; j < this._config.uniforms.length; j++) {
  13279. var uniform = this._config.uniforms[j];
  13280. switch (uniform.type) {
  13281. case "float":
  13282. this.setFloat(uniform.name, uniform.value);
  13283. break;
  13284. case "color3":
  13285. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13286. break;
  13287. case "color4":
  13288. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13289. break;
  13290. case "vector2":
  13291. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13292. break;
  13293. case "vector3":
  13294. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13295. break;
  13296. }
  13297. }
  13298. }
  13299. this.setFloat("time", this._time);
  13300. };
  13301. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13302. get: function () {
  13303. return this._animate;
  13304. },
  13305. set: function (value) {
  13306. this._animate = value;
  13307. },
  13308. enumerable: true,
  13309. configurable: true
  13310. });
  13311. return CustomProceduralTexture;
  13312. })(BABYLON.ProceduralTexture);
  13313. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13314. })(BABYLON || (BABYLON = {}));
  13315. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13316. var BABYLON;
  13317. (function (BABYLON) {
  13318. var MirrorTexture = (function (_super) {
  13319. __extends(MirrorTexture, _super);
  13320. function MirrorTexture(name, size, scene, generateMipMaps) {
  13321. var _this = this;
  13322. _super.call(this, name, size, scene, generateMipMaps, true);
  13323. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13324. this._transformMatrix = BABYLON.Matrix.Zero();
  13325. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13326. this.onBeforeRender = function () {
  13327. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13328. _this._savedViewMatrix = scene.getViewMatrix();
  13329. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13330. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13331. scene.clipPlane = _this.mirrorPlane;
  13332. scene.getEngine().cullBackFaces = false;
  13333. };
  13334. this.onAfterRender = function () {
  13335. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13336. scene.getEngine().cullBackFaces = true;
  13337. delete scene.clipPlane;
  13338. };
  13339. }
  13340. MirrorTexture.prototype.clone = function () {
  13341. var textureSize = this.getSize();
  13342. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13343. // Base texture
  13344. newTexture.hasAlpha = this.hasAlpha;
  13345. newTexture.level = this.level;
  13346. // Mirror Texture
  13347. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13348. newTexture.renderList = this.renderList.slice(0);
  13349. return newTexture;
  13350. };
  13351. return MirrorTexture;
  13352. })(BABYLON.RenderTargetTexture);
  13353. BABYLON.MirrorTexture = MirrorTexture;
  13354. })(BABYLON || (BABYLON = {}));
  13355. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13356. var BABYLON;
  13357. (function (BABYLON) {
  13358. var DynamicTexture = (function (_super) {
  13359. __extends(DynamicTexture, _super);
  13360. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13362. _super.call(this, null, scene, !generateMipMaps);
  13363. this.name = name;
  13364. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13365. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13366. this._generateMipMaps = generateMipMaps;
  13367. if (options.getContext) {
  13368. this._canvas = options;
  13369. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13370. }
  13371. else {
  13372. this._canvas = document.createElement("canvas");
  13373. if (options.width) {
  13374. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13375. }
  13376. else {
  13377. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13378. }
  13379. }
  13380. var textureSize = this.getSize();
  13381. this._canvas.width = textureSize.width;
  13382. this._canvas.height = textureSize.height;
  13383. this._context = this._canvas.getContext("2d");
  13384. }
  13385. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13386. get: function () {
  13387. return true;
  13388. },
  13389. enumerable: true,
  13390. configurable: true
  13391. });
  13392. DynamicTexture.prototype.scale = function (ratio) {
  13393. var textureSize = this.getSize();
  13394. textureSize.width *= ratio;
  13395. textureSize.height *= ratio;
  13396. this._canvas.width = textureSize.width;
  13397. this._canvas.height = textureSize.height;
  13398. this.releaseInternalTexture();
  13399. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13400. };
  13401. DynamicTexture.prototype.getContext = function () {
  13402. return this._context;
  13403. };
  13404. DynamicTexture.prototype.clear = function () {
  13405. var size = this.getSize();
  13406. this._context.fillRect(0, 0, size.width, size.height);
  13407. };
  13408. DynamicTexture.prototype.update = function (invertY) {
  13409. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13410. };
  13411. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13412. if (update === void 0) { update = true; }
  13413. var size = this.getSize();
  13414. if (clearColor) {
  13415. this._context.fillStyle = clearColor;
  13416. this._context.fillRect(0, 0, size.width, size.height);
  13417. }
  13418. this._context.font = font;
  13419. if (x === null) {
  13420. var textSize = this._context.measureText(text);
  13421. x = (size.width - textSize.width) / 2;
  13422. }
  13423. this._context.fillStyle = color;
  13424. this._context.fillText(text, x, y);
  13425. if (update) {
  13426. this.update(invertY);
  13427. }
  13428. };
  13429. DynamicTexture.prototype.clone = function () {
  13430. var textureSize = this.getSize();
  13431. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13432. // Base texture
  13433. newTexture.hasAlpha = this.hasAlpha;
  13434. newTexture.level = this.level;
  13435. // Dynamic Texture
  13436. newTexture.wrapU = this.wrapU;
  13437. newTexture.wrapV = this.wrapV;
  13438. return newTexture;
  13439. };
  13440. return DynamicTexture;
  13441. })(BABYLON.Texture);
  13442. BABYLON.DynamicTexture = DynamicTexture;
  13443. })(BABYLON || (BABYLON = {}));
  13444. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13445. var BABYLON;
  13446. (function (BABYLON) {
  13447. var VideoTexture = (function (_super) {
  13448. __extends(VideoTexture, _super);
  13449. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13450. var _this = this;
  13451. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13452. _super.call(this, null, scene, !generateMipMaps, invertY);
  13453. this._autoLaunch = true;
  13454. this.name = name;
  13455. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13456. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13457. var requiredWidth = size.width || size;
  13458. var requiredHeight = size.height || size;
  13459. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13460. var textureSize = this.getSize();
  13461. this.video = document.createElement("video");
  13462. this.video.width = textureSize.width;
  13463. this.video.height = textureSize.height;
  13464. this.video.autoplay = false;
  13465. this.video.loop = true;
  13466. this.video.addEventListener("canplaythrough", function () {
  13467. if (_this._texture) {
  13468. _this._texture.isReady = true;
  13469. }
  13470. });
  13471. urls.forEach(function (url) {
  13472. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13473. var source = document.createElement("source");
  13474. source.src = url;
  13475. _this.video.appendChild(source);
  13476. });
  13477. this._lastUpdate = BABYLON.Tools.Now;
  13478. }
  13479. VideoTexture.prototype.update = function () {
  13480. if (this._autoLaunch) {
  13481. this._autoLaunch = false;
  13482. this.video.play();
  13483. }
  13484. var now = BABYLON.Tools.Now;
  13485. if (now - this._lastUpdate < 15) {
  13486. return false;
  13487. }
  13488. this._lastUpdate = now;
  13489. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13490. return true;
  13491. };
  13492. return VideoTexture;
  13493. })(BABYLON.Texture);
  13494. BABYLON.VideoTexture = VideoTexture;
  13495. })(BABYLON || (BABYLON = {}));
  13496. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13497. (function (BABYLON) {
  13498. var EffectFallbacks = (function () {
  13499. function EffectFallbacks() {
  13500. this._defines = {};
  13501. this._currentRank = 32;
  13502. this._maxRank = -1;
  13503. }
  13504. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13505. if (!this._defines[rank]) {
  13506. if (rank < this._currentRank) {
  13507. this._currentRank = rank;
  13508. }
  13509. if (rank > this._maxRank) {
  13510. this._maxRank = rank;
  13511. }
  13512. this._defines[rank] = new Array();
  13513. }
  13514. this._defines[rank].push(define);
  13515. };
  13516. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13517. get: function () {
  13518. return this._currentRank <= this._maxRank;
  13519. },
  13520. enumerable: true,
  13521. configurable: true
  13522. });
  13523. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13524. var currentFallbacks = this._defines[this._currentRank];
  13525. for (var index = 0; index < currentFallbacks.length; index++) {
  13526. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13527. }
  13528. this._currentRank++;
  13529. return currentDefines;
  13530. };
  13531. return EffectFallbacks;
  13532. })();
  13533. BABYLON.EffectFallbacks = EffectFallbacks;
  13534. var Effect = (function () {
  13535. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13536. var _this = this;
  13537. this._isReady = false;
  13538. this._compilationError = "";
  13539. this._valueCache = [];
  13540. this._engine = engine;
  13541. this.name = baseName;
  13542. this.defines = defines;
  13543. this._uniformsNames = uniformsNames.concat(samplers);
  13544. this._samplers = samplers;
  13545. this._attributesNames = attributesNames;
  13546. this.onError = onError;
  13547. this.onCompiled = onCompiled;
  13548. var vertexSource;
  13549. var fragmentSource;
  13550. if (baseName.vertexElement) {
  13551. vertexSource = document.getElementById(baseName.vertexElement);
  13552. if (!vertexSource) {
  13553. vertexSource = baseName.vertexElement;
  13554. }
  13555. }
  13556. else {
  13557. vertexSource = baseName.vertex || baseName;
  13558. }
  13559. if (baseName.fragmentElement) {
  13560. fragmentSource = document.getElementById(baseName.fragmentElement);
  13561. if (!fragmentSource) {
  13562. fragmentSource = baseName.fragmentElement;
  13563. }
  13564. }
  13565. else {
  13566. fragmentSource = baseName.fragment || baseName;
  13567. }
  13568. this._loadVertexShader(vertexSource, function (vertexCode) {
  13569. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13570. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13571. });
  13572. });
  13573. }
  13574. // Properties
  13575. Effect.prototype.isReady = function () {
  13576. return this._isReady;
  13577. };
  13578. Effect.prototype.getProgram = function () {
  13579. return this._program;
  13580. };
  13581. Effect.prototype.getAttributesNames = function () {
  13582. return this._attributesNames;
  13583. };
  13584. Effect.prototype.getAttributeLocation = function (index) {
  13585. return this._attributes[index];
  13586. };
  13587. Effect.prototype.getAttributeLocationByName = function (name) {
  13588. var index = this._attributesNames.indexOf(name);
  13589. return this._attributes[index];
  13590. };
  13591. Effect.prototype.getAttributesCount = function () {
  13592. return this._attributes.length;
  13593. };
  13594. Effect.prototype.getUniformIndex = function (uniformName) {
  13595. return this._uniformsNames.indexOf(uniformName);
  13596. };
  13597. Effect.prototype.getUniform = function (uniformName) {
  13598. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13599. };
  13600. Effect.prototype.getSamplers = function () {
  13601. return this._samplers;
  13602. };
  13603. Effect.prototype.getCompilationError = function () {
  13604. return this._compilationError;
  13605. };
  13606. // Methods
  13607. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13608. // DOM element ?
  13609. if (vertex instanceof HTMLElement) {
  13610. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13611. callback(vertexCode);
  13612. return;
  13613. }
  13614. // Is in local store ?
  13615. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13616. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13617. return;
  13618. }
  13619. var vertexShaderUrl;
  13620. if (vertex[0] === ".") {
  13621. vertexShaderUrl = vertex;
  13622. }
  13623. else {
  13624. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13625. }
  13626. // Vertex shader
  13627. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13628. };
  13629. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13630. // DOM element ?
  13631. if (fragment instanceof HTMLElement) {
  13632. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13633. callback(fragmentCode);
  13634. return;
  13635. }
  13636. // Is in local store ?
  13637. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13638. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13639. return;
  13640. }
  13641. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13642. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13643. return;
  13644. }
  13645. var fragmentShaderUrl;
  13646. if (fragment[0] === ".") {
  13647. fragmentShaderUrl = fragment;
  13648. }
  13649. else {
  13650. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13651. }
  13652. // Fragment shader
  13653. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13654. };
  13655. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13656. try {
  13657. var engine = this._engine;
  13658. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13659. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13660. this._attributes = engine.getAttributes(this._program, attributesNames);
  13661. for (var index = 0; index < this._samplers.length; index++) {
  13662. var sampler = this.getUniform(this._samplers[index]);
  13663. if (sampler == null) {
  13664. this._samplers.splice(index, 1);
  13665. index--;
  13666. }
  13667. }
  13668. engine.bindSamplers(this);
  13669. this._isReady = true;
  13670. if (this.onCompiled) {
  13671. this.onCompiled(this);
  13672. }
  13673. }
  13674. catch (e) {
  13675. // Is it a problem with precision?
  13676. if (e.message.indexOf("highp") !== -1) {
  13677. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13678. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13679. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13680. return;
  13681. }
  13682. // Let's go through fallbacks then
  13683. if (fallbacks && fallbacks.isMoreFallbacks) {
  13684. defines = fallbacks.reduce(defines);
  13685. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13686. }
  13687. else {
  13688. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13689. BABYLON.Tools.Error("Defines: " + defines);
  13690. BABYLON.Tools.Error("Error: " + e.message);
  13691. this._compilationError = e.message;
  13692. if (this.onError) {
  13693. this.onError(this, this._compilationError);
  13694. }
  13695. }
  13696. }
  13697. };
  13698. Effect.prototype._bindTexture = function (channel, texture) {
  13699. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13700. };
  13701. Effect.prototype.setTexture = function (channel, texture) {
  13702. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13703. };
  13704. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13705. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13706. };
  13707. //public _cacheMatrix(uniformName, matrix) {
  13708. // if (!this._valueCache[uniformName]) {
  13709. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13710. // }
  13711. // for (var index = 0; index < 16; index++) {
  13712. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13713. // }
  13714. //};
  13715. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13716. if (!this._valueCache[uniformName]) {
  13717. this._valueCache[uniformName] = [x, y];
  13718. return;
  13719. }
  13720. this._valueCache[uniformName][0] = x;
  13721. this._valueCache[uniformName][1] = y;
  13722. };
  13723. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13724. if (!this._valueCache[uniformName]) {
  13725. this._valueCache[uniformName] = [x, y, z];
  13726. return;
  13727. }
  13728. this._valueCache[uniformName][0] = x;
  13729. this._valueCache[uniformName][1] = y;
  13730. this._valueCache[uniformName][2] = z;
  13731. };
  13732. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13733. if (!this._valueCache[uniformName]) {
  13734. this._valueCache[uniformName] = [x, y, z, w];
  13735. return;
  13736. }
  13737. this._valueCache[uniformName][0] = x;
  13738. this._valueCache[uniformName][1] = y;
  13739. this._valueCache[uniformName][2] = z;
  13740. this._valueCache[uniformName][3] = w;
  13741. };
  13742. Effect.prototype.setArray = function (uniformName, array) {
  13743. this._engine.setArray(this.getUniform(uniformName), array);
  13744. return this;
  13745. };
  13746. Effect.prototype.setArray2 = function (uniformName, array) {
  13747. this._engine.setArray2(this.getUniform(uniformName), array);
  13748. return this;
  13749. };
  13750. Effect.prototype.setArray3 = function (uniformName, array) {
  13751. this._engine.setArray3(this.getUniform(uniformName), array);
  13752. return this;
  13753. };
  13754. Effect.prototype.setArray4 = function (uniformName, array) {
  13755. this._engine.setArray4(this.getUniform(uniformName), array);
  13756. return this;
  13757. };
  13758. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13759. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13760. return this;
  13761. };
  13762. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13763. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13764. // return;
  13765. //this._cacheMatrix(uniformName, matrix);
  13766. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13767. return this;
  13768. };
  13769. Effect.prototype.setFloat = function (uniformName, value) {
  13770. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13771. return this;
  13772. this._valueCache[uniformName] = value;
  13773. this._engine.setFloat(this.getUniform(uniformName), value);
  13774. return this;
  13775. };
  13776. Effect.prototype.setBool = function (uniformName, bool) {
  13777. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13778. return this;
  13779. this._valueCache[uniformName] = bool;
  13780. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13781. return this;
  13782. };
  13783. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13784. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13785. return this;
  13786. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13787. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13788. return this;
  13789. };
  13790. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13791. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13792. return this;
  13793. this._cacheFloat2(uniformName, x, y);
  13794. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13795. return this;
  13796. };
  13797. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13798. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13799. return this;
  13800. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13801. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13802. return this;
  13803. };
  13804. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13805. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13806. return this;
  13807. this._cacheFloat3(uniformName, x, y, z);
  13808. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13809. return this;
  13810. };
  13811. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13812. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13813. return this;
  13814. this._cacheFloat4(uniformName, x, y, z, w);
  13815. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13816. return this;
  13817. };
  13818. Effect.prototype.setColor3 = function (uniformName, color3) {
  13819. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13820. return this;
  13821. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13822. this._engine.setColor3(this.getUniform(uniformName), color3);
  13823. return this;
  13824. };
  13825. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13826. 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)
  13827. return this;
  13828. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13829. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13830. return this;
  13831. };
  13832. // Statics
  13833. 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}",
  13834. 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}",
  13835. 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}",
  13836. 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}",
  13837. 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}",
  13838. 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}",
  13839. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13840. 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}",
  13841. 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}",
  13842. 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}",
  13843. defaultPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#define MAP_EXPLICIT 0.\n#define MAP_SPHERICAL 1.\n#define MAP_PLANAR 2.\n#define MAP_CUBIC 3.\n#define MAP_PROJECTION 4.\n#define MAP_SKYBOX 5.\n\n// Constants\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\nuniform vec4 vSpecularColor;\nuniform vec3 vEmissiveColor;\n\n// Input\nvarying vec3 vPositionW;\n\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n// Lights\n#ifdef LIGHT0\nuniform vec4 vLightData0;\nuniform vec4 vLightDiffuse0;\nuniform vec3 vLightSpecular0;\n#ifdef SHADOW0\nvarying vec4 vPositionFromLight0;\nuniform sampler2D shadowSampler0;\nuniform vec3 shadowsInfo0;\n#endif\n#ifdef SPOTLIGHT0\nuniform vec4 vLightDirection0;\n#endif\n#ifdef HEMILIGHT0\nuniform vec3 vLightGround0;\n#endif\n#endif\n\n#ifdef LIGHT1\nuniform vec4 vLightData1;\nuniform vec4 vLightDiffuse1;\nuniform vec3 vLightSpecular1;\n#ifdef SHADOW1\nvarying vec4 vPositionFromLight1;\nuniform sampler2D shadowSampler1;\nuniform vec3 shadowsInfo1;\n#endif\n#ifdef SPOTLIGHT1\nuniform vec4 vLightDirection1;\n#endif\n#ifdef HEMILIGHT1\nuniform vec3 vLightGround1;\n#endif\n#endif\n\n#ifdef LIGHT2\nuniform vec4 vLightData2;\nuniform vec4 vLightDiffuse2;\nuniform vec3 vLightSpecular2;\n#ifdef SHADOW2\nvarying vec4 vPositionFromLight2;\nuniform sampler2D shadowSampler2;\nuniform vec3 shadowsInfo2;\n#endif\n#ifdef SPOTLIGHT2\nuniform vec4 vLightDirection2;\n#endif\n#ifdef HEMILIGHT2\nuniform vec3 vLightGround2;\n#endif\n#endif\n\n#ifdef LIGHT3\nuniform vec4 vLightData3;\nuniform vec4 vLightDiffuse3;\nuniform vec3 vLightSpecular3;\n#ifdef SHADOW3\nvarying vec4 vPositionFromLight3;\nuniform sampler2D shadowSampler3;\nuniform vec3 shadowsInfo3;\n#endif\n#ifdef SPOTLIGHT3\nuniform vec4 vLightDirection3;\n#endif\n#ifdef HEMILIGHT3\nuniform vec3 vLightGround3;\n#endif\n#endif\n\n// Samplers\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n\n#ifdef SPECULAR\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n// Fresnel\n#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection, vec3 worldNormal, float bias, float power)\n{\n float fresnelTerm = pow(bias + abs(dot(viewDirection, worldNormal)), power);\n return clamp(fresnelTerm, 0., 1.);\n}\n#endif\n\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n// Reflection\n#ifdef REFLECTION\nvarying vec3 vPositionUVW;\nuniform samplerCube reflectionCubeSampler;\nuniform sampler2D reflection2DSampler;\nuniform vec3 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform mat4 view;\n\nvec3 computeReflectionCoords(float mode, vec4 worldPos, vec3 worldNormal)\n{\n if (mode == MAP_SPHERICAL)\n {\n vec3 coords = vec3(view * vec4(worldNormal, 0.0));\n\n return vec3(reflectionMatrix * vec4(coords, 1.0));\n }\n else if (mode == MAP_PLANAR)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = normalize(reflect(viewDir, worldNormal));\n\n return vec3(reflectionMatrix * vec4(coords, 1));\n }\n else if (mode == MAP_CUBIC)\n {\n vec3 viewDir = worldPos.xyz - vEyePosition;\n vec3 coords = reflect(viewDir, worldNormal);\n\n return vec3(reflectionMatrix * vec4(coords, 0));\n }\n else if (mode == MAP_PROJECTION)\n {\n return vec3(reflectionMatrix * (view * worldPos));\n }\n else if (mode == MAP_SKYBOX)\n {\n return vPositionUVW;\n }\n\n return vec3(0, 0, 0);\n}\n#endif\n\n// Shadows\n#ifdef SHADOWS\n\nfloat unpack(vec4 color)\n{\n const vec4 bit_shift = vec4(1.0 / (255.0 * 255.0 * 255.0), 1.0 / (255.0 * 255.0), 1.0 / 255.0, 1.0);\n return dot(color, bit_shift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float shadow = unpack(texture2D(shadowSampler, uv)) + bias;\n\n if (depth.z > shadow)\n {\n return darkness;\n }\n return 1.;\n}\n\nfloat computeShadowWithPCF(vec4 vPositionFromLight, sampler2D shadowSampler, float mapSize, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[1] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[2] / mapSize)) + bias < depth.z) visibility -= 0.25;\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[3] / mapSize)) + bias < depth.z) visibility -= 0.25;\n\n return visibility;\n}\n\n// Thanks to http://devmaster.net/\nfloat ChebychevInequality(vec2 moments, float t, float bias)\n{\n bias = 0.02 + bias;\n if (t <= moments.x)\n {\n return 0.0;\n }\n\n float variance = moments.y - (moments.x * moments.x);\n variance = max(variance, bias);\n\n float d = t - moments.x;\n\n return clamp(variance / (variance + d * d) - 0.05 - bias, 0.0, 1.0);\n}\n\nfloat computeShadowWithVSM(vec4 vPositionFromLight, sampler2D shadowSampler, float bias)\n{\n vec3 depth = vPositionFromLight.xyz / vPositionFromLight.w;\n depth = 0.5 * depth + vec3(0.5);\n vec2 uv = depth.xy;\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0 || depth.z > 1.0)\n {\n return 1.0;\n }\n\n vec4 texel = texture2D(shadowSampler, uv);\n\n vec2 moments = vec2(unpackHalf(texel.xy), unpackHalf(texel.zw));\n return 1.0 - ChebychevInequality(moments, depth.z, bias);\n}\n#endif\n\n// Bump\n#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\nvarying vec2 vBumpUV;\nuniform vec2 vBumpInfos;\nuniform sampler2D bumpSampler;\n\n// Thanks to http://www.thetenthplanet.de/archives/1180\nmat3 cotangent_frame(vec3 normal, vec3 p, vec2 uv)\n{\n // get edge vectors of the pixel triangle\n vec3 dp1 = dFdx(p);\n vec3 dp2 = dFdy(p);\n vec2 duv1 = dFdx(uv);\n vec2 duv2 = dFdy(uv);\n\n // solve the linear system\n vec3 dp2perp = cross(dp2, normal);\n vec3 dp1perp = cross(normal, dp1);\n vec3 tangent = dp2perp * duv1.x + dp1perp * duv2.x;\n vec3 binormal = dp2perp * duv1.y + dp1perp * duv2.y;\n\n // construct a scale-invariant frame \n float invmax = inversesqrt(max(dot(tangent, tangent), dot(binormal, binormal)));\n return mat3(tangent * invmax, binormal * invmax, normal);\n}\n\nvec3 perturbNormal(vec3 viewDir)\n{\n vec3 map = texture2D(bumpSampler, vBumpUV).xyz;\n map = map * 255. / 127. - 128. / 127.;\n mat3 TBN = cotangent_frame(vNormalW * vBumpInfos.y, -viewDir, vBumpUV);\n return normalize(TBN * map);\n}\n#endif\n\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\n\n// Fog\n#ifdef FOG\n\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\n\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying float fFogDistance;\n\nfloat CalcFogFactor()\n{\n float fogCoeff = 1.0;\n float fogStart = vFogInfos.y;\n float fogEnd = vFogInfos.z;\n float fogDensity = vFogInfos.w;\n\n if (FOGMODE_LINEAR == vFogInfos.x)\n {\n fogCoeff = (fogEnd - fFogDistance) / (fogEnd - fogStart);\n }\n else if (FOGMODE_EXP == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fogDensity);\n }\n else if (FOGMODE_EXP2 == vFogInfos.x)\n {\n fogCoeff = 1.0 / pow(E, fFogDistance * fFogDistance * fogDensity * fogDensity);\n }\n\n return clamp(fogCoeff, 0.0, 1.0);\n}\n#endif\n\n// Light Computing\nstruct lightingInfo\n{\n vec3 diffuse;\n vec3 specular;\n};\n\nlightingInfo computeLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 lightVectorW;\n float attenuation = 1.0;\n if (lightData.w == 0.)\n {\n vec3 direction = lightData.xyz - vPositionW;\n\n attenuation = max(0., 1.0 - length(direction) / range);\n lightVectorW = normalize(direction);\n }\n else\n {\n lightVectorW = normalize(-lightData.xyz);\n }\n\n // diffuse\n float ndl = max(0., dot(vNormal, lightVectorW));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightVectorW);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, max(1., vSpecularColor.a));\n\n result.diffuse = ndl * diffuseColor * attenuation;\n result.specular = specComp * specularColor * attenuation;\n\n return result;\n}\n\nlightingInfo computeSpotLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec4 lightDirection, vec3 diffuseColor, vec3 specularColor, float range) {\n lightingInfo result;\n\n vec3 direction = lightData.xyz - vPositionW;\n vec3 lightVectorW = normalize(direction);\n float attenuation = max(0., 1.0 - length(direction) / range);\n\n // diffuse\n float cosAngle = max(0., dot(-lightDirection.xyz, lightVectorW));\n float spotAtten = 0.0;\n\n if (cosAngle >= lightDirection.w)\n {\n cosAngle = max(0., pow(cosAngle, lightData.w));\n spotAtten = clamp((cosAngle - lightDirection.w) / (1. - cosAngle), 0.0, 1.0);\n\n // Diffuse\n float ndl = max(0., dot(vNormal, -lightDirection.xyz));\n\n // Specular\n vec3 angleW = normalize(viewDirectionW - lightDirection.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = ndl * spotAtten * diffuseColor * attenuation;\n result.specular = specComp * specularColor * spotAtten * attenuation;\n\n return result;\n }\n\n result.diffuse = vec3(0.);\n result.specular = vec3(0.);\n\n return result;\n}\n\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW, vec3 vNormal, vec4 lightData, vec3 diffuseColor, vec3 specularColor, vec3 groundColor) {\n lightingInfo result;\n\n // Diffuse\n float ndl = dot(vNormal, lightData.xyz) * 0.5 + 0.5;\n\n // Specular\n vec3 angleW = normalize(viewDirectionW + lightData.xyz);\n float specComp = max(0., dot(vNormal, angleW));\n specComp = pow(specComp, vSpecularColor.a);\n\n result.diffuse = mix(groundColor, diffuseColor, ndl);\n result.specular = specComp * specularColor;\n\n return result;\n}\n\nvoid main(void) {\n // Clip plane\n#ifdef CLIPPLANE\n if (fClipDistance > 0.0)\n discard;\n#endif\n\n vec3 viewDirectionW = normalize(vEyePosition - vPositionW);\n\n // Base color\n vec4 baseColor = vec4(1., 1., 1., 1.);\n vec3 diffuseColor = vDiffuseColor.rgb;\n\n // Alpha\n float alpha = vDiffuseColor.a;\n\n#ifdef VERTEXCOLOR\n baseColor.rgb *= vColor.rgb;\n#endif\n\n#ifdef DIFFUSE\n baseColor = texture2D(diffuseSampler, vDiffuseUV);\n\n#ifdef ALPHATEST\n if (baseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef ALPHAFROMDIFFUSE\n alpha *= baseColor.a;\n#endif\n\n baseColor.rgb *= vDiffuseInfos.y;\n#endif\n\n // Bump\n#ifdef NORMAL\n vec3 normalW = normalize(vNormalW);\n#else\n vec3 normalW = vec3(1.0, 1.0, 1.0);\n#endif\n\n\n#ifdef BUMP\n normalW = perturbNormal(viewDirectionW);\n#endif\n\n\n // Ambient color\n vec3 baseAmbientColor = vec3(1., 1., 1.);\n\n#ifdef AMBIENT\n baseAmbientColor = texture2D(ambientSampler, vAmbientUV).rgb * vAmbientInfos.y;\n#endif\n\n // Lighting\n vec3 diffuseBase = vec3(0., 0., 0.);\n vec3 specularBase = vec3(0., 0., 0.);\n float shadow = 1.;\n\n#ifdef LIGHT0\n#ifdef SPOTLIGHT0\n lightingInfo info = computeSpotLighting(viewDirectionW, normalW, vLightData0, vLightDirection0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef HEMILIGHT0\n lightingInfo info = computeHemisphericLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightGround0);\n#endif\n#ifdef POINTDIRLIGHT0\n lightingInfo info = computeLighting(viewDirectionW, normalW, vLightData0, vLightDiffuse0.rgb, vLightSpecular0, vLightDiffuse0.a);\n#endif\n#ifdef SHADOW0\n#ifdef SHADOWVSM0\n shadow = computeShadowWithVSM(vPositionFromLight0, shadowSampler0, shadowsInfo0.z);\n#else\n #ifdef SHADOWPCF0\n shadow = computeShadowWithPCF(vPositionFromLight0, shadowSampler0, shadowsInfo0.y, shadowsInfo0.z);\n #else\n shadow = computeShadow(vPositionFromLight0, shadowSampler0, shadowsInfo0.x, shadowsInfo0.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT1\n#ifdef SPOTLIGHT1\n info = computeSpotLighting(viewDirectionW, normalW, vLightData1, vLightDirection1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef HEMILIGHT1\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightGround1);\n#endif\n#ifdef POINTDIRLIGHT1\n info = computeLighting(viewDirectionW, normalW, vLightData1, vLightDiffuse1.rgb, vLightSpecular1, vLightDiffuse1.a);\n#endif\n#ifdef SHADOW1\n#ifdef SHADOWVSM1\n shadow = computeShadowWithVSM(vPositionFromLight1, shadowSampler1, shadowsInfo1.z);\n#else\n #ifdef SHADOWPCF1\n shadow = computeShadowWithPCF(vPositionFromLight1, shadowSampler1, shadowsInfo1.y, shadowsInfo1.z);\n #else\n shadow = computeShadow(vPositionFromLight1, shadowSampler1, shadowsInfo1.x, shadowsInfo1.z);\n #endif\n#endif\n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT2\n#ifdef SPOTLIGHT2\n info = computeSpotLighting(viewDirectionW, normalW, vLightData2, vLightDirection2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef HEMILIGHT2\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightGround2);\n#endif\n#ifdef POINTDIRLIGHT2\n info = computeLighting(viewDirectionW, normalW, vLightData2, vLightDiffuse2.rgb, vLightSpecular2, vLightDiffuse2.a);\n#endif\n#ifdef SHADOW2\n#ifdef SHADOWVSM2\n shadow = computeShadowWithVSM(vPositionFromLight2, shadowSampler2, shadowsInfo2.z);\n#else\n #ifdef SHADOWPCF2\n shadow = computeShadowWithPCF(vPositionFromLight2, shadowSampler2, shadowsInfo2.y, shadowsInfo2.z);\n #else\n shadow = computeShadow(vPositionFromLight2, shadowSampler2, shadowsInfo2.x, shadowsInfo2.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n#ifdef LIGHT3\n#ifdef SPOTLIGHT3\n info = computeSpotLighting(viewDirectionW, normalW, vLightData3, vLightDirection3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef HEMILIGHT3\n info = computeHemisphericLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightGround3);\n#endif\n#ifdef POINTDIRLIGHT3\n info = computeLighting(viewDirectionW, normalW, vLightData3, vLightDiffuse3.rgb, vLightSpecular3, vLightDiffuse3.a);\n#endif\n#ifdef SHADOW3\n#ifdef SHADOWVSM3\n shadow = computeShadowWithVSM(vPositionFromLight3, shadowSampler3, shadowsInfo3.z);\n#else\n #ifdef SHADOWPCF3\n shadow = computeShadowWithPCF(vPositionFromLight3, shadowSampler3, shadowsInfo3.y, shadowsInfo3.z);\n #else\n shadow = computeShadow(vPositionFromLight3, shadowSampler3, shadowsInfo3.x, shadowsInfo3.z);\n #endif \n#endif \n#else\n shadow = 1.;\n#endif\n diffuseBase += info.diffuse * shadow;\n specularBase += info.specular * shadow;\n#endif\n\n // Reflection\n vec3 reflectionColor = vec3(0., 0., 0.);\n\n#ifdef REFLECTION\n vec3 vReflectionUVW = computeReflectionCoords(vReflectionInfos.x, vec4(vPositionW, 1.0), normalW);\n\n if (vReflectionInfos.z != 0.0)\n {\n reflectionColor = textureCube(reflectionCubeSampler, vReflectionUVW).rgb * vReflectionInfos.y * shadow;\n }\n else\n {\n vec2 coords = vReflectionUVW.xy;\n\n if (vReflectionInfos.x == MAP_PROJECTION)\n {\n coords /= vReflectionUVW.z;\n }\n\n coords.y = 1.0 - coords.y;\n\n reflectionColor = texture2D(reflection2DSampler, coords).rgb * vReflectionInfos.y * shadow;\n }\n\n#ifdef REFLECTIONFRESNEL\n float reflectionFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, reflectionRightColor.a, reflectionLeftColor.a);\n\n reflectionColor *= reflectionLeftColor.rgb * (1.0 - reflectionFresnelTerm) + reflectionFresnelTerm * reflectionRightColor.rgb;\n#endif\n#endif\n\n#ifdef OPACITY\n vec4 opacityMap = texture2D(opacitySampler, vOpacityUV);\n\n#ifdef OPACITYRGB\n opacityMap.rgb = opacityMap.rgb * vec3(0.3, 0.59, 0.11);\n alpha *= (opacityMap.x + opacityMap.y + opacityMap.z)* vOpacityInfos.y;\n#else\n alpha *= opacityMap.a * vOpacityInfos.y;\n#endif\n\n#endif\n\n#ifdef VERTEXALPHA\n alpha *= vColor.a;\n#endif\n\n#ifdef OPACITYFRESNEL\n float opacityFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, opacityParts.z, opacityParts.w);\n\n alpha += opacityParts.x * (1.0 - opacityFresnelTerm) + opacityFresnelTerm * opacityParts.y;\n#endif\n\n // Emissive\n vec3 emissiveColor = vEmissiveColor;\n#ifdef EMISSIVE\n emissiveColor += texture2D(emissiveSampler, vEmissiveUV).rgb * vEmissiveInfos.y;\n#endif\n\n#ifdef EMISSIVEFRESNEL\n float emissiveFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, emissiveRightColor.a, emissiveLeftColor.a);\n\n emissiveColor *= emissiveLeftColor.rgb * (1.0 - emissiveFresnelTerm) + emissiveFresnelTerm * emissiveRightColor.rgb;\n#endif\n\n // Specular map\n vec3 specularColor = vSpecularColor.rgb;\n#ifdef SPECULAR\n specularColor = texture2D(specularSampler, vSpecularUV).rgb * vSpecularInfos.y;\n#endif\n\n // Fresnel\n#ifdef DIFFUSEFRESNEL\n float diffuseFresnelTerm = computeFresnelTerm(viewDirectionW, normalW, diffuseRightColor.a, diffuseLeftColor.a);\n\n diffuseBase *= diffuseLeftColor.rgb * (1.0 - diffuseFresnelTerm) + diffuseFresnelTerm * diffuseRightColor.rgb;\n#endif\n\n // Composition\n vec3 finalDiffuse = clamp(diffuseBase * diffuseColor + emissiveColor + vAmbientColor, 0.0, 1.0) * baseColor.rgb;\n vec3 finalSpecular = specularBase * specularColor;\n\n#ifdef SPECULAROVERALPHA\n alpha = clamp(alpha + dot(finalSpecular, vec3(0.3, 0.59, 0.11)), 0., 1.);\n#endif\n\n vec4 color = vec4(finalDiffuse * baseAmbientColor + finalSpecular + reflectionColor, alpha);\n\n#ifdef FOG\n float fog = CalcFogFactor();\n color.rgb = fog * color.rgb + (1.0 - fog) * vFogColor;\n#endif\n\n gl_FragColor = color;\n}",
  13844. 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}",
  13845. 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}",
  13846. 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(BASIC_RENDER)\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}",
  13847. 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}",
  13848. 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}",
  13849. 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}",
  13850. 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}",
  13851. 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}",
  13852. 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}",
  13853. 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}",
  13854. 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}",
  13855. 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}",
  13856. 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}",
  13857. 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}",
  13858. 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}",
  13859. 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}",
  13860. 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}",
  13861. 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}",
  13862. 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}",
  13863. 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}",
  13864. 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}",
  13865. 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}",
  13866. 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}",
  13867. 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}",
  13868. 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}",
  13869. 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}",
  13870. 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}",
  13871. 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}",
  13872. 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}",
  13873. 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}",
  13874. 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}",
  13875. 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}",
  13876. 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}",
  13877. 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}",
  13878. volumetricLightScatteringPassPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER) || defined(OPACITY)\nvarying vec2 vUV;\n#endif\n\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\nuniform sampler2D diffuseSampler;\n#endif\n\n#if defined(OPACITY)\nuniform sampler2D opacitySampler;\n#endif\n\nvoid main(void)\n{\n#if defined(ALPHATEST) || defined(OPACITY) || defined(BASIC_RENDER)\n vec4 diffuseColor = texture2D(diffuseSampler, vUV);\n#endif\n\n#ifdef ALPHATEST\n if (diffuseColor.a < 0.4)\n discard;\n#endif\n\n#ifdef BASIC_RENDER\n #ifdef OPACITY\n gl_FragColor = diffuseColor * texture2D(opacitySampler, vUV);\n #else\n gl_FragColor = diffuseColor;\n #endif\n#else\n gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\n\n}",
  13879. 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}",
  13880. };
  13881. return Effect;
  13882. })();
  13883. BABYLON.Effect = Effect;
  13884. })(BABYLON || (BABYLON = {}));
  13885. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13886. (function (BABYLON) {
  13887. var Material = (function () {
  13888. function Material(name, scene, doNotAdd) {
  13889. this.name = name;
  13890. this.checkReadyOnEveryCall = true;
  13891. this.checkReadyOnlyOnce = false;
  13892. this.state = "";
  13893. this.alpha = 1.0;
  13894. this.backFaceCulling = true;
  13895. this._wasPreviouslyReady = false;
  13896. this._fillMode = Material.TriangleFillMode;
  13897. this.pointSize = 1.0;
  13898. this.id = name;
  13899. this._scene = scene;
  13900. if (!doNotAdd) {
  13901. scene.materials.push(this);
  13902. }
  13903. }
  13904. Object.defineProperty(Material, "TriangleFillMode", {
  13905. get: function () {
  13906. return Material._TriangleFillMode;
  13907. },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. Object.defineProperty(Material, "WireFrameFillMode", {
  13912. get: function () {
  13913. return Material._WireFrameFillMode;
  13914. },
  13915. enumerable: true,
  13916. configurable: true
  13917. });
  13918. Object.defineProperty(Material, "PointFillMode", {
  13919. get: function () {
  13920. return Material._PointFillMode;
  13921. },
  13922. enumerable: true,
  13923. configurable: true
  13924. });
  13925. Object.defineProperty(Material.prototype, "wireframe", {
  13926. get: function () {
  13927. return this._fillMode === Material.WireFrameFillMode;
  13928. },
  13929. set: function (value) {
  13930. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13931. },
  13932. enumerable: true,
  13933. configurable: true
  13934. });
  13935. Object.defineProperty(Material.prototype, "pointsCloud", {
  13936. get: function () {
  13937. return this._fillMode === Material.PointFillMode;
  13938. },
  13939. set: function (value) {
  13940. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13941. },
  13942. enumerable: true,
  13943. configurable: true
  13944. });
  13945. Object.defineProperty(Material.prototype, "fillMode", {
  13946. get: function () {
  13947. return this._fillMode;
  13948. },
  13949. set: function (value) {
  13950. this._fillMode = value;
  13951. },
  13952. enumerable: true,
  13953. configurable: true
  13954. });
  13955. Material.prototype.isReady = function (mesh, useInstances) {
  13956. return true;
  13957. };
  13958. Material.prototype.getEffect = function () {
  13959. return this._effect;
  13960. };
  13961. Material.prototype.getScene = function () {
  13962. return this._scene;
  13963. };
  13964. Material.prototype.needAlphaBlending = function () {
  13965. return (this.alpha < 1.0);
  13966. };
  13967. Material.prototype.needAlphaTesting = function () {
  13968. return false;
  13969. };
  13970. Material.prototype.getAlphaTestTexture = function () {
  13971. return null;
  13972. };
  13973. Material.prototype.trackCreation = function (onCompiled, onError) {
  13974. };
  13975. Material.prototype._preBind = function () {
  13976. var engine = this._scene.getEngine();
  13977. engine.enableEffect(this._effect);
  13978. engine.setState(this.backFaceCulling);
  13979. };
  13980. Material.prototype.bind = function (world, mesh) {
  13981. this._scene._cachedMaterial = this;
  13982. if (this.onBind) {
  13983. this.onBind(this);
  13984. }
  13985. };
  13986. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13987. };
  13988. Material.prototype.unbind = function () {
  13989. };
  13990. Material.prototype.dispose = function (forceDisposeEffect) {
  13991. // Remove from scene
  13992. var index = this._scene.materials.indexOf(this);
  13993. this._scene.materials.splice(index, 1);
  13994. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13995. if (forceDisposeEffect && this._effect) {
  13996. this._scene.getEngine()._releaseEffect(this._effect);
  13997. this._effect = null;
  13998. }
  13999. // Callback
  14000. if (this.onDispose) {
  14001. this.onDispose();
  14002. }
  14003. };
  14004. Material._TriangleFillMode = 0;
  14005. Material._WireFrameFillMode = 1;
  14006. Material._PointFillMode = 2;
  14007. return Material;
  14008. })();
  14009. BABYLON.Material = Material;
  14010. })(BABYLON || (BABYLON = {}));
  14011. //# sourceMappingURL=babylon.material.js.map
  14012. var BABYLON;
  14013. (function (BABYLON) {
  14014. var maxSimultaneousLights = 4;
  14015. var FresnelParameters = (function () {
  14016. function FresnelParameters() {
  14017. this.isEnabled = true;
  14018. this.leftColor = BABYLON.Color3.White();
  14019. this.rightColor = BABYLON.Color3.Black();
  14020. this.bias = 0;
  14021. this.power = 1;
  14022. }
  14023. return FresnelParameters;
  14024. })();
  14025. BABYLON.FresnelParameters = FresnelParameters;
  14026. var StandardMaterial = (function (_super) {
  14027. __extends(StandardMaterial, _super);
  14028. function StandardMaterial(name, scene) {
  14029. var _this = this;
  14030. _super.call(this, name, scene);
  14031. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  14032. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  14033. this.specularColor = new BABYLON.Color3(1, 1, 1);
  14034. this.specularPower = 64;
  14035. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  14036. this.useAlphaFromDiffuseTexture = false;
  14037. this.useSpecularOverAlpha = true;
  14038. this.fogEnabled = true;
  14039. this._cachedDefines = null;
  14040. this._renderTargets = new BABYLON.SmartArray(16);
  14041. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  14042. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  14043. this._scaledDiffuse = new BABYLON.Color3();
  14044. this._scaledSpecular = new BABYLON.Color3();
  14045. this.getRenderTargetTextures = function () {
  14046. _this._renderTargets.reset();
  14047. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  14048. _this._renderTargets.push(_this.reflectionTexture);
  14049. }
  14050. return _this._renderTargets;
  14051. };
  14052. }
  14053. StandardMaterial.prototype.needAlphaBlending = function () {
  14054. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  14055. };
  14056. StandardMaterial.prototype.needAlphaTesting = function () {
  14057. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  14058. };
  14059. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  14060. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  14061. };
  14062. StandardMaterial.prototype.getAlphaTestTexture = function () {
  14063. return this.diffuseTexture;
  14064. };
  14065. // Methods
  14066. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  14067. if (this.checkReadyOnlyOnce) {
  14068. if (this._wasPreviouslyReady) {
  14069. return true;
  14070. }
  14071. }
  14072. var scene = this.getScene();
  14073. if (!this.checkReadyOnEveryCall) {
  14074. if (this._renderId === scene.getRenderId()) {
  14075. return true;
  14076. }
  14077. }
  14078. var engine = scene.getEngine();
  14079. var defines = [];
  14080. var fallbacks = new BABYLON.EffectFallbacks();
  14081. var needNormals = false;
  14082. var needUVs = false;
  14083. // Textures
  14084. if (scene.texturesEnabled) {
  14085. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14086. if (!this.diffuseTexture.isReady()) {
  14087. return false;
  14088. }
  14089. else {
  14090. needUVs = true;
  14091. defines.push("#define DIFFUSE");
  14092. }
  14093. }
  14094. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14095. if (!this.ambientTexture.isReady()) {
  14096. return false;
  14097. }
  14098. else {
  14099. needUVs = true;
  14100. defines.push("#define AMBIENT");
  14101. }
  14102. }
  14103. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14104. if (!this.opacityTexture.isReady()) {
  14105. return false;
  14106. }
  14107. else {
  14108. needUVs = true;
  14109. defines.push("#define OPACITY");
  14110. if (this.opacityTexture.getAlphaFromRGB) {
  14111. defines.push("#define OPACITYRGB");
  14112. }
  14113. }
  14114. }
  14115. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14116. if (!this.reflectionTexture.isReady()) {
  14117. return false;
  14118. }
  14119. else {
  14120. needNormals = true;
  14121. needUVs = true;
  14122. defines.push("#define REFLECTION");
  14123. fallbacks.addFallback(0, "REFLECTION");
  14124. }
  14125. }
  14126. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14127. if (!this.emissiveTexture.isReady()) {
  14128. return false;
  14129. }
  14130. else {
  14131. needUVs = true;
  14132. defines.push("#define EMISSIVE");
  14133. }
  14134. }
  14135. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14136. if (!this.specularTexture.isReady()) {
  14137. return false;
  14138. }
  14139. else {
  14140. needUVs = true;
  14141. defines.push("#define SPECULAR");
  14142. fallbacks.addFallback(0, "SPECULAR");
  14143. }
  14144. }
  14145. }
  14146. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  14147. if (!this.bumpTexture.isReady()) {
  14148. return false;
  14149. }
  14150. else {
  14151. needUVs = true;
  14152. defines.push("#define BUMP");
  14153. fallbacks.addFallback(0, "BUMP");
  14154. }
  14155. }
  14156. // Effect
  14157. if (this.useSpecularOverAlpha) {
  14158. defines.push("#define SPECULAROVERALPHA");
  14159. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  14160. }
  14161. if (scene.clipPlane) {
  14162. defines.push("#define CLIPPLANE");
  14163. }
  14164. if (engine.getAlphaTesting()) {
  14165. defines.push("#define ALPHATEST");
  14166. }
  14167. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14168. defines.push("#define ALPHAFROMDIFFUSE");
  14169. }
  14170. // Point size
  14171. if (this.pointsCloud || scene.forcePointsCloud) {
  14172. defines.push("#define POINTSIZE");
  14173. }
  14174. // Fog
  14175. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14176. defines.push("#define FOG");
  14177. fallbacks.addFallback(1, "FOG");
  14178. }
  14179. var shadowsActivated = false;
  14180. var lightIndex = 0;
  14181. if (scene.lightsEnabled) {
  14182. for (var index = 0; index < scene.lights.length; index++) {
  14183. var light = scene.lights[index];
  14184. if (!light.isEnabled()) {
  14185. continue;
  14186. }
  14187. // Excluded check
  14188. if (light._excludedMeshesIds.length > 0) {
  14189. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14190. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14191. if (excludedMesh) {
  14192. light.excludedMeshes.push(excludedMesh);
  14193. }
  14194. }
  14195. light._excludedMeshesIds = [];
  14196. }
  14197. // Included check
  14198. if (light._includedOnlyMeshesIds.length > 0) {
  14199. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14200. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14201. if (includedOnlyMesh) {
  14202. light.includedOnlyMeshes.push(includedOnlyMesh);
  14203. }
  14204. }
  14205. light._includedOnlyMeshesIds = [];
  14206. }
  14207. if (!light.canAffectMesh(mesh)) {
  14208. continue;
  14209. }
  14210. needNormals = true;
  14211. defines.push("#define LIGHT" + lightIndex);
  14212. if (lightIndex > 0) {
  14213. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14214. }
  14215. var type;
  14216. if (light instanceof BABYLON.SpotLight) {
  14217. type = "#define SPOTLIGHT" + lightIndex;
  14218. }
  14219. else if (light instanceof BABYLON.HemisphericLight) {
  14220. type = "#define HEMILIGHT" + lightIndex;
  14221. }
  14222. else {
  14223. type = "#define POINTDIRLIGHT" + lightIndex;
  14224. }
  14225. defines.push(type);
  14226. if (lightIndex > 0) {
  14227. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14228. }
  14229. // Shadows
  14230. if (scene.shadowsEnabled) {
  14231. var shadowGenerator = light.getShadowGenerator();
  14232. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14233. defines.push("#define SHADOW" + lightIndex);
  14234. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14235. if (!shadowsActivated) {
  14236. defines.push("#define SHADOWS");
  14237. shadowsActivated = true;
  14238. }
  14239. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  14240. defines.push("#define SHADOWVSM" + lightIndex);
  14241. if (lightIndex > 0) {
  14242. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14243. }
  14244. }
  14245. if (shadowGenerator.usePoissonSampling) {
  14246. defines.push("#define SHADOWPCF" + lightIndex);
  14247. if (lightIndex > 0) {
  14248. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14249. }
  14250. }
  14251. }
  14252. }
  14253. lightIndex++;
  14254. if (lightIndex === maxSimultaneousLights)
  14255. break;
  14256. }
  14257. }
  14258. if (StandardMaterial.FresnelEnabled) {
  14259. // Fresnel
  14260. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14261. var fresnelRank = 1;
  14262. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14263. defines.push("#define DIFFUSEFRESNEL");
  14264. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14265. fresnelRank++;
  14266. }
  14267. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14268. defines.push("#define OPACITYFRESNEL");
  14269. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14270. fresnelRank++;
  14271. }
  14272. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14273. defines.push("#define REFLECTIONFRESNEL");
  14274. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14275. fresnelRank++;
  14276. }
  14277. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14278. defines.push("#define EMISSIVEFRESNEL");
  14279. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14280. fresnelRank++;
  14281. }
  14282. needNormals = true;
  14283. defines.push("#define FRESNEL");
  14284. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14285. }
  14286. }
  14287. // Attribs
  14288. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14289. if (mesh) {
  14290. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14291. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14292. defines.push("#define NORMAL");
  14293. }
  14294. if (needUVs) {
  14295. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14296. attribs.push(BABYLON.VertexBuffer.UVKind);
  14297. defines.push("#define UV1");
  14298. }
  14299. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14300. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14301. defines.push("#define UV2");
  14302. }
  14303. }
  14304. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14305. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14306. defines.push("#define VERTEXCOLOR");
  14307. if (mesh.hasVertexAlpha) {
  14308. defines.push("#define VERTEXALPHA");
  14309. }
  14310. }
  14311. if (mesh.useBones) {
  14312. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14313. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14314. defines.push("#define BONES");
  14315. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14316. defines.push("#define BONES4");
  14317. fallbacks.addFallback(0, "BONES4");
  14318. }
  14319. // Instances
  14320. if (useInstances) {
  14321. defines.push("#define INSTANCES");
  14322. attribs.push("world0");
  14323. attribs.push("world1");
  14324. attribs.push("world2");
  14325. attribs.push("world3");
  14326. }
  14327. }
  14328. // Get correct effect
  14329. var join = defines.join("\n");
  14330. if (this._cachedDefines !== join) {
  14331. this._cachedDefines = join;
  14332. scene.resetCachedMaterial();
  14333. // Legacy browser patch
  14334. var shaderName = "default";
  14335. if (!scene.getEngine().getCaps().standardDerivatives) {
  14336. shaderName = "legacydefault";
  14337. }
  14338. 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);
  14339. }
  14340. if (!this._effect.isReady()) {
  14341. return false;
  14342. }
  14343. this._renderId = scene.getRenderId();
  14344. this._wasPreviouslyReady = true;
  14345. return true;
  14346. };
  14347. StandardMaterial.prototype.unbind = function () {
  14348. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14349. this._effect.setTexture("reflection2DSampler", null);
  14350. }
  14351. };
  14352. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14353. this._effect.setMatrix("world", world);
  14354. };
  14355. StandardMaterial.prototype.bind = function (world, mesh) {
  14356. var scene = this.getScene();
  14357. // Matrices
  14358. this.bindOnlyWorldMatrix(world);
  14359. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14360. // Bones
  14361. if (mesh.useBones) {
  14362. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14363. }
  14364. if (scene.getCachedMaterial() !== this) {
  14365. if (StandardMaterial.FresnelEnabled) {
  14366. // Fresnel
  14367. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14368. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14369. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14370. }
  14371. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14372. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14373. }
  14374. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14375. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14376. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14377. }
  14378. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14379. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14380. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14381. }
  14382. }
  14383. // Textures
  14384. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14385. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14386. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14387. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14388. }
  14389. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14390. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14391. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14392. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14393. }
  14394. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14395. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14396. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14397. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14398. }
  14399. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14400. if (this.reflectionTexture.isCube) {
  14401. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14402. }
  14403. else {
  14404. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14405. }
  14406. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14407. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14408. }
  14409. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14410. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14411. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14412. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14413. }
  14414. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14415. this._effect.setTexture("specularSampler", this.specularTexture);
  14416. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14417. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14418. }
  14419. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14420. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14421. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14422. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14423. }
  14424. // Clip plane
  14425. if (scene.clipPlane) {
  14426. var clipPlane = scene.clipPlane;
  14427. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14428. }
  14429. // Point size
  14430. if (this.pointsCloud) {
  14431. this._effect.setFloat("pointSize", this.pointSize);
  14432. }
  14433. // Colors
  14434. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14435. // Scaling down color according to emissive
  14436. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14437. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14438. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14439. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14440. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14441. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14442. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14443. }
  14444. // Scaling down color according to emissive
  14445. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14446. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14447. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14448. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14449. if (scene.lightsEnabled) {
  14450. var lightIndex = 0;
  14451. for (var index = 0; index < scene.lights.length; index++) {
  14452. var light = scene.lights[index];
  14453. if (!light.isEnabled()) {
  14454. continue;
  14455. }
  14456. if (!light.canAffectMesh(mesh)) {
  14457. continue;
  14458. }
  14459. if (light instanceof BABYLON.PointLight) {
  14460. // Point Light
  14461. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14462. }
  14463. else if (light instanceof BABYLON.DirectionalLight) {
  14464. // Directional Light
  14465. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14466. }
  14467. else if (light instanceof BABYLON.SpotLight) {
  14468. // Spot Light
  14469. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14470. }
  14471. else if (light instanceof BABYLON.HemisphericLight) {
  14472. // Hemispheric Light
  14473. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14474. }
  14475. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14476. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14477. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14478. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14479. // Shadows
  14480. if (scene.shadowsEnabled) {
  14481. var shadowGenerator = light.getShadowGenerator();
  14482. if (mesh.receiveShadows && shadowGenerator) {
  14483. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14484. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  14485. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  14486. }
  14487. }
  14488. lightIndex++;
  14489. if (lightIndex === maxSimultaneousLights)
  14490. break;
  14491. }
  14492. }
  14493. // View
  14494. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14495. this._effect.setMatrix("view", scene.getViewMatrix());
  14496. }
  14497. // Fog
  14498. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14499. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14500. this._effect.setColor3("vFogColor", scene.fogColor);
  14501. }
  14502. _super.prototype.bind.call(this, world, mesh);
  14503. };
  14504. StandardMaterial.prototype.getAnimatables = function () {
  14505. var results = [];
  14506. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14507. results.push(this.diffuseTexture);
  14508. }
  14509. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14510. results.push(this.ambientTexture);
  14511. }
  14512. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14513. results.push(this.opacityTexture);
  14514. }
  14515. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14516. results.push(this.reflectionTexture);
  14517. }
  14518. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14519. results.push(this.emissiveTexture);
  14520. }
  14521. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14522. results.push(this.specularTexture);
  14523. }
  14524. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14525. results.push(this.bumpTexture);
  14526. }
  14527. return results;
  14528. };
  14529. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14530. if (this.diffuseTexture) {
  14531. this.diffuseTexture.dispose();
  14532. }
  14533. if (this.ambientTexture) {
  14534. this.ambientTexture.dispose();
  14535. }
  14536. if (this.opacityTexture) {
  14537. this.opacityTexture.dispose();
  14538. }
  14539. if (this.reflectionTexture) {
  14540. this.reflectionTexture.dispose();
  14541. }
  14542. if (this.emissiveTexture) {
  14543. this.emissiveTexture.dispose();
  14544. }
  14545. if (this.specularTexture) {
  14546. this.specularTexture.dispose();
  14547. }
  14548. if (this.bumpTexture) {
  14549. this.bumpTexture.dispose();
  14550. }
  14551. _super.prototype.dispose.call(this, forceDisposeEffect);
  14552. };
  14553. StandardMaterial.prototype.clone = function (name) {
  14554. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14555. // Base material
  14556. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14557. newStandardMaterial.alpha = this.alpha;
  14558. newStandardMaterial.fillMode = this.fillMode;
  14559. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14560. // Standard material
  14561. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14562. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14563. }
  14564. if (this.ambientTexture && this.ambientTexture.clone) {
  14565. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14566. }
  14567. if (this.opacityTexture && this.opacityTexture.clone) {
  14568. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14569. }
  14570. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14571. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14572. }
  14573. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14574. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14575. }
  14576. if (this.specularTexture && this.specularTexture.clone) {
  14577. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14578. }
  14579. if (this.bumpTexture && this.bumpTexture.clone) {
  14580. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14581. }
  14582. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14583. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14584. newStandardMaterial.specularColor = this.specularColor.clone();
  14585. newStandardMaterial.specularPower = this.specularPower;
  14586. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14587. return newStandardMaterial;
  14588. };
  14589. // Statics
  14590. // Flags used to enable or disable a type of texture for all Standard Materials
  14591. StandardMaterial.DiffuseTextureEnabled = true;
  14592. StandardMaterial.AmbientTextureEnabled = true;
  14593. StandardMaterial.OpacityTextureEnabled = true;
  14594. StandardMaterial.ReflectionTextureEnabled = true;
  14595. StandardMaterial.EmissiveTextureEnabled = true;
  14596. StandardMaterial.SpecularTextureEnabled = true;
  14597. StandardMaterial.BumpTextureEnabled = true;
  14598. StandardMaterial.FresnelEnabled = true;
  14599. return StandardMaterial;
  14600. })(BABYLON.Material);
  14601. BABYLON.StandardMaterial = StandardMaterial;
  14602. })(BABYLON || (BABYLON = {}));
  14603. //# sourceMappingURL=babylon.standardMaterial.js.map
  14604. var BABYLON;
  14605. (function (BABYLON) {
  14606. var MultiMaterial = (function (_super) {
  14607. __extends(MultiMaterial, _super);
  14608. function MultiMaterial(name, scene) {
  14609. _super.call(this, name, scene, true);
  14610. this.subMaterials = new Array();
  14611. scene.multiMaterials.push(this);
  14612. }
  14613. // Properties
  14614. MultiMaterial.prototype.getSubMaterial = function (index) {
  14615. if (index < 0 || index >= this.subMaterials.length) {
  14616. return this.getScene().defaultMaterial;
  14617. }
  14618. return this.subMaterials[index];
  14619. };
  14620. // Methods
  14621. MultiMaterial.prototype.isReady = function (mesh) {
  14622. for (var index = 0; index < this.subMaterials.length; index++) {
  14623. var subMaterial = this.subMaterials[index];
  14624. if (subMaterial) {
  14625. if (!this.subMaterials[index].isReady(mesh)) {
  14626. return false;
  14627. }
  14628. }
  14629. }
  14630. return true;
  14631. };
  14632. return MultiMaterial;
  14633. })(BABYLON.Material);
  14634. BABYLON.MultiMaterial = MultiMaterial;
  14635. })(BABYLON || (BABYLON = {}));
  14636. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14637. (function (BABYLON) {
  14638. var Database = (function () {
  14639. function Database(urlToScene, callbackManifestChecked) {
  14640. // Handling various flavors of prefixed version of IndexedDB
  14641. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14642. this.callbackManifestChecked = callbackManifestChecked;
  14643. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14644. this.db = null;
  14645. this.enableSceneOffline = false;
  14646. this.enableTexturesOffline = false;
  14647. this.manifestVersionFound = 0;
  14648. this.mustUpdateRessources = false;
  14649. this.hasReachedQuota = false;
  14650. this.checkManifestFile();
  14651. }
  14652. Database.prototype.checkManifestFile = function () {
  14653. var _this = this;
  14654. function noManifestFile() {
  14655. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14656. that.enableSceneOffline = false;
  14657. that.enableTexturesOffline = false;
  14658. that.callbackManifestChecked(false);
  14659. }
  14660. var that = this;
  14661. var manifestURL = this.currentSceneUrl + ".manifest";
  14662. var xhr = new XMLHttpRequest();
  14663. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14664. xhr.open("GET", manifestURLTimeStamped, true);
  14665. xhr.addEventListener("load", function () {
  14666. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14667. try {
  14668. var manifestFile = JSON.parse(xhr.response);
  14669. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14670. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14671. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14672. _this.manifestVersionFound = manifestFile.version;
  14673. }
  14674. if (_this.callbackManifestChecked) {
  14675. _this.callbackManifestChecked(true);
  14676. }
  14677. }
  14678. catch (ex) {
  14679. noManifestFile();
  14680. }
  14681. }
  14682. else {
  14683. noManifestFile();
  14684. }
  14685. }, false);
  14686. xhr.addEventListener("error", function (event) {
  14687. noManifestFile();
  14688. }, false);
  14689. try {
  14690. xhr.send();
  14691. }
  14692. catch (ex) {
  14693. BABYLON.Tools.Error("Error on XHR send request.");
  14694. that.callbackManifestChecked(false);
  14695. }
  14696. };
  14697. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14698. var _this = this;
  14699. function handleError() {
  14700. that.isSupported = false;
  14701. if (errorCallback)
  14702. errorCallback();
  14703. }
  14704. var that = this;
  14705. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14706. // Your browser doesn't support IndexedDB
  14707. this.isSupported = false;
  14708. if (errorCallback)
  14709. errorCallback();
  14710. }
  14711. else {
  14712. // If the DB hasn't been opened or created yet
  14713. if (!this.db) {
  14714. this.hasReachedQuota = false;
  14715. this.isSupported = true;
  14716. var request = this.idbFactory.open("babylonjs", 1);
  14717. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14718. request.onerror = function (event) {
  14719. handleError();
  14720. };
  14721. // executes when a version change transaction cannot complete due to other active transactions
  14722. request.onblocked = function (event) {
  14723. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14724. handleError();
  14725. };
  14726. // DB has been opened successfully
  14727. request.onsuccess = function (event) {
  14728. _this.db = request.result;
  14729. successCallback();
  14730. };
  14731. // Initialization of the DB. Creating Scenes & Textures stores
  14732. request.onupgradeneeded = function (event) {
  14733. _this.db = (event.target).result;
  14734. try {
  14735. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14736. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14737. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14738. }
  14739. catch (ex) {
  14740. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14741. handleError();
  14742. }
  14743. };
  14744. }
  14745. else {
  14746. if (successCallback)
  14747. successCallback();
  14748. }
  14749. }
  14750. };
  14751. Database.prototype.loadImageFromDB = function (url, image) {
  14752. var _this = this;
  14753. var completeURL = Database.ReturnFullUrlLocation(url);
  14754. var saveAndLoadImage = function () {
  14755. if (!_this.hasReachedQuota && _this.db !== null) {
  14756. // the texture is not yet in the DB, let's try to save it
  14757. _this._saveImageIntoDBAsync(completeURL, image);
  14758. }
  14759. else {
  14760. image.src = url;
  14761. }
  14762. };
  14763. if (!this.mustUpdateRessources) {
  14764. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14765. }
  14766. else {
  14767. saveAndLoadImage();
  14768. }
  14769. };
  14770. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14771. if (this.isSupported && this.db !== null) {
  14772. var texture;
  14773. var transaction = this.db.transaction(["textures"]);
  14774. transaction.onabort = function (event) {
  14775. image.src = url;
  14776. };
  14777. transaction.oncomplete = function (event) {
  14778. var blobTextureURL;
  14779. if (texture) {
  14780. var URL = window.URL || window.webkitURL;
  14781. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14782. image.onerror = function () {
  14783. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14784. image.src = url;
  14785. };
  14786. image.src = blobTextureURL;
  14787. }
  14788. else {
  14789. notInDBCallback();
  14790. }
  14791. };
  14792. var getRequest = transaction.objectStore("textures").get(url);
  14793. getRequest.onsuccess = function (event) {
  14794. texture = (event.target).result;
  14795. };
  14796. getRequest.onerror = function (event) {
  14797. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14798. image.src = url;
  14799. };
  14800. }
  14801. else {
  14802. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14803. image.src = url;
  14804. }
  14805. };
  14806. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14807. var _this = this;
  14808. if (this.isSupported) {
  14809. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14810. var generateBlobUrl = function () {
  14811. var blobTextureURL;
  14812. if (blob) {
  14813. var URL = window.URL || window.webkitURL;
  14814. try {
  14815. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14816. }
  14817. catch (ex) {
  14818. blobTextureURL = URL.createObjectURL(blob);
  14819. }
  14820. }
  14821. image.src = blobTextureURL;
  14822. };
  14823. if (Database.isUASupportingBlobStorage) {
  14824. var xhr = new XMLHttpRequest(), blob;
  14825. xhr.open("GET", url, true);
  14826. xhr.responseType = "blob";
  14827. xhr.addEventListener("load", function () {
  14828. if (xhr.status === 200) {
  14829. // Blob as response (XHR2)
  14830. blob = xhr.response;
  14831. var transaction = _this.db.transaction(["textures"], "readwrite");
  14832. // the transaction could abort because of a QuotaExceededError error
  14833. transaction.onabort = function (event) {
  14834. try {
  14835. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14836. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14837. this.hasReachedQuota = true;
  14838. }
  14839. }
  14840. catch (ex) {
  14841. }
  14842. generateBlobUrl();
  14843. };
  14844. transaction.oncomplete = function (event) {
  14845. generateBlobUrl();
  14846. };
  14847. var newTexture = { textureUrl: url, data: blob };
  14848. try {
  14849. // Put the blob into the dabase
  14850. var addRequest = transaction.objectStore("textures").put(newTexture);
  14851. addRequest.onsuccess = function (event) {
  14852. };
  14853. addRequest.onerror = function (event) {
  14854. generateBlobUrl();
  14855. };
  14856. }
  14857. catch (ex) {
  14858. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14859. if (ex.code === 25) {
  14860. Database.isUASupportingBlobStorage = false;
  14861. }
  14862. image.src = url;
  14863. }
  14864. }
  14865. else {
  14866. image.src = url;
  14867. }
  14868. }, false);
  14869. xhr.addEventListener("error", function (event) {
  14870. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14871. image.src = url;
  14872. }, false);
  14873. xhr.send();
  14874. }
  14875. else {
  14876. image.src = url;
  14877. }
  14878. }
  14879. else {
  14880. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14881. image.src = url;
  14882. }
  14883. };
  14884. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14885. var _this = this;
  14886. var updateVersion = function (event) {
  14887. // the version is not yet in the DB or we need to update it
  14888. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14889. };
  14890. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14891. };
  14892. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14893. var _this = this;
  14894. if (this.isSupported) {
  14895. var version;
  14896. try {
  14897. var transaction = this.db.transaction(["versions"]);
  14898. transaction.oncomplete = function (event) {
  14899. if (version) {
  14900. // If the version in the JSON file is > than the version in DB
  14901. if (_this.manifestVersionFound > version.data) {
  14902. _this.mustUpdateRessources = true;
  14903. updateInDBCallback();
  14904. }
  14905. else {
  14906. callback(version.data);
  14907. }
  14908. }
  14909. else {
  14910. _this.mustUpdateRessources = true;
  14911. updateInDBCallback();
  14912. }
  14913. };
  14914. transaction.onabort = function (event) {
  14915. callback(-1);
  14916. };
  14917. var getRequest = transaction.objectStore("versions").get(url);
  14918. getRequest.onsuccess = function (event) {
  14919. version = (event.target).result;
  14920. };
  14921. getRequest.onerror = function (event) {
  14922. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14923. callback(-1);
  14924. };
  14925. }
  14926. catch (ex) {
  14927. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14928. callback(-1);
  14929. }
  14930. }
  14931. else {
  14932. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14933. callback(-1);
  14934. }
  14935. };
  14936. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14937. var _this = this;
  14938. if (this.isSupported && !this.hasReachedQuota) {
  14939. try {
  14940. // Open a transaction to the database
  14941. var transaction = this.db.transaction(["versions"], "readwrite");
  14942. // the transaction could abort because of a QuotaExceededError error
  14943. transaction.onabort = function (event) {
  14944. try {
  14945. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14946. _this.hasReachedQuota = true;
  14947. }
  14948. }
  14949. catch (ex) {
  14950. }
  14951. callback(-1);
  14952. };
  14953. transaction.oncomplete = function (event) {
  14954. callback(_this.manifestVersionFound);
  14955. };
  14956. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14957. // Put the scene into the database
  14958. var addRequest = transaction.objectStore("versions").put(newVersion);
  14959. addRequest.onsuccess = function (event) {
  14960. };
  14961. addRequest.onerror = function (event) {
  14962. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14963. };
  14964. }
  14965. catch (ex) {
  14966. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14967. callback(-1);
  14968. }
  14969. }
  14970. else {
  14971. callback(-1);
  14972. }
  14973. };
  14974. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14975. var _this = this;
  14976. var completeUrl = Database.ReturnFullUrlLocation(url);
  14977. var saveAndLoadFile = function (event) {
  14978. // the scene is not yet in the DB, let's try to save it
  14979. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14980. };
  14981. this._checkVersionFromDB(completeUrl, function (version) {
  14982. if (version !== -1) {
  14983. if (!_this.mustUpdateRessources) {
  14984. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14985. }
  14986. else {
  14987. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14988. }
  14989. }
  14990. else {
  14991. errorCallback();
  14992. }
  14993. });
  14994. };
  14995. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14996. if (this.isSupported) {
  14997. var targetStore;
  14998. if (url.indexOf(".babylon") !== -1) {
  14999. targetStore = "scenes";
  15000. }
  15001. else {
  15002. targetStore = "textures";
  15003. }
  15004. var file;
  15005. var transaction = this.db.transaction([targetStore]);
  15006. transaction.oncomplete = function (event) {
  15007. if (file) {
  15008. callback(file.data);
  15009. }
  15010. else {
  15011. notInDBCallback();
  15012. }
  15013. };
  15014. transaction.onabort = function (event) {
  15015. notInDBCallback();
  15016. };
  15017. var getRequest = transaction.objectStore(targetStore).get(url);
  15018. getRequest.onsuccess = function (event) {
  15019. file = (event.target).result;
  15020. };
  15021. getRequest.onerror = function (event) {
  15022. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  15023. notInDBCallback();
  15024. };
  15025. }
  15026. else {
  15027. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15028. callback();
  15029. }
  15030. };
  15031. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  15032. var _this = this;
  15033. if (this.isSupported) {
  15034. var targetStore;
  15035. if (url.indexOf(".babylon") !== -1) {
  15036. targetStore = "scenes";
  15037. }
  15038. else {
  15039. targetStore = "textures";
  15040. }
  15041. // Create XHR
  15042. var xhr = new XMLHttpRequest(), fileData;
  15043. xhr.open("GET", url, true);
  15044. if (useArrayBuffer) {
  15045. xhr.responseType = "arraybuffer";
  15046. }
  15047. xhr.onprogress = progressCallback;
  15048. xhr.addEventListener("load", function () {
  15049. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  15050. // Blob as response (XHR2)
  15051. //fileData = xhr.responseText;
  15052. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  15053. if (!_this.hasReachedQuota) {
  15054. // Open a transaction to the database
  15055. var transaction = _this.db.transaction([targetStore], "readwrite");
  15056. // the transaction could abort because of a QuotaExceededError error
  15057. transaction.onabort = function (event) {
  15058. try {
  15059. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  15060. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  15061. this.hasReachedQuota = true;
  15062. }
  15063. }
  15064. catch (ex) {
  15065. }
  15066. callback(fileData);
  15067. };
  15068. transaction.oncomplete = function (event) {
  15069. callback(fileData);
  15070. };
  15071. var newFile;
  15072. if (targetStore === "scenes") {
  15073. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  15074. }
  15075. else {
  15076. newFile = { textureUrl: url, data: fileData };
  15077. }
  15078. try {
  15079. // Put the scene into the database
  15080. var addRequest = transaction.objectStore(targetStore).put(newFile);
  15081. addRequest.onsuccess = function (event) {
  15082. };
  15083. addRequest.onerror = function (event) {
  15084. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  15085. };
  15086. }
  15087. catch (ex) {
  15088. callback(fileData);
  15089. }
  15090. }
  15091. else {
  15092. callback(fileData);
  15093. }
  15094. }
  15095. else {
  15096. callback();
  15097. }
  15098. }, false);
  15099. xhr.addEventListener("error", function (event) {
  15100. BABYLON.Tools.Error("error on XHR request.");
  15101. callback();
  15102. }, false);
  15103. xhr.send();
  15104. }
  15105. else {
  15106. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  15107. callback();
  15108. }
  15109. };
  15110. Database.isUASupportingBlobStorage = true;
  15111. Database.parseURL = function (url) {
  15112. var a = document.createElement('a');
  15113. a.href = url;
  15114. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  15115. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  15116. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  15117. return absLocation;
  15118. };
  15119. Database.ReturnFullUrlLocation = function (url) {
  15120. if (url.indexOf("http:/") === -1) {
  15121. return (BABYLON.Database.parseURL(window.location.href) + url);
  15122. }
  15123. else {
  15124. return url;
  15125. }
  15126. };
  15127. return Database;
  15128. })();
  15129. BABYLON.Database = Database;
  15130. })(BABYLON || (BABYLON = {}));
  15131. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  15132. (function (BABYLON) {
  15133. var SpriteManager = (function () {
  15134. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  15135. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15136. this.name = name;
  15137. this.cellSize = cellSize;
  15138. this.sprites = new Array();
  15139. this.renderingGroupId = 0;
  15140. this.fogEnabled = true;
  15141. this._vertexDeclaration = [3, 4, 4, 4];
  15142. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  15143. this._capacity = capacity;
  15144. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  15145. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15146. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  15147. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  15148. this._scene = scene;
  15149. this._scene.spriteManagers.push(this);
  15150. // VBO
  15151. this._vertexDeclaration = [3, 4, 4, 4];
  15152. this._vertexStrideSize = 15 * 4;
  15153. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15154. var indices = [];
  15155. var index = 0;
  15156. for (var count = 0; count < capacity; count++) {
  15157. indices.push(index);
  15158. indices.push(index + 1);
  15159. indices.push(index + 2);
  15160. indices.push(index);
  15161. indices.push(index + 2);
  15162. indices.push(index + 3);
  15163. index += 4;
  15164. }
  15165. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15166. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15167. // Effects
  15168. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15169. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15170. }
  15171. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15172. var arrayOffset = index * 15;
  15173. if (offsetX === 0)
  15174. offsetX = this._epsilon;
  15175. else if (offsetX === 1)
  15176. offsetX = 1 - this._epsilon;
  15177. if (offsetY === 0)
  15178. offsetY = this._epsilon;
  15179. else if (offsetY === 1)
  15180. offsetY = 1 - this._epsilon;
  15181. this._vertices[arrayOffset] = sprite.position.x;
  15182. this._vertices[arrayOffset + 1] = sprite.position.y;
  15183. this._vertices[arrayOffset + 2] = sprite.position.z;
  15184. this._vertices[arrayOffset + 3] = sprite.angle;
  15185. this._vertices[arrayOffset + 4] = sprite.size;
  15186. this._vertices[arrayOffset + 5] = offsetX;
  15187. this._vertices[arrayOffset + 6] = offsetY;
  15188. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15189. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15190. var offset = (sprite.cellIndex / rowSize) >> 0;
  15191. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15192. this._vertices[arrayOffset + 10] = offset;
  15193. // Color
  15194. this._vertices[arrayOffset + 11] = sprite.color.r;
  15195. this._vertices[arrayOffset + 12] = sprite.color.g;
  15196. this._vertices[arrayOffset + 13] = sprite.color.b;
  15197. this._vertices[arrayOffset + 14] = sprite.color.a;
  15198. };
  15199. SpriteManager.prototype.render = function () {
  15200. // Check
  15201. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15202. return;
  15203. var engine = this._scene.getEngine();
  15204. var baseSize = this._spriteTexture.getBaseSize();
  15205. // Sprites
  15206. var deltaTime = engine.getDeltaTime();
  15207. var max = Math.min(this._capacity, this.sprites.length);
  15208. var rowSize = baseSize.width / this.cellSize;
  15209. var offset = 0;
  15210. for (var index = 0; index < max; index++) {
  15211. var sprite = this.sprites[index];
  15212. if (!sprite) {
  15213. continue;
  15214. }
  15215. sprite._animate(deltaTime);
  15216. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15217. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15218. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15219. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15220. }
  15221. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15222. // Render
  15223. var effect = this._effectBase;
  15224. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15225. effect = this._effectFog;
  15226. }
  15227. engine.enableEffect(effect);
  15228. var viewMatrix = this._scene.getViewMatrix();
  15229. effect.setTexture("diffuseSampler", this._spriteTexture);
  15230. effect.setMatrix("view", viewMatrix);
  15231. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15232. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15233. // Fog
  15234. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15235. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15236. effect.setColor3("vFogColor", this._scene.fogColor);
  15237. }
  15238. // VBOs
  15239. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15240. // Draw order
  15241. effect.setBool("alphaTest", true);
  15242. engine.setColorWrite(false);
  15243. engine.draw(true, 0, max * 6);
  15244. engine.setColorWrite(true);
  15245. effect.setBool("alphaTest", false);
  15246. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15247. engine.draw(true, 0, max * 6);
  15248. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15249. };
  15250. SpriteManager.prototype.dispose = function () {
  15251. if (this._vertexBuffer) {
  15252. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15253. this._vertexBuffer = null;
  15254. }
  15255. if (this._indexBuffer) {
  15256. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15257. this._indexBuffer = null;
  15258. }
  15259. if (this._spriteTexture) {
  15260. this._spriteTexture.dispose();
  15261. this._spriteTexture = null;
  15262. }
  15263. // Remove from scene
  15264. var index = this._scene.spriteManagers.indexOf(this);
  15265. this._scene.spriteManagers.splice(index, 1);
  15266. // Callback
  15267. if (this.onDispose) {
  15268. this.onDispose();
  15269. }
  15270. };
  15271. return SpriteManager;
  15272. })();
  15273. BABYLON.SpriteManager = SpriteManager;
  15274. })(BABYLON || (BABYLON = {}));
  15275. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15276. (function (BABYLON) {
  15277. var Sprite = (function () {
  15278. function Sprite(name, manager) {
  15279. this.name = name;
  15280. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15281. this.size = 1.0;
  15282. this.angle = 0;
  15283. this.cellIndex = 0;
  15284. this.invertU = 0;
  15285. this.invertV = 0;
  15286. this.animations = new Array();
  15287. this._animationStarted = false;
  15288. this._loopAnimation = false;
  15289. this._fromIndex = 0;
  15290. this._toIndex = 0;
  15291. this._delay = 0;
  15292. this._direction = 1;
  15293. this._frameCount = 0;
  15294. this._time = 0;
  15295. this._manager = manager;
  15296. this._manager.sprites.push(this);
  15297. this.position = BABYLON.Vector3.Zero();
  15298. }
  15299. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15300. this._fromIndex = from;
  15301. this._toIndex = to;
  15302. this._loopAnimation = loop;
  15303. this._delay = delay;
  15304. this._animationStarted = true;
  15305. this._direction = from < to ? 1 : -1;
  15306. this.cellIndex = from;
  15307. this._time = 0;
  15308. };
  15309. Sprite.prototype.stopAnimation = function () {
  15310. this._animationStarted = false;
  15311. };
  15312. Sprite.prototype._animate = function (deltaTime) {
  15313. if (!this._animationStarted)
  15314. return;
  15315. this._time += deltaTime;
  15316. if (this._time > this._delay) {
  15317. this._time = this._time % this._delay;
  15318. this.cellIndex += this._direction;
  15319. if (this.cellIndex == this._toIndex) {
  15320. if (this._loopAnimation) {
  15321. this.cellIndex = this._fromIndex;
  15322. }
  15323. else {
  15324. this._animationStarted = false;
  15325. if (this.disposeWhenFinishedAnimating) {
  15326. this.dispose();
  15327. }
  15328. }
  15329. }
  15330. }
  15331. };
  15332. Sprite.prototype.dispose = function () {
  15333. for (var i = 0; i < this._manager.sprites.length; i++) {
  15334. if (this._manager.sprites[i] == this) {
  15335. this._manager.sprites.splice(i, 1);
  15336. }
  15337. }
  15338. };
  15339. return Sprite;
  15340. })();
  15341. BABYLON.Sprite = Sprite;
  15342. })(BABYLON || (BABYLON = {}));
  15343. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15344. (function (BABYLON) {
  15345. var Layer = (function () {
  15346. function Layer(name, imgUrl, scene, isBackground, color) {
  15347. this.name = name;
  15348. this._vertexDeclaration = [2];
  15349. this._vertexStrideSize = 2 * 4;
  15350. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15351. this.isBackground = isBackground === undefined ? true : isBackground;
  15352. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15353. this._scene = scene;
  15354. this._scene.layers.push(this);
  15355. // VBO
  15356. var vertices = [];
  15357. vertices.push(1, 1);
  15358. vertices.push(-1, 1);
  15359. vertices.push(-1, -1);
  15360. vertices.push(1, -1);
  15361. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15362. // Indices
  15363. var indices = [];
  15364. indices.push(0);
  15365. indices.push(1);
  15366. indices.push(2);
  15367. indices.push(0);
  15368. indices.push(2);
  15369. indices.push(3);
  15370. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15371. // Effects
  15372. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15373. }
  15374. Layer.prototype.render = function () {
  15375. // Check
  15376. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15377. return;
  15378. var engine = this._scene.getEngine();
  15379. // Render
  15380. engine.enableEffect(this._effect);
  15381. engine.setState(false);
  15382. // Texture
  15383. this._effect.setTexture("textureSampler", this.texture);
  15384. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15385. // Color
  15386. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15387. // VBOs
  15388. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15389. // Draw order
  15390. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15391. engine.draw(true, 0, 6);
  15392. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15393. };
  15394. Layer.prototype.dispose = function () {
  15395. if (this._vertexBuffer) {
  15396. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15397. this._vertexBuffer = null;
  15398. }
  15399. if (this._indexBuffer) {
  15400. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15401. this._indexBuffer = null;
  15402. }
  15403. if (this.texture) {
  15404. this.texture.dispose();
  15405. this.texture = null;
  15406. }
  15407. // Remove from scene
  15408. var index = this._scene.layers.indexOf(this);
  15409. this._scene.layers.splice(index, 1);
  15410. // Callback
  15411. if (this.onDispose) {
  15412. this.onDispose();
  15413. }
  15414. };
  15415. return Layer;
  15416. })();
  15417. BABYLON.Layer = Layer;
  15418. })(BABYLON || (BABYLON = {}));
  15419. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15420. (function (BABYLON) {
  15421. var Particle = (function () {
  15422. function Particle() {
  15423. this.position = BABYLON.Vector3.Zero();
  15424. this.direction = BABYLON.Vector3.Zero();
  15425. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15426. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15427. this.lifeTime = 1.0;
  15428. this.age = 0;
  15429. this.size = 0;
  15430. this.angle = 0;
  15431. this.angularSpeed = 0;
  15432. }
  15433. Particle.prototype.copyTo = function (other) {
  15434. other.position.copyFrom(this.position);
  15435. other.direction.copyFrom(this.direction);
  15436. other.color.copyFrom(this.color);
  15437. other.colorStep.copyFrom(this.colorStep);
  15438. other.lifeTime = this.lifeTime;
  15439. other.age = this.age;
  15440. other.size = this.size;
  15441. other.angle = this.angle;
  15442. other.angularSpeed = this.angularSpeed;
  15443. };
  15444. return Particle;
  15445. })();
  15446. BABYLON.Particle = Particle;
  15447. })(BABYLON || (BABYLON = {}));
  15448. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15449. (function (BABYLON) {
  15450. var randomNumber = function (min, max) {
  15451. if (min === max) {
  15452. return (min);
  15453. }
  15454. var random = Math.random();
  15455. return ((random * (max - min)) + min);
  15456. };
  15457. var ParticleSystem = (function () {
  15458. function ParticleSystem(name, capacity, scene, customEffect) {
  15459. var _this = this;
  15460. this.name = name;
  15461. this.renderingGroupId = 0;
  15462. this.emitter = null;
  15463. this.emitRate = 10;
  15464. this.manualEmitCount = -1;
  15465. this.updateSpeed = 0.01;
  15466. this.targetStopDuration = 0;
  15467. this.disposeOnStop = false;
  15468. this.minEmitPower = 1;
  15469. this.maxEmitPower = 1;
  15470. this.minLifeTime = 1;
  15471. this.maxLifeTime = 1;
  15472. this.minSize = 1;
  15473. this.maxSize = 1;
  15474. this.minAngularSpeed = 0;
  15475. this.maxAngularSpeed = 0;
  15476. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15477. this.forceDepthWrite = false;
  15478. this.gravity = BABYLON.Vector3.Zero();
  15479. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15480. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15481. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15482. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15483. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15484. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15485. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15486. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15487. this.particles = new Array();
  15488. this._vertexDeclaration = [3, 4, 4];
  15489. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15490. this._stockParticles = new Array();
  15491. this._newPartsExcess = 0;
  15492. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15493. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15494. this._scaledDirection = BABYLON.Vector3.Zero();
  15495. this._scaledGravity = BABYLON.Vector3.Zero();
  15496. this._currentRenderId = -1;
  15497. this._started = false;
  15498. this._stopped = false;
  15499. this._actualFrame = 0;
  15500. this.id = name;
  15501. this._capacity = capacity;
  15502. this._scene = scene;
  15503. this._customEffect = customEffect;
  15504. scene.particleSystems.push(this);
  15505. // VBO
  15506. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15507. var indices = [];
  15508. var index = 0;
  15509. for (var count = 0; count < capacity; count++) {
  15510. indices.push(index);
  15511. indices.push(index + 1);
  15512. indices.push(index + 2);
  15513. indices.push(index);
  15514. indices.push(index + 2);
  15515. indices.push(index + 3);
  15516. index += 4;
  15517. }
  15518. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15519. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15520. // Default behaviors
  15521. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15522. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15523. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15524. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15525. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15526. };
  15527. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15528. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15529. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15530. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15531. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15532. };
  15533. this.updateFunction = function (particles) {
  15534. for (var index = 0; index < particles.length; index++) {
  15535. var particle = particles[index];
  15536. particle.age += _this._scaledUpdateSpeed;
  15537. if (particle.age >= particle.lifeTime) {
  15538. _this.recycleParticle(particle);
  15539. index--;
  15540. continue;
  15541. }
  15542. else {
  15543. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15544. particle.color.addInPlace(_this._scaledColorStep);
  15545. if (particle.color.a < 0)
  15546. particle.color.a = 0;
  15547. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15548. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15549. particle.position.addInPlace(_this._scaledDirection);
  15550. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15551. particle.direction.addInPlace(_this._scaledGravity);
  15552. }
  15553. }
  15554. };
  15555. }
  15556. ParticleSystem.prototype.recycleParticle = function (particle) {
  15557. var lastParticle = this.particles.pop();
  15558. if (lastParticle !== particle) {
  15559. lastParticle.copyTo(particle);
  15560. this._stockParticles.push(lastParticle);
  15561. }
  15562. };
  15563. ParticleSystem.prototype.getCapacity = function () {
  15564. return this._capacity;
  15565. };
  15566. ParticleSystem.prototype.isAlive = function () {
  15567. return this._alive;
  15568. };
  15569. ParticleSystem.prototype.isStarted = function () {
  15570. return this._started;
  15571. };
  15572. ParticleSystem.prototype.start = function () {
  15573. this._started = true;
  15574. this._stopped = false;
  15575. this._actualFrame = 0;
  15576. };
  15577. ParticleSystem.prototype.stop = function () {
  15578. this._stopped = true;
  15579. };
  15580. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15581. var offset = index * 11;
  15582. this._vertices[offset] = particle.position.x;
  15583. this._vertices[offset + 1] = particle.position.y;
  15584. this._vertices[offset + 2] = particle.position.z;
  15585. this._vertices[offset + 3] = particle.color.r;
  15586. this._vertices[offset + 4] = particle.color.g;
  15587. this._vertices[offset + 5] = particle.color.b;
  15588. this._vertices[offset + 6] = particle.color.a;
  15589. this._vertices[offset + 7] = particle.angle;
  15590. this._vertices[offset + 8] = particle.size;
  15591. this._vertices[offset + 9] = offsetX;
  15592. this._vertices[offset + 10] = offsetY;
  15593. };
  15594. ParticleSystem.prototype._update = function (newParticles) {
  15595. // Update current
  15596. this._alive = this.particles.length > 0;
  15597. this.updateFunction(this.particles);
  15598. // Add new ones
  15599. var worldMatrix;
  15600. if (this.emitter.position) {
  15601. worldMatrix = this.emitter.getWorldMatrix();
  15602. }
  15603. else {
  15604. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15605. }
  15606. for (var index = 0; index < newParticles; index++) {
  15607. if (this.particles.length === this._capacity) {
  15608. break;
  15609. }
  15610. if (this._stockParticles.length !== 0) {
  15611. var particle = this._stockParticles.pop();
  15612. particle.age = 0;
  15613. }
  15614. else {
  15615. particle = new BABYLON.Particle();
  15616. }
  15617. this.particles.push(particle);
  15618. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15619. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15620. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15621. particle.size = randomNumber(this.minSize, this.maxSize);
  15622. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15623. this.startPositionFunction(worldMatrix, particle.position);
  15624. var step = randomNumber(0, 1.0);
  15625. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15626. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15627. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15628. }
  15629. };
  15630. ParticleSystem.prototype._getEffect = function () {
  15631. if (this._customEffect) {
  15632. return this._customEffect;
  15633. }
  15634. ;
  15635. var defines = [];
  15636. if (this._scene.clipPlane) {
  15637. defines.push("#define CLIPPLANE");
  15638. }
  15639. // Effect
  15640. var join = defines.join("\n");
  15641. if (this._cachedDefines !== join) {
  15642. this._cachedDefines = join;
  15643. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15644. }
  15645. return this._effect;
  15646. };
  15647. ParticleSystem.prototype.animate = function () {
  15648. if (!this._started)
  15649. return;
  15650. var effect = this._getEffect();
  15651. // Check
  15652. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15653. return;
  15654. if (this._currentRenderId === this._scene.getRenderId()) {
  15655. return;
  15656. }
  15657. this._currentRenderId = this._scene.getRenderId();
  15658. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15659. // determine the number of particles we need to create
  15660. var emitCout;
  15661. if (this.manualEmitCount > -1) {
  15662. emitCout = this.manualEmitCount;
  15663. this.manualEmitCount = 0;
  15664. }
  15665. else {
  15666. emitCout = this.emitRate;
  15667. }
  15668. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15669. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15670. if (this._newPartsExcess > 1.0) {
  15671. newParticles += this._newPartsExcess >> 0;
  15672. this._newPartsExcess -= this._newPartsExcess >> 0;
  15673. }
  15674. this._alive = false;
  15675. if (!this._stopped) {
  15676. this._actualFrame += this._scaledUpdateSpeed;
  15677. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15678. this.stop();
  15679. }
  15680. else {
  15681. newParticles = 0;
  15682. }
  15683. this._update(newParticles);
  15684. // Stopped?
  15685. if (this._stopped) {
  15686. if (!this._alive) {
  15687. this._started = false;
  15688. if (this.disposeOnStop) {
  15689. this._scene._toBeDisposed.push(this);
  15690. }
  15691. }
  15692. }
  15693. // Update VBO
  15694. var offset = 0;
  15695. for (var index = 0; index < this.particles.length; index++) {
  15696. var particle = this.particles[index];
  15697. this._appendParticleVertex(offset++, particle, 0, 0);
  15698. this._appendParticleVertex(offset++, particle, 1, 0);
  15699. this._appendParticleVertex(offset++, particle, 1, 1);
  15700. this._appendParticleVertex(offset++, particle, 0, 1);
  15701. }
  15702. var engine = this._scene.getEngine();
  15703. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15704. };
  15705. ParticleSystem.prototype.render = function () {
  15706. var effect = this._getEffect();
  15707. // Check
  15708. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15709. return 0;
  15710. var engine = this._scene.getEngine();
  15711. // Render
  15712. engine.enableEffect(effect);
  15713. engine.setState(false);
  15714. var viewMatrix = this._scene.getViewMatrix();
  15715. effect.setTexture("diffuseSampler", this.particleTexture);
  15716. effect.setMatrix("view", viewMatrix);
  15717. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15718. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15719. if (this._scene.clipPlane) {
  15720. var clipPlane = this._scene.clipPlane;
  15721. var invView = viewMatrix.clone();
  15722. invView.invert();
  15723. effect.setMatrix("invView", invView);
  15724. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15725. }
  15726. // VBOs
  15727. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15728. // Draw order
  15729. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15730. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15731. }
  15732. else {
  15733. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15734. }
  15735. if (this.forceDepthWrite) {
  15736. engine.setDepthWrite(true);
  15737. }
  15738. engine.draw(true, 0, this.particles.length * 6);
  15739. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15740. return this.particles.length;
  15741. };
  15742. ParticleSystem.prototype.dispose = function () {
  15743. if (this._vertexBuffer) {
  15744. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15745. this._vertexBuffer = null;
  15746. }
  15747. if (this._indexBuffer) {
  15748. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15749. this._indexBuffer = null;
  15750. }
  15751. if (this.particleTexture) {
  15752. this.particleTexture.dispose();
  15753. this.particleTexture = null;
  15754. }
  15755. // Remove from scene
  15756. var index = this._scene.particleSystems.indexOf(this);
  15757. this._scene.particleSystems.splice(index, 1);
  15758. // Callback
  15759. if (this.onDispose) {
  15760. this.onDispose();
  15761. }
  15762. };
  15763. // Clone
  15764. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15765. var result = new ParticleSystem(name, this._capacity, this._scene);
  15766. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15767. if (newEmitter === undefined) {
  15768. newEmitter = this.emitter;
  15769. }
  15770. result.emitter = newEmitter;
  15771. if (this.particleTexture) {
  15772. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15773. }
  15774. result.start();
  15775. return result;
  15776. };
  15777. // Statics
  15778. ParticleSystem.BLENDMODE_ONEONE = 0;
  15779. ParticleSystem.BLENDMODE_STANDARD = 1;
  15780. return ParticleSystem;
  15781. })();
  15782. BABYLON.ParticleSystem = ParticleSystem;
  15783. })(BABYLON || (BABYLON = {}));
  15784. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15785. (function (BABYLON) {
  15786. var Animation = (function () {
  15787. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15788. this.name = name;
  15789. this.targetProperty = targetProperty;
  15790. this.framePerSecond = framePerSecond;
  15791. this.dataType = dataType;
  15792. this.loopMode = loopMode;
  15793. this._offsetsCache = {};
  15794. this._highLimitsCache = {};
  15795. this._stopped = false;
  15796. this.targetPropertyPath = targetProperty.split(".");
  15797. this.dataType = dataType;
  15798. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15799. }
  15800. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15801. var dataType = undefined;
  15802. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15803. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15804. }
  15805. else if (from instanceof BABYLON.Quaternion) {
  15806. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15807. }
  15808. else if (from instanceof BABYLON.Vector3) {
  15809. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15810. }
  15811. else if (from instanceof BABYLON.Vector2) {
  15812. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15813. }
  15814. else if (from instanceof BABYLON.Color3) {
  15815. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15816. }
  15817. if (dataType == undefined) {
  15818. return null;
  15819. }
  15820. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15821. var keys = [];
  15822. keys.push({ frame: 0, value: from });
  15823. keys.push({ frame: totalFrame, value: to });
  15824. animation.setKeys(keys);
  15825. mesh.animations.push(animation);
  15826. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15827. };
  15828. // Methods
  15829. Animation.prototype.isStopped = function () {
  15830. return this._stopped;
  15831. };
  15832. Animation.prototype.getKeys = function () {
  15833. return this._keys;
  15834. };
  15835. Animation.prototype.getEasingFunction = function () {
  15836. return this._easingFunction;
  15837. };
  15838. Animation.prototype.setEasingFunction = function (easingFunction) {
  15839. this._easingFunction = easingFunction;
  15840. };
  15841. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15842. return startValue + (endValue - startValue) * gradient;
  15843. };
  15844. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15845. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15846. };
  15847. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15848. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15849. };
  15850. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15851. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15852. };
  15853. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15854. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15855. };
  15856. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15857. var startScale = new BABYLON.Vector3(0, 0, 0);
  15858. var startRotation = new BABYLON.Quaternion();
  15859. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15860. startValue.decompose(startScale, startRotation, startTranslation);
  15861. var endScale = new BABYLON.Vector3(0, 0, 0);
  15862. var endRotation = new BABYLON.Quaternion();
  15863. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15864. endValue.decompose(endScale, endRotation, endTranslation);
  15865. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15866. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15867. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15868. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15869. return result;
  15870. };
  15871. Animation.prototype.clone = function () {
  15872. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15873. clone.setKeys(this._keys);
  15874. return clone;
  15875. };
  15876. Animation.prototype.setKeys = function (values) {
  15877. this._keys = values.slice(0);
  15878. this._offsetsCache = {};
  15879. this._highLimitsCache = {};
  15880. };
  15881. Animation.prototype._getKeyValue = function (value) {
  15882. if (typeof value === "function") {
  15883. return value();
  15884. }
  15885. return value;
  15886. };
  15887. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15888. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15889. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15890. }
  15891. this.currentFrame = currentFrame;
  15892. for (var key = 0; key < this._keys.length; key++) {
  15893. // for each frame, we need the key just before the frame superior
  15894. if (this._keys[key + 1].frame >= currentFrame) {
  15895. var startValue = this._getKeyValue(this._keys[key].value);
  15896. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15897. // gradient : percent of currentFrame between the frame inf and the frame sup
  15898. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15899. // check for easingFunction and correction of gradient
  15900. if (this._easingFunction != null) {
  15901. gradient = this._easingFunction.ease(gradient);
  15902. }
  15903. switch (this.dataType) {
  15904. case Animation.ANIMATIONTYPE_FLOAT:
  15905. switch (loopMode) {
  15906. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15907. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15908. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15909. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15910. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15911. }
  15912. break;
  15913. case Animation.ANIMATIONTYPE_QUATERNION:
  15914. var quaternion = null;
  15915. switch (loopMode) {
  15916. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15917. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15918. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15919. break;
  15920. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15921. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15922. break;
  15923. }
  15924. return quaternion;
  15925. case Animation.ANIMATIONTYPE_VECTOR3:
  15926. switch (loopMode) {
  15927. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15928. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15929. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15930. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15931. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15932. }
  15933. case Animation.ANIMATIONTYPE_VECTOR2:
  15934. switch (loopMode) {
  15935. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15936. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15937. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15938. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15939. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15940. }
  15941. case Animation.ANIMATIONTYPE_COLOR3:
  15942. switch (loopMode) {
  15943. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15944. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15945. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15946. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15947. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15948. }
  15949. case Animation.ANIMATIONTYPE_MATRIX:
  15950. switch (loopMode) {
  15951. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15952. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15953. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15954. return startValue;
  15955. }
  15956. default:
  15957. break;
  15958. }
  15959. break;
  15960. }
  15961. }
  15962. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15963. };
  15964. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15965. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15966. this._stopped = true;
  15967. return false;
  15968. }
  15969. var returnValue = true;
  15970. // Adding a start key at frame 0 if missing
  15971. if (this._keys[0].frame !== 0) {
  15972. var newKey = { frame: 0, value: this._keys[0].value };
  15973. this._keys.splice(0, 0, newKey);
  15974. }
  15975. // Check limits
  15976. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15977. from = this._keys[0].frame;
  15978. }
  15979. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15980. to = this._keys[this._keys.length - 1].frame;
  15981. }
  15982. // Compute ratio
  15983. var range = to - from;
  15984. var offsetValue;
  15985. // ratio represents the frame delta between from and to
  15986. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15987. var highLimitValue = 0;
  15988. if (ratio > range && !loop) {
  15989. returnValue = false;
  15990. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15991. }
  15992. else {
  15993. // Get max value if required
  15994. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15995. var keyOffset = to.toString() + from.toString();
  15996. if (!this._offsetsCache[keyOffset]) {
  15997. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15998. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15999. switch (this.dataType) {
  16000. case Animation.ANIMATIONTYPE_FLOAT:
  16001. this._offsetsCache[keyOffset] = toValue - fromValue;
  16002. break;
  16003. case Animation.ANIMATIONTYPE_QUATERNION:
  16004. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16005. break;
  16006. case Animation.ANIMATIONTYPE_VECTOR3:
  16007. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16008. case Animation.ANIMATIONTYPE_VECTOR2:
  16009. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16010. case Animation.ANIMATIONTYPE_COLOR3:
  16011. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  16012. default:
  16013. break;
  16014. }
  16015. this._highLimitsCache[keyOffset] = toValue;
  16016. }
  16017. highLimitValue = this._highLimitsCache[keyOffset];
  16018. offsetValue = this._offsetsCache[keyOffset];
  16019. }
  16020. }
  16021. if (offsetValue === undefined) {
  16022. switch (this.dataType) {
  16023. case Animation.ANIMATIONTYPE_FLOAT:
  16024. offsetValue = 0;
  16025. break;
  16026. case Animation.ANIMATIONTYPE_QUATERNION:
  16027. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  16028. break;
  16029. case Animation.ANIMATIONTYPE_VECTOR3:
  16030. offsetValue = BABYLON.Vector3.Zero();
  16031. break;
  16032. case Animation.ANIMATIONTYPE_VECTOR2:
  16033. offsetValue = BABYLON.Vector2.Zero();
  16034. break;
  16035. case Animation.ANIMATIONTYPE_COLOR3:
  16036. offsetValue = BABYLON.Color3.Black();
  16037. }
  16038. }
  16039. // Compute value
  16040. var repeatCount = (ratio / range) >> 0;
  16041. var currentFrame = returnValue ? from + ratio % range : to;
  16042. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  16043. // Set value
  16044. if (this.targetPropertyPath.length > 1) {
  16045. var property = this._target[this.targetPropertyPath[0]];
  16046. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  16047. property = property[this.targetPropertyPath[index]];
  16048. }
  16049. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  16050. }
  16051. else {
  16052. this._target[this.targetPropertyPath[0]] = currentValue;
  16053. }
  16054. if (this._target.markAsDirty) {
  16055. this._target.markAsDirty(this.targetProperty);
  16056. }
  16057. if (!returnValue) {
  16058. this._stopped = true;
  16059. }
  16060. return returnValue;
  16061. };
  16062. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  16063. get: function () {
  16064. return Animation._ANIMATIONTYPE_FLOAT;
  16065. },
  16066. enumerable: true,
  16067. configurable: true
  16068. });
  16069. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  16070. get: function () {
  16071. return Animation._ANIMATIONTYPE_VECTOR3;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  16077. get: function () {
  16078. return Animation._ANIMATIONTYPE_VECTOR2;
  16079. },
  16080. enumerable: true,
  16081. configurable: true
  16082. });
  16083. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  16084. get: function () {
  16085. return Animation._ANIMATIONTYPE_QUATERNION;
  16086. },
  16087. enumerable: true,
  16088. configurable: true
  16089. });
  16090. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  16091. get: function () {
  16092. return Animation._ANIMATIONTYPE_MATRIX;
  16093. },
  16094. enumerable: true,
  16095. configurable: true
  16096. });
  16097. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  16098. get: function () {
  16099. return Animation._ANIMATIONTYPE_COLOR3;
  16100. },
  16101. enumerable: true,
  16102. configurable: true
  16103. });
  16104. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  16105. get: function () {
  16106. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  16107. },
  16108. enumerable: true,
  16109. configurable: true
  16110. });
  16111. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  16112. get: function () {
  16113. return Animation._ANIMATIONLOOPMODE_CYCLE;
  16114. },
  16115. enumerable: true,
  16116. configurable: true
  16117. });
  16118. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  16119. get: function () {
  16120. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  16121. },
  16122. enumerable: true,
  16123. configurable: true
  16124. });
  16125. // Statics
  16126. Animation._ANIMATIONTYPE_FLOAT = 0;
  16127. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  16128. Animation._ANIMATIONTYPE_QUATERNION = 2;
  16129. Animation._ANIMATIONTYPE_MATRIX = 3;
  16130. Animation._ANIMATIONTYPE_COLOR3 = 4;
  16131. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  16132. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  16133. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  16134. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  16135. return Animation;
  16136. })();
  16137. BABYLON.Animation = Animation;
  16138. })(BABYLON || (BABYLON = {}));
  16139. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  16140. (function (BABYLON) {
  16141. var Animatable = (function () {
  16142. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  16143. if (fromFrame === void 0) { fromFrame = 0; }
  16144. if (toFrame === void 0) { toFrame = 100; }
  16145. if (loopAnimation === void 0) { loopAnimation = false; }
  16146. if (speedRatio === void 0) { speedRatio = 1.0; }
  16147. this.target = target;
  16148. this.fromFrame = fromFrame;
  16149. this.toFrame = toFrame;
  16150. this.loopAnimation = loopAnimation;
  16151. this.speedRatio = speedRatio;
  16152. this.onAnimationEnd = onAnimationEnd;
  16153. this._animations = new Array();
  16154. this._paused = false;
  16155. this.animationStarted = false;
  16156. if (animations) {
  16157. this.appendAnimations(target, animations);
  16158. }
  16159. this._scene = scene;
  16160. scene._activeAnimatables.push(this);
  16161. }
  16162. // Methods
  16163. Animatable.prototype.appendAnimations = function (target, animations) {
  16164. for (var index = 0; index < animations.length; index++) {
  16165. var animation = animations[index];
  16166. animation._target = target;
  16167. this._animations.push(animation);
  16168. }
  16169. };
  16170. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16171. var animations = this._animations;
  16172. for (var index = 0; index < animations.length; index++) {
  16173. if (animations[index].targetProperty === property) {
  16174. return animations[index];
  16175. }
  16176. }
  16177. return null;
  16178. };
  16179. Animatable.prototype.pause = function () {
  16180. if (this._paused) {
  16181. return;
  16182. }
  16183. this._paused = true;
  16184. };
  16185. Animatable.prototype.restart = function () {
  16186. this._paused = false;
  16187. };
  16188. Animatable.prototype.stop = function () {
  16189. var index = this._scene._activeAnimatables.indexOf(this);
  16190. if (index > -1) {
  16191. this._scene._activeAnimatables.splice(index, 1);
  16192. }
  16193. if (this.onAnimationEnd) {
  16194. this.onAnimationEnd();
  16195. }
  16196. };
  16197. Animatable.prototype._animate = function (delay) {
  16198. if (this._paused) {
  16199. if (!this._pausedDelay) {
  16200. this._pausedDelay = delay;
  16201. }
  16202. return true;
  16203. }
  16204. if (!this._localDelayOffset) {
  16205. this._localDelayOffset = delay;
  16206. }
  16207. else if (this._pausedDelay) {
  16208. this._localDelayOffset += delay - this._pausedDelay;
  16209. this._pausedDelay = null;
  16210. }
  16211. // Animating
  16212. var running = false;
  16213. var animations = this._animations;
  16214. for (var index = 0; index < animations.length; index++) {
  16215. var animation = animations[index];
  16216. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16217. running = running || isRunning;
  16218. }
  16219. if (!running && this.onAnimationEnd) {
  16220. this.onAnimationEnd();
  16221. }
  16222. return running;
  16223. };
  16224. return Animatable;
  16225. })();
  16226. BABYLON.Animatable = Animatable;
  16227. })(BABYLON || (BABYLON = {}));
  16228. //# sourceMappingURL=babylon.animatable.js.map
  16229. var BABYLON;
  16230. (function (BABYLON) {
  16231. var EasingFunction = (function () {
  16232. function EasingFunction() {
  16233. // Properties
  16234. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16235. }
  16236. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16237. get: function () {
  16238. return EasingFunction._EASINGMODE_EASEIN;
  16239. },
  16240. enumerable: true,
  16241. configurable: true
  16242. });
  16243. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16244. get: function () {
  16245. return EasingFunction._EASINGMODE_EASEOUT;
  16246. },
  16247. enumerable: true,
  16248. configurable: true
  16249. });
  16250. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16251. get: function () {
  16252. return EasingFunction._EASINGMODE_EASEINOUT;
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16258. var n = Math.min(Math.max(easingMode, 0), 2);
  16259. this._easingMode = n;
  16260. };
  16261. EasingFunction.prototype.getEasingMode = function () {
  16262. return this._easingMode;
  16263. };
  16264. EasingFunction.prototype.easeInCore = function (gradient) {
  16265. throw new Error('You must implement this method');
  16266. };
  16267. EasingFunction.prototype.ease = function (gradient) {
  16268. switch (this._easingMode) {
  16269. case EasingFunction.EASINGMODE_EASEIN:
  16270. return this.easeInCore(gradient);
  16271. case EasingFunction.EASINGMODE_EASEOUT:
  16272. return (1 - this.easeInCore(1 - gradient));
  16273. }
  16274. if (gradient >= 0.5) {
  16275. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16276. }
  16277. return (this.easeInCore(gradient * 2) * 0.5);
  16278. };
  16279. //Statics
  16280. EasingFunction._EASINGMODE_EASEIN = 0;
  16281. EasingFunction._EASINGMODE_EASEOUT = 1;
  16282. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16283. return EasingFunction;
  16284. })();
  16285. BABYLON.EasingFunction = EasingFunction;
  16286. var CircleEase = (function (_super) {
  16287. __extends(CircleEase, _super);
  16288. function CircleEase() {
  16289. _super.apply(this, arguments);
  16290. }
  16291. CircleEase.prototype.easeInCore = function (gradient) {
  16292. gradient = Math.max(0, Math.min(1, gradient));
  16293. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16294. };
  16295. return CircleEase;
  16296. })(EasingFunction);
  16297. BABYLON.CircleEase = CircleEase;
  16298. var BackEase = (function (_super) {
  16299. __extends(BackEase, _super);
  16300. function BackEase(amplitude) {
  16301. if (amplitude === void 0) { amplitude = 1; }
  16302. _super.call(this);
  16303. this.amplitude = amplitude;
  16304. }
  16305. BackEase.prototype.easeInCore = function (gradient) {
  16306. var num = Math.max(0, this.amplitude);
  16307. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16308. };
  16309. return BackEase;
  16310. })(EasingFunction);
  16311. BABYLON.BackEase = BackEase;
  16312. var BounceEase = (function (_super) {
  16313. __extends(BounceEase, _super);
  16314. function BounceEase(bounces, bounciness) {
  16315. if (bounces === void 0) { bounces = 3; }
  16316. if (bounciness === void 0) { bounciness = 2; }
  16317. _super.call(this);
  16318. this.bounces = bounces;
  16319. this.bounciness = bounciness;
  16320. }
  16321. BounceEase.prototype.easeInCore = function (gradient) {
  16322. var y = Math.max(0.0, this.bounces);
  16323. var bounciness = this.bounciness;
  16324. if (bounciness <= 1.0) {
  16325. bounciness = 1.001;
  16326. }
  16327. var num9 = Math.pow(bounciness, y);
  16328. var num5 = 1.0 - bounciness;
  16329. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16330. var num15 = gradient * num4;
  16331. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16332. var num3 = Math.floor(num65);
  16333. var num13 = num3 + 1.0;
  16334. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16335. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16336. var num7 = (num8 + num12) * 0.5;
  16337. var num6 = gradient - num7;
  16338. var num2 = num7 - num8;
  16339. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16340. };
  16341. return BounceEase;
  16342. })(EasingFunction);
  16343. BABYLON.BounceEase = BounceEase;
  16344. var CubicEase = (function (_super) {
  16345. __extends(CubicEase, _super);
  16346. function CubicEase() {
  16347. _super.apply(this, arguments);
  16348. }
  16349. CubicEase.prototype.easeInCore = function (gradient) {
  16350. return (gradient * gradient * gradient);
  16351. };
  16352. return CubicEase;
  16353. })(EasingFunction);
  16354. BABYLON.CubicEase = CubicEase;
  16355. var ElasticEase = (function (_super) {
  16356. __extends(ElasticEase, _super);
  16357. function ElasticEase(oscillations, springiness) {
  16358. if (oscillations === void 0) { oscillations = 3; }
  16359. if (springiness === void 0) { springiness = 3; }
  16360. _super.call(this);
  16361. this.oscillations = oscillations;
  16362. this.springiness = springiness;
  16363. }
  16364. ElasticEase.prototype.easeInCore = function (gradient) {
  16365. var num2;
  16366. var num3 = Math.max(0.0, this.oscillations);
  16367. var num = Math.max(0.0, this.springiness);
  16368. if (num == 0) {
  16369. num2 = gradient;
  16370. }
  16371. else {
  16372. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16373. }
  16374. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16375. };
  16376. return ElasticEase;
  16377. })(EasingFunction);
  16378. BABYLON.ElasticEase = ElasticEase;
  16379. var ExponentialEase = (function (_super) {
  16380. __extends(ExponentialEase, _super);
  16381. function ExponentialEase(exponent) {
  16382. if (exponent === void 0) { exponent = 2; }
  16383. _super.call(this);
  16384. this.exponent = exponent;
  16385. }
  16386. ExponentialEase.prototype.easeInCore = function (gradient) {
  16387. if (this.exponent <= 0) {
  16388. return gradient;
  16389. }
  16390. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16391. };
  16392. return ExponentialEase;
  16393. })(EasingFunction);
  16394. BABYLON.ExponentialEase = ExponentialEase;
  16395. var PowerEase = (function (_super) {
  16396. __extends(PowerEase, _super);
  16397. function PowerEase(power) {
  16398. if (power === void 0) { power = 2; }
  16399. _super.call(this);
  16400. this.power = power;
  16401. }
  16402. PowerEase.prototype.easeInCore = function (gradient) {
  16403. var y = Math.max(0.0, this.power);
  16404. return Math.pow(gradient, y);
  16405. };
  16406. return PowerEase;
  16407. })(EasingFunction);
  16408. BABYLON.PowerEase = PowerEase;
  16409. var QuadraticEase = (function (_super) {
  16410. __extends(QuadraticEase, _super);
  16411. function QuadraticEase() {
  16412. _super.apply(this, arguments);
  16413. }
  16414. QuadraticEase.prototype.easeInCore = function (gradient) {
  16415. return (gradient * gradient);
  16416. };
  16417. return QuadraticEase;
  16418. })(EasingFunction);
  16419. BABYLON.QuadraticEase = QuadraticEase;
  16420. var QuarticEase = (function (_super) {
  16421. __extends(QuarticEase, _super);
  16422. function QuarticEase() {
  16423. _super.apply(this, arguments);
  16424. }
  16425. QuarticEase.prototype.easeInCore = function (gradient) {
  16426. return (gradient * gradient * gradient * gradient);
  16427. };
  16428. return QuarticEase;
  16429. })(EasingFunction);
  16430. BABYLON.QuarticEase = QuarticEase;
  16431. var QuinticEase = (function (_super) {
  16432. __extends(QuinticEase, _super);
  16433. function QuinticEase() {
  16434. _super.apply(this, arguments);
  16435. }
  16436. QuinticEase.prototype.easeInCore = function (gradient) {
  16437. return (gradient * gradient * gradient * gradient * gradient);
  16438. };
  16439. return QuinticEase;
  16440. })(EasingFunction);
  16441. BABYLON.QuinticEase = QuinticEase;
  16442. var SineEase = (function (_super) {
  16443. __extends(SineEase, _super);
  16444. function SineEase() {
  16445. _super.apply(this, arguments);
  16446. }
  16447. SineEase.prototype.easeInCore = function (gradient) {
  16448. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16449. };
  16450. return SineEase;
  16451. })(EasingFunction);
  16452. BABYLON.SineEase = SineEase;
  16453. var BezierCurveEase = (function (_super) {
  16454. __extends(BezierCurveEase, _super);
  16455. function BezierCurveEase(x1, y1, x2, y2) {
  16456. if (x1 === void 0) { x1 = 0; }
  16457. if (y1 === void 0) { y1 = 0; }
  16458. if (x2 === void 0) { x2 = 1; }
  16459. if (y2 === void 0) { y2 = 1; }
  16460. _super.call(this);
  16461. this.x1 = x1;
  16462. this.y1 = y1;
  16463. this.x2 = x2;
  16464. this.y2 = y2;
  16465. }
  16466. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16467. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16468. };
  16469. return BezierCurveEase;
  16470. })(EasingFunction);
  16471. BABYLON.BezierCurveEase = BezierCurveEase;
  16472. })(BABYLON || (BABYLON = {}));
  16473. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16474. (function (BABYLON) {
  16475. var Octree = (function () {
  16476. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16477. if (maxDepth === void 0) { maxDepth = 2; }
  16478. this.maxDepth = maxDepth;
  16479. this.dynamicContent = new Array();
  16480. this._maxBlockCapacity = maxBlockCapacity || 64;
  16481. this._selectionContent = new BABYLON.SmartArray(1024);
  16482. this._creationFunc = creationFunc;
  16483. }
  16484. // Methods
  16485. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16486. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16487. };
  16488. Octree.prototype.addMesh = function (entry) {
  16489. for (var index = 0; index < this.blocks.length; index++) {
  16490. var block = this.blocks[index];
  16491. block.addEntry(entry);
  16492. }
  16493. };
  16494. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16495. this._selectionContent.reset();
  16496. for (var index = 0; index < this.blocks.length; index++) {
  16497. var block = this.blocks[index];
  16498. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16499. }
  16500. if (allowDuplicate) {
  16501. this._selectionContent.concat(this.dynamicContent);
  16502. }
  16503. else {
  16504. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16505. }
  16506. return this._selectionContent;
  16507. };
  16508. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16509. this._selectionContent.reset();
  16510. for (var index = 0; index < this.blocks.length; index++) {
  16511. var block = this.blocks[index];
  16512. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16513. }
  16514. if (allowDuplicate) {
  16515. this._selectionContent.concat(this.dynamicContent);
  16516. }
  16517. else {
  16518. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16519. }
  16520. return this._selectionContent;
  16521. };
  16522. Octree.prototype.intersectsRay = function (ray) {
  16523. this._selectionContent.reset();
  16524. for (var index = 0; index < this.blocks.length; index++) {
  16525. var block = this.blocks[index];
  16526. block.intersectsRay(ray, this._selectionContent);
  16527. }
  16528. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16529. return this._selectionContent;
  16530. };
  16531. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16532. target.blocks = new Array();
  16533. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16534. for (var x = 0; x < 2; x++) {
  16535. for (var y = 0; y < 2; y++) {
  16536. for (var z = 0; z < 2; z++) {
  16537. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16538. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16539. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16540. block.addEntries(entries);
  16541. target.blocks.push(block);
  16542. }
  16543. }
  16544. }
  16545. };
  16546. Octree.CreationFuncForMeshes = function (entry, block) {
  16547. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16548. block.entries.push(entry);
  16549. }
  16550. };
  16551. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16552. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16553. block.entries.push(entry);
  16554. }
  16555. };
  16556. return Octree;
  16557. })();
  16558. BABYLON.Octree = Octree;
  16559. })(BABYLON || (BABYLON = {}));
  16560. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16561. (function (BABYLON) {
  16562. var OctreeBlock = (function () {
  16563. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16564. this.entries = new Array();
  16565. this._boundingVectors = new Array();
  16566. this._capacity = capacity;
  16567. this._depth = depth;
  16568. this._maxDepth = maxDepth;
  16569. this._creationFunc = creationFunc;
  16570. this._minPoint = minPoint;
  16571. this._maxPoint = maxPoint;
  16572. this._boundingVectors.push(minPoint.clone());
  16573. this._boundingVectors.push(maxPoint.clone());
  16574. this._boundingVectors.push(minPoint.clone());
  16575. this._boundingVectors[2].x = maxPoint.x;
  16576. this._boundingVectors.push(minPoint.clone());
  16577. this._boundingVectors[3].y = maxPoint.y;
  16578. this._boundingVectors.push(minPoint.clone());
  16579. this._boundingVectors[4].z = maxPoint.z;
  16580. this._boundingVectors.push(maxPoint.clone());
  16581. this._boundingVectors[5].z = minPoint.z;
  16582. this._boundingVectors.push(maxPoint.clone());
  16583. this._boundingVectors[6].x = minPoint.x;
  16584. this._boundingVectors.push(maxPoint.clone());
  16585. this._boundingVectors[7].y = minPoint.y;
  16586. }
  16587. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16588. // Property
  16589. get: function () {
  16590. return this._capacity;
  16591. },
  16592. enumerable: true,
  16593. configurable: true
  16594. });
  16595. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16596. get: function () {
  16597. return this._minPoint;
  16598. },
  16599. enumerable: true,
  16600. configurable: true
  16601. });
  16602. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16603. get: function () {
  16604. return this._maxPoint;
  16605. },
  16606. enumerable: true,
  16607. configurable: true
  16608. });
  16609. // Methods
  16610. OctreeBlock.prototype.addEntry = function (entry) {
  16611. if (this.blocks) {
  16612. for (var index = 0; index < this.blocks.length; index++) {
  16613. var block = this.blocks[index];
  16614. block.addEntry(entry);
  16615. }
  16616. return;
  16617. }
  16618. this._creationFunc(entry, this);
  16619. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16620. this.createInnerBlocks();
  16621. }
  16622. };
  16623. OctreeBlock.prototype.addEntries = function (entries) {
  16624. for (var index = 0; index < entries.length; index++) {
  16625. var mesh = entries[index];
  16626. this.addEntry(mesh);
  16627. }
  16628. };
  16629. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16630. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16631. if (this.blocks) {
  16632. for (var index = 0; index < this.blocks.length; index++) {
  16633. var block = this.blocks[index];
  16634. block.select(frustumPlanes, selection, allowDuplicate);
  16635. }
  16636. return;
  16637. }
  16638. if (allowDuplicate) {
  16639. selection.concat(this.entries);
  16640. }
  16641. else {
  16642. selection.concatWithNoDuplicate(this.entries);
  16643. }
  16644. }
  16645. };
  16646. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16647. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16648. if (this.blocks) {
  16649. for (var index = 0; index < this.blocks.length; index++) {
  16650. var block = this.blocks[index];
  16651. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16652. }
  16653. return;
  16654. }
  16655. if (allowDuplicate) {
  16656. selection.concat(this.entries);
  16657. }
  16658. else {
  16659. selection.concatWithNoDuplicate(this.entries);
  16660. }
  16661. }
  16662. };
  16663. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16664. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16665. if (this.blocks) {
  16666. for (var index = 0; index < this.blocks.length; index++) {
  16667. var block = this.blocks[index];
  16668. block.intersectsRay(ray, selection);
  16669. }
  16670. return;
  16671. }
  16672. selection.concatWithNoDuplicate(this.entries);
  16673. }
  16674. };
  16675. OctreeBlock.prototype.createInnerBlocks = function () {
  16676. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16677. };
  16678. return OctreeBlock;
  16679. })();
  16680. BABYLON.OctreeBlock = OctreeBlock;
  16681. })(BABYLON || (BABYLON = {}));
  16682. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16683. (function (BABYLON) {
  16684. var Bone = (function () {
  16685. function Bone(name, skeleton, parentBone, matrix) {
  16686. this.name = name;
  16687. this.children = new Array();
  16688. this.animations = new Array();
  16689. this._worldTransform = new BABYLON.Matrix();
  16690. this._absoluteTransform = new BABYLON.Matrix();
  16691. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16692. this._skeleton = skeleton;
  16693. this._matrix = matrix;
  16694. this._baseMatrix = matrix;
  16695. skeleton.bones.push(this);
  16696. if (parentBone) {
  16697. this._parent = parentBone;
  16698. parentBone.children.push(this);
  16699. }
  16700. else {
  16701. this._parent = null;
  16702. }
  16703. this._updateDifferenceMatrix();
  16704. }
  16705. // Members
  16706. Bone.prototype.getParent = function () {
  16707. return this._parent;
  16708. };
  16709. Bone.prototype.getLocalMatrix = function () {
  16710. return this._matrix;
  16711. };
  16712. Bone.prototype.getBaseMatrix = function () {
  16713. return this._baseMatrix;
  16714. };
  16715. Bone.prototype.getWorldMatrix = function () {
  16716. return this._worldTransform;
  16717. };
  16718. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16719. return this._invertedAbsoluteTransform;
  16720. };
  16721. Bone.prototype.getAbsoluteMatrix = function () {
  16722. var matrix = this._matrix.clone();
  16723. var parent = this._parent;
  16724. while (parent) {
  16725. matrix = matrix.multiply(parent.getLocalMatrix());
  16726. parent = parent.getParent();
  16727. }
  16728. return matrix;
  16729. };
  16730. // Methods
  16731. Bone.prototype.updateMatrix = function (matrix) {
  16732. this._matrix = matrix;
  16733. this._skeleton._markAsDirty();
  16734. this._updateDifferenceMatrix();
  16735. };
  16736. Bone.prototype._updateDifferenceMatrix = function () {
  16737. if (this._parent) {
  16738. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16739. }
  16740. else {
  16741. this._absoluteTransform.copyFrom(this._matrix);
  16742. }
  16743. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16744. for (var index = 0; index < this.children.length; index++) {
  16745. this.children[index]._updateDifferenceMatrix();
  16746. }
  16747. };
  16748. Bone.prototype.markAsDirty = function () {
  16749. this._skeleton._markAsDirty();
  16750. };
  16751. return Bone;
  16752. })();
  16753. BABYLON.Bone = Bone;
  16754. })(BABYLON || (BABYLON = {}));
  16755. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16756. (function (BABYLON) {
  16757. var Skeleton = (function () {
  16758. function Skeleton(name, id, scene) {
  16759. this.name = name;
  16760. this.id = id;
  16761. this.bones = new Array();
  16762. this._isDirty = true;
  16763. this._identity = BABYLON.Matrix.Identity();
  16764. this.bones = [];
  16765. this._scene = scene;
  16766. scene.skeletons.push(this);
  16767. }
  16768. // Members
  16769. Skeleton.prototype.getTransformMatrices = function () {
  16770. return this._transformMatrices;
  16771. };
  16772. // Methods
  16773. Skeleton.prototype._markAsDirty = function () {
  16774. this._isDirty = true;
  16775. };
  16776. Skeleton.prototype.prepare = function () {
  16777. if (!this._isDirty) {
  16778. return;
  16779. }
  16780. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16781. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16782. }
  16783. for (var index = 0; index < this.bones.length; index++) {
  16784. var bone = this.bones[index];
  16785. var parentBone = bone.getParent();
  16786. if (parentBone) {
  16787. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16788. }
  16789. else {
  16790. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16791. }
  16792. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16793. }
  16794. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16795. this._isDirty = false;
  16796. this._scene._activeBones += this.bones.length;
  16797. };
  16798. Skeleton.prototype.getAnimatables = function () {
  16799. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16800. this._animatables = [];
  16801. for (var index = 0; index < this.bones.length; index++) {
  16802. this._animatables.push(this.bones[index]);
  16803. }
  16804. }
  16805. return this._animatables;
  16806. };
  16807. Skeleton.prototype.clone = function (name, id) {
  16808. var result = new Skeleton(name, id || name, this._scene);
  16809. for (var index = 0; index < this.bones.length; index++) {
  16810. var source = this.bones[index];
  16811. var parentBone = null;
  16812. if (source.getParent()) {
  16813. var parentIndex = this.bones.indexOf(source.getParent());
  16814. parentBone = result.bones[parentIndex];
  16815. }
  16816. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16817. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16818. }
  16819. return result;
  16820. };
  16821. return Skeleton;
  16822. })();
  16823. BABYLON.Skeleton = Skeleton;
  16824. })(BABYLON || (BABYLON = {}));
  16825. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16826. (function (BABYLON) {
  16827. var PostProcess = (function () {
  16828. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  16830. this.name = name;
  16831. this.width = -1;
  16832. this.height = -1;
  16833. this._reusable = false;
  16834. this._textures = new BABYLON.SmartArray(2);
  16835. this._currentRenderTextureInd = 0;
  16836. if (camera != null) {
  16837. this._camera = camera;
  16838. this._scene = camera.getScene();
  16839. camera.attachPostProcess(this);
  16840. this._engine = this._scene.getEngine();
  16841. }
  16842. else {
  16843. this._engine = engine;
  16844. }
  16845. this._renderRatio = ratio;
  16846. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16847. this._reusable = reusable || false;
  16848. samplers = samplers || [];
  16849. samplers.push("textureSampler");
  16850. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16851. }
  16852. PostProcess.prototype.isReusable = function () {
  16853. return this._reusable;
  16854. };
  16855. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16856. camera = camera || this._camera;
  16857. var scene = camera.getScene();
  16858. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16859. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16860. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16861. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16862. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16863. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16864. if (this._textures.length > 0) {
  16865. for (var i = 0; i < this._textures.length; i++) {
  16866. this._engine._releaseTexture(this._textures.data[i]);
  16867. }
  16868. this._textures.reset();
  16869. }
  16870. this.width = desiredWidth;
  16871. this.height = desiredHeight;
  16872. 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 }));
  16873. if (this._reusable) {
  16874. 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 }));
  16875. }
  16876. if (this.onSizeChanged) {
  16877. this.onSizeChanged();
  16878. }
  16879. }
  16880. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16881. if (this.onActivate) {
  16882. this.onActivate(camera);
  16883. }
  16884. // Clear
  16885. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16886. if (this._reusable) {
  16887. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16888. }
  16889. };
  16890. PostProcess.prototype.apply = function () {
  16891. // Check
  16892. if (!this._effect.isReady())
  16893. return null;
  16894. // States
  16895. this._engine.enableEffect(this._effect);
  16896. this._engine.setState(false);
  16897. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16898. this._engine.setDepthBuffer(false);
  16899. this._engine.setDepthWrite(false);
  16900. // Texture
  16901. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16902. // Parameters
  16903. if (this.onApply) {
  16904. this.onApply(this._effect);
  16905. }
  16906. return this._effect;
  16907. };
  16908. PostProcess.prototype.dispose = function (camera) {
  16909. camera = camera || this._camera;
  16910. if (this._textures.length > 0) {
  16911. for (var i = 0; i < this._textures.length; i++) {
  16912. this._engine._releaseTexture(this._textures.data[i]);
  16913. }
  16914. this._textures.reset();
  16915. }
  16916. if (!camera) {
  16917. return;
  16918. }
  16919. camera.detachPostProcess(this);
  16920. var index = camera._postProcesses.indexOf(this);
  16921. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16922. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16923. }
  16924. };
  16925. return PostProcess;
  16926. })();
  16927. BABYLON.PostProcess = PostProcess;
  16928. })(BABYLON || (BABYLON = {}));
  16929. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16930. (function (BABYLON) {
  16931. var PostProcessManager = (function () {
  16932. function PostProcessManager(scene) {
  16933. this._vertexDeclaration = [2];
  16934. this._vertexStrideSize = 2 * 4;
  16935. this._scene = scene;
  16936. // VBO
  16937. var vertices = [];
  16938. vertices.push(1, 1);
  16939. vertices.push(-1, 1);
  16940. vertices.push(-1, -1);
  16941. vertices.push(1, -1);
  16942. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16943. // Indices
  16944. var indices = [];
  16945. indices.push(0);
  16946. indices.push(1);
  16947. indices.push(2);
  16948. indices.push(0);
  16949. indices.push(2);
  16950. indices.push(3);
  16951. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16952. }
  16953. // Methods
  16954. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16955. var postProcesses = this._scene.activeCamera._postProcesses;
  16956. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16957. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16958. return false;
  16959. }
  16960. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16961. return true;
  16962. };
  16963. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  16964. var engine = this._scene.getEngine();
  16965. for (var index = 0; index < postProcesses.length; index++) {
  16966. if (index < postProcesses.length - 1) {
  16967. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  16968. }
  16969. else {
  16970. if (targetTexture) {
  16971. engine.bindFramebuffer(targetTexture);
  16972. }
  16973. else {
  16974. engine.restoreDefaultFramebuffer();
  16975. }
  16976. }
  16977. var pp = postProcesses[index];
  16978. var effect = pp.apply();
  16979. if (effect) {
  16980. if (pp.onBeforeRender) {
  16981. pp.onBeforeRender(effect);
  16982. }
  16983. // VBOs
  16984. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16985. // Draw order
  16986. engine.draw(true, 0, 6);
  16987. }
  16988. }
  16989. // Restore depth buffer
  16990. engine.setDepthBuffer(true);
  16991. engine.setDepthWrite(true);
  16992. };
  16993. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, postProcesses) {
  16994. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  16995. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16996. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16997. return;
  16998. }
  16999. var engine = this._scene.getEngine();
  17000. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  17001. if (index < postProcessesTakenIndices.length - 1) {
  17002. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  17003. }
  17004. else {
  17005. if (targetTexture) {
  17006. engine.bindFramebuffer(targetTexture);
  17007. }
  17008. else {
  17009. engine.restoreDefaultFramebuffer();
  17010. }
  17011. }
  17012. if (doNotPresent) {
  17013. break;
  17014. }
  17015. var pp = postProcesses[postProcessesTakenIndices[index]];
  17016. var effect = pp.apply();
  17017. if (effect) {
  17018. if (pp.onBeforeRender) {
  17019. pp.onBeforeRender(effect);
  17020. }
  17021. // VBOs
  17022. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  17023. // Draw order
  17024. engine.draw(true, 0, 6);
  17025. }
  17026. }
  17027. // Restore depth buffer
  17028. engine.setDepthBuffer(true);
  17029. engine.setDepthWrite(true);
  17030. };
  17031. PostProcessManager.prototype.dispose = function () {
  17032. if (this._vertexBuffer) {
  17033. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17034. this._vertexBuffer = null;
  17035. }
  17036. if (this._indexBuffer) {
  17037. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17038. this._indexBuffer = null;
  17039. }
  17040. };
  17041. return PostProcessManager;
  17042. })();
  17043. BABYLON.PostProcessManager = PostProcessManager;
  17044. })(BABYLON || (BABYLON = {}));
  17045. //# sourceMappingURL=babylon.postProcessManager.js.map
  17046. var BABYLON;
  17047. (function (BABYLON) {
  17048. var PassPostProcess = (function (_super) {
  17049. __extends(PassPostProcess, _super);
  17050. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17051. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  17052. }
  17053. return PassPostProcess;
  17054. })(BABYLON.PostProcess);
  17055. BABYLON.PassPostProcess = PassPostProcess;
  17056. })(BABYLON || (BABYLON = {}));
  17057. //# sourceMappingURL=babylon.passPostProcess.js.map
  17058. var BABYLON;
  17059. (function (BABYLON) {
  17060. var BlurPostProcess = (function (_super) {
  17061. __extends(BlurPostProcess, _super);
  17062. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  17063. var _this = this;
  17064. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  17065. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  17066. this.direction = direction;
  17067. this.blurWidth = blurWidth;
  17068. this.onApply = function (effect) {
  17069. effect.setFloat2("screenSize", _this.width, _this.height);
  17070. effect.setVector2("direction", _this.direction);
  17071. effect.setFloat("blurWidth", _this.blurWidth);
  17072. };
  17073. }
  17074. return BlurPostProcess;
  17075. })(BABYLON.PostProcess);
  17076. BABYLON.BlurPostProcess = BlurPostProcess;
  17077. })(BABYLON || (BABYLON = {}));
  17078. //# sourceMappingURL=babylon.blurPostProcess.js.map
  17079. var BABYLON;
  17080. (function (BABYLON) {
  17081. var FilterPostProcess = (function (_super) {
  17082. __extends(FilterPostProcess, _super);
  17083. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  17084. var _this = this;
  17085. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  17086. this.kernelMatrix = kernelMatrix;
  17087. this.onApply = function (effect) {
  17088. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  17089. };
  17090. }
  17091. return FilterPostProcess;
  17092. })(BABYLON.PostProcess);
  17093. BABYLON.FilterPostProcess = FilterPostProcess;
  17094. })(BABYLON || (BABYLON = {}));
  17095. //# sourceMappingURL=babylon.filterPostProcess.js.map
  17096. var BABYLON;
  17097. (function (BABYLON) {
  17098. var RefractionPostProcess = (function (_super) {
  17099. __extends(RefractionPostProcess, _super);
  17100. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  17101. var _this = this;
  17102. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  17103. this.color = color;
  17104. this.depth = depth;
  17105. this.colorLevel = colorLevel;
  17106. this.onActivate = function (cam) {
  17107. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  17108. };
  17109. this.onApply = function (effect) {
  17110. effect.setColor3("baseColor", _this.color);
  17111. effect.setFloat("depth", _this.depth);
  17112. effect.setFloat("colorLevel", _this.colorLevel);
  17113. effect.setTexture("refractionSampler", _this._refRexture);
  17114. };
  17115. }
  17116. // Methods
  17117. RefractionPostProcess.prototype.dispose = function (camera) {
  17118. if (this._refRexture) {
  17119. this._refRexture.dispose();
  17120. }
  17121. _super.prototype.dispose.call(this, camera);
  17122. };
  17123. return RefractionPostProcess;
  17124. })(BABYLON.PostProcess);
  17125. BABYLON.RefractionPostProcess = RefractionPostProcess;
  17126. })(BABYLON || (BABYLON = {}));
  17127. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  17128. var BABYLON;
  17129. (function (BABYLON) {
  17130. var BlackAndWhitePostProcess = (function (_super) {
  17131. __extends(BlackAndWhitePostProcess, _super);
  17132. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17133. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  17134. }
  17135. return BlackAndWhitePostProcess;
  17136. })(BABYLON.PostProcess);
  17137. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  17138. })(BABYLON || (BABYLON = {}));
  17139. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  17140. var BABYLON;
  17141. (function (BABYLON) {
  17142. var ConvolutionPostProcess = (function (_super) {
  17143. __extends(ConvolutionPostProcess, _super);
  17144. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  17145. var _this = this;
  17146. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  17147. this.kernel = kernel;
  17148. this.onApply = function (effect) {
  17149. effect.setFloat2("screenSize", _this.width, _this.height);
  17150. effect.setArray("kernel", _this.kernel);
  17151. };
  17152. }
  17153. // Statics
  17154. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  17155. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  17156. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  17157. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  17158. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  17159. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  17160. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  17161. return ConvolutionPostProcess;
  17162. })(BABYLON.PostProcess);
  17163. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  17164. })(BABYLON || (BABYLON = {}));
  17165. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  17166. var BABYLON;
  17167. (function (BABYLON) {
  17168. var FxaaPostProcess = (function (_super) {
  17169. __extends(FxaaPostProcess, _super);
  17170. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  17171. var _this = this;
  17172. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  17173. this.onSizeChanged = function () {
  17174. _this.texelWidth = 1.0 / _this.width;
  17175. _this.texelHeight = 1.0 / _this.height;
  17176. };
  17177. this.onApply = function (effect) {
  17178. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  17179. };
  17180. }
  17181. return FxaaPostProcess;
  17182. })(BABYLON.PostProcess);
  17183. BABYLON.FxaaPostProcess = FxaaPostProcess;
  17184. })(BABYLON || (BABYLON = {}));
  17185. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  17186. (function (BABYLON) {
  17187. var LensFlare = (function () {
  17188. function LensFlare(size, position, color, imgUrl, system) {
  17189. this.size = size;
  17190. this.position = position;
  17191. this.dispose = function () {
  17192. if (this.texture) {
  17193. this.texture.dispose();
  17194. }
  17195. // Remove from scene
  17196. var index = this._system.lensFlares.indexOf(this);
  17197. this._system.lensFlares.splice(index, 1);
  17198. };
  17199. this.color = color || new BABYLON.Color3(1, 1, 1);
  17200. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17201. this._system = system;
  17202. system.lensFlares.push(this);
  17203. }
  17204. return LensFlare;
  17205. })();
  17206. BABYLON.LensFlare = LensFlare;
  17207. })(BABYLON || (BABYLON = {}));
  17208. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17209. (function (BABYLON) {
  17210. var LensFlareSystem = (function () {
  17211. function LensFlareSystem(name, emitter, scene) {
  17212. this.name = name;
  17213. this.lensFlares = new Array();
  17214. this.borderLimit = 300;
  17215. this._vertexDeclaration = [2];
  17216. this._vertexStrideSize = 2 * 4;
  17217. this._isEnabled = true;
  17218. this._scene = scene;
  17219. this._emitter = emitter;
  17220. scene.lensFlareSystems.push(this);
  17221. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17222. // VBO
  17223. var vertices = [];
  17224. vertices.push(1, 1);
  17225. vertices.push(-1, 1);
  17226. vertices.push(-1, -1);
  17227. vertices.push(1, -1);
  17228. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17229. // Indices
  17230. var indices = [];
  17231. indices.push(0);
  17232. indices.push(1);
  17233. indices.push(2);
  17234. indices.push(0);
  17235. indices.push(2);
  17236. indices.push(3);
  17237. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17238. // Effects
  17239. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17240. }
  17241. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17242. get: function () {
  17243. return this._isEnabled;
  17244. },
  17245. set: function (value) {
  17246. this._isEnabled = value;
  17247. },
  17248. enumerable: true,
  17249. configurable: true
  17250. });
  17251. LensFlareSystem.prototype.getScene = function () {
  17252. return this._scene;
  17253. };
  17254. LensFlareSystem.prototype.getEmitter = function () {
  17255. return this._emitter;
  17256. };
  17257. LensFlareSystem.prototype.getEmitterPosition = function () {
  17258. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17259. };
  17260. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17261. var position = this.getEmitterPosition();
  17262. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17263. this._positionX = position.x;
  17264. this._positionY = position.y;
  17265. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17266. if (position.z > 0) {
  17267. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17268. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17269. return true;
  17270. }
  17271. }
  17272. return false;
  17273. };
  17274. LensFlareSystem.prototype._isVisible = function () {
  17275. if (!this._isEnabled) {
  17276. return false;
  17277. }
  17278. var emitterPosition = this.getEmitterPosition();
  17279. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17280. var distance = direction.length();
  17281. direction.normalize();
  17282. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17283. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17284. return !pickInfo.hit || pickInfo.distance > distance;
  17285. };
  17286. LensFlareSystem.prototype.render = function () {
  17287. if (!this._effect.isReady())
  17288. return false;
  17289. var engine = this._scene.getEngine();
  17290. var viewport = this._scene.activeCamera.viewport;
  17291. var globalViewport = viewport.toGlobal(engine);
  17292. // Position
  17293. if (!this.computeEffectivePosition(globalViewport)) {
  17294. return false;
  17295. }
  17296. // Visibility
  17297. if (!this._isVisible()) {
  17298. return false;
  17299. }
  17300. // Intensity
  17301. var awayX;
  17302. var awayY;
  17303. if (this._positionX < this.borderLimit + globalViewport.x) {
  17304. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17305. }
  17306. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17307. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17308. }
  17309. else {
  17310. awayX = 0;
  17311. }
  17312. if (this._positionY < this.borderLimit + globalViewport.y) {
  17313. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17314. }
  17315. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17316. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17317. }
  17318. else {
  17319. awayY = 0;
  17320. }
  17321. var away = (awayX > awayY) ? awayX : awayY;
  17322. if (away > this.borderLimit) {
  17323. away = this.borderLimit;
  17324. }
  17325. var intensity = 1.0 - (away / this.borderLimit);
  17326. if (intensity < 0) {
  17327. return false;
  17328. }
  17329. if (intensity > 1.0) {
  17330. intensity = 1.0;
  17331. }
  17332. // Position
  17333. var centerX = globalViewport.x + globalViewport.width / 2;
  17334. var centerY = globalViewport.y + globalViewport.height / 2;
  17335. var distX = centerX - this._positionX;
  17336. var distY = centerY - this._positionY;
  17337. // Effects
  17338. engine.enableEffect(this._effect);
  17339. engine.setState(false);
  17340. engine.setDepthBuffer(false);
  17341. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17342. // VBOs
  17343. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17344. for (var index = 0; index < this.lensFlares.length; index++) {
  17345. var flare = this.lensFlares[index];
  17346. var x = centerX - (distX * flare.position);
  17347. var y = centerY - (distY * flare.position);
  17348. var cw = flare.size;
  17349. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17350. var cx = 2 * (x / globalViewport.width) - 1.0;
  17351. var cy = 1.0 - 2 * (y / globalViewport.height);
  17352. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17353. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17354. // Texture
  17355. this._effect.setTexture("textureSampler", flare.texture);
  17356. // Color
  17357. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17358. // Draw order
  17359. engine.draw(true, 0, 6);
  17360. }
  17361. engine.setDepthBuffer(true);
  17362. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17363. return true;
  17364. };
  17365. LensFlareSystem.prototype.dispose = function () {
  17366. if (this._vertexBuffer) {
  17367. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17368. this._vertexBuffer = null;
  17369. }
  17370. if (this._indexBuffer) {
  17371. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17372. this._indexBuffer = null;
  17373. }
  17374. while (this.lensFlares.length) {
  17375. this.lensFlares[0].dispose();
  17376. }
  17377. // Remove from scene
  17378. var index = this._scene.lensFlareSystems.indexOf(this);
  17379. this._scene.lensFlareSystems.splice(index, 1);
  17380. };
  17381. return LensFlareSystem;
  17382. })();
  17383. BABYLON.LensFlareSystem = LensFlareSystem;
  17384. })(BABYLON || (BABYLON = {}));
  17385. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17386. (function (BABYLON) {
  17387. var IntersectionInfo = (function () {
  17388. function IntersectionInfo(bu, bv, distance) {
  17389. this.bu = bu;
  17390. this.bv = bv;
  17391. this.distance = distance;
  17392. this.faceId = 0;
  17393. this.subMeshId = 0;
  17394. }
  17395. return IntersectionInfo;
  17396. })();
  17397. BABYLON.IntersectionInfo = IntersectionInfo;
  17398. var PickingInfo = (function () {
  17399. function PickingInfo() {
  17400. this.hit = false;
  17401. this.distance = 0;
  17402. this.pickedPoint = null;
  17403. this.pickedMesh = null;
  17404. this.bu = 0;
  17405. this.bv = 0;
  17406. this.faceId = -1;
  17407. this.subMeshId = 0;
  17408. }
  17409. // Methods
  17410. PickingInfo.prototype.getNormal = function () {
  17411. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17412. return null;
  17413. }
  17414. var indices = this.pickedMesh.getIndices();
  17415. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17416. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17417. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17418. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17419. normal0 = normal0.scale(this.bu);
  17420. normal1 = normal1.scale(this.bv);
  17421. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17422. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17423. };
  17424. PickingInfo.prototype.getTextureCoordinates = function () {
  17425. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17426. return null;
  17427. }
  17428. var indices = this.pickedMesh.getIndices();
  17429. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17430. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17431. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17432. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17433. uv0 = uv0.scale(this.bu);
  17434. uv1 = uv1.scale(this.bv);
  17435. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17436. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17437. };
  17438. return PickingInfo;
  17439. })();
  17440. BABYLON.PickingInfo = PickingInfo;
  17441. })(BABYLON || (BABYLON = {}));
  17442. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17443. (function (BABYLON) {
  17444. var FilesInput = (function () {
  17445. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17446. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17447. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17448. this._engine = p_engine;
  17449. this._canvas = p_canvas;
  17450. this._currentScene = p_scene;
  17451. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17452. this._progressCallback = p_progressCallback;
  17453. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17454. this._textureLoadingCallback = p_textureLoadingCallback;
  17455. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17456. }
  17457. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17458. var _this = this;
  17459. if (p_elementToMonitor) {
  17460. this._elementToMonitor = p_elementToMonitor;
  17461. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17462. _this.drag(e);
  17463. }, false);
  17464. this._elementToMonitor.addEventListener("dragover", function (e) {
  17465. _this.drag(e);
  17466. }, false);
  17467. this._elementToMonitor.addEventListener("drop", function (e) {
  17468. _this.drop(e);
  17469. }, false);
  17470. }
  17471. };
  17472. FilesInput.prototype.renderFunction = function () {
  17473. if (this._additionnalRenderLoopLogicCallback) {
  17474. this._additionnalRenderLoopLogicCallback();
  17475. }
  17476. if (this._currentScene) {
  17477. if (this._textureLoadingCallback) {
  17478. var remaining = this._currentScene.getWaitingItemsCount();
  17479. if (remaining > 0) {
  17480. this._textureLoadingCallback(remaining);
  17481. }
  17482. }
  17483. this._currentScene.render();
  17484. }
  17485. };
  17486. FilesInput.prototype.drag = function (e) {
  17487. e.stopPropagation();
  17488. e.preventDefault();
  17489. };
  17490. FilesInput.prototype.drop = function (eventDrop) {
  17491. eventDrop.stopPropagation();
  17492. eventDrop.preventDefault();
  17493. this.loadFiles(eventDrop);
  17494. };
  17495. FilesInput.prototype.loadFiles = function (event) {
  17496. if (this._startingProcessingFilesCallback)
  17497. this._startingProcessingFilesCallback();
  17498. // Handling data transfer via drag'n'drop
  17499. if (event && event.dataTransfer && event.dataTransfer.files) {
  17500. this._filesToLoad = event.dataTransfer.files;
  17501. }
  17502. // Handling files from input files
  17503. if (event && event.target && event.target.files) {
  17504. this._filesToLoad = event.target.files;
  17505. }
  17506. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17507. for (var i = 0; i < this._filesToLoad.length; i++) {
  17508. switch (this._filesToLoad[i].type) {
  17509. case "image/jpeg":
  17510. case "image/png":
  17511. case "image/bmp":
  17512. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17513. break;
  17514. case "image/targa":
  17515. case "image/vnd.ms-dds":
  17516. case "audio/wav":
  17517. case "audio/x-wav":
  17518. case "audio/mp3":
  17519. case "audio/mpeg":
  17520. case "audio/mpeg3":
  17521. case "audio/x-mpeg-3":
  17522. case "audio/ogg":
  17523. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17524. break;
  17525. default:
  17526. 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) {
  17527. this._sceneFileToLoad = this._filesToLoad[i];
  17528. }
  17529. break;
  17530. }
  17531. }
  17532. this.reload();
  17533. }
  17534. };
  17535. FilesInput.prototype.reload = function () {
  17536. var _this = this;
  17537. var that = this;
  17538. // If a ".babylon" file has been provided
  17539. if (this._sceneFileToLoad) {
  17540. if (this._currentScene) {
  17541. this._engine.stopRenderLoop();
  17542. this._currentScene.dispose();
  17543. }
  17544. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17545. that._currentScene = newScene;
  17546. // Wait for textures and shaders to be ready
  17547. that._currentScene.executeWhenReady(function () {
  17548. // Attach camera to canvas inputs
  17549. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17550. that._currentScene.createDefaultCameraOrLight();
  17551. }
  17552. that._currentScene.activeCamera.attachControl(that._canvas);
  17553. if (that._sceneLoadedCallback) {
  17554. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17555. }
  17556. that._engine.runRenderLoop(function () {
  17557. that.renderFunction();
  17558. });
  17559. });
  17560. }, function (progress) {
  17561. if (_this._progressCallback) {
  17562. _this._progressCallback(progress);
  17563. }
  17564. });
  17565. }
  17566. else {
  17567. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17568. }
  17569. };
  17570. FilesInput.FilesTextures = new Array();
  17571. FilesInput.FilesToLoad = new Array();
  17572. return FilesInput;
  17573. })();
  17574. BABYLON.FilesInput = FilesInput;
  17575. })(BABYLON || (BABYLON = {}));
  17576. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17577. (function (BABYLON) {
  17578. var OimoJSPlugin = (function () {
  17579. function OimoJSPlugin() {
  17580. this._registeredMeshes = [];
  17581. /**
  17582. * Update the body position according to the mesh position
  17583. * @param mesh
  17584. */
  17585. this.updateBodyPosition = function (mesh) {
  17586. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17587. var registeredMesh = this._registeredMeshes[index];
  17588. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17589. var body = registeredMesh.body.body;
  17590. mesh.computeWorldMatrix(true);
  17591. var center = mesh.getBoundingInfo().boundingBox.center;
  17592. body.setPosition(center.x, center.y, center.z);
  17593. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17594. return;
  17595. }
  17596. // Case where the parent has been updated
  17597. if (registeredMesh.mesh.parent === mesh) {
  17598. mesh.computeWorldMatrix(true);
  17599. registeredMesh.mesh.computeWorldMatrix(true);
  17600. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17601. var absoluteRotation = mesh.rotation;
  17602. body = registeredMesh.body.body;
  17603. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17604. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17605. return;
  17606. }
  17607. }
  17608. };
  17609. }
  17610. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17611. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17612. };
  17613. OimoJSPlugin.prototype.initialize = function (iterations) {
  17614. this._world = new OIMO.World();
  17615. this._world.clear();
  17616. };
  17617. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17618. this._world.gravity = gravity;
  17619. };
  17620. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17621. var body = null;
  17622. this.unregisterMesh(mesh);
  17623. mesh.computeWorldMatrix(true);
  17624. var initialRotation = null;
  17625. if (mesh.rotationQuaternion) {
  17626. initialRotation = mesh.rotationQuaternion.clone();
  17627. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17628. mesh.computeWorldMatrix(true);
  17629. }
  17630. var bbox = mesh.getBoundingInfo().boundingBox;
  17631. // The delta between the mesh position and the mesh bounding box center
  17632. var deltaPosition = mesh.position.subtract(bbox.center);
  17633. // Transform delta position with the rotation
  17634. if (initialRotation) {
  17635. var m = new BABYLON.Matrix();
  17636. initialRotation.toRotationMatrix(m);
  17637. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17638. }
  17639. switch (impostor) {
  17640. case BABYLON.PhysicsEngine.SphereImpostor:
  17641. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17642. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17643. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17644. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17645. body = new OIMO.Body({
  17646. type: 'sphere',
  17647. size: [size],
  17648. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17649. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17650. move: options.mass != 0,
  17651. config: [options.mass, options.friction, options.restitution],
  17652. world: this._world
  17653. });
  17654. break;
  17655. case BABYLON.PhysicsEngine.PlaneImpostor:
  17656. case BABYLON.PhysicsEngine.CylinderImpostor:
  17657. case BABYLON.PhysicsEngine.BoxImpostor:
  17658. var min = bbox.minimumWorld;
  17659. var max = bbox.maximumWorld;
  17660. var box = max.subtract(min);
  17661. var sizeX = this._checkWithEpsilon(box.x);
  17662. var sizeY = this._checkWithEpsilon(box.y);
  17663. var sizeZ = this._checkWithEpsilon(box.z);
  17664. body = new OIMO.Body({
  17665. type: 'box',
  17666. size: [sizeX, sizeY, sizeZ],
  17667. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17668. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17669. move: options.mass != 0,
  17670. config: [options.mass, options.friction, options.restitution],
  17671. world: this._world
  17672. });
  17673. break;
  17674. }
  17675. //If quaternion was set as the rotation of the object
  17676. if (initialRotation) {
  17677. //We have to access the rigid body's properties to set the quaternion.
  17678. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17679. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17680. //update the internal rotation matrix
  17681. body.body.syncShapes();
  17682. }
  17683. this._registeredMeshes.push({
  17684. mesh: mesh,
  17685. body: body,
  17686. delta: deltaPosition
  17687. });
  17688. return body;
  17689. };
  17690. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17691. var types = [], sizes = [], positions = [], rotations = [];
  17692. var initialMesh = parts[0].mesh;
  17693. for (var index = 0; index < parts.length; index++) {
  17694. var part = parts[index];
  17695. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17696. types.push(bodyParameters.type);
  17697. sizes.push.apply(sizes, bodyParameters.size);
  17698. positions.push.apply(positions, bodyParameters.pos);
  17699. rotations.push.apply(rotations, bodyParameters.rot);
  17700. }
  17701. var body = new OIMO.Body({
  17702. type: types,
  17703. size: sizes,
  17704. pos: positions,
  17705. rot: rotations,
  17706. move: options.mass != 0,
  17707. config: [options.mass, options.friction, options.restitution],
  17708. world: this._world
  17709. });
  17710. this._registeredMeshes.push({
  17711. mesh: initialMesh,
  17712. body: body
  17713. });
  17714. return body;
  17715. };
  17716. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17717. var bodyParameters = null;
  17718. var mesh = part.mesh;
  17719. // We need the bounding box/sphere info to compute the physics body
  17720. mesh.computeWorldMatrix();
  17721. switch (part.impostor) {
  17722. case BABYLON.PhysicsEngine.SphereImpostor:
  17723. var bbox = mesh.getBoundingInfo().boundingBox;
  17724. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17725. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17726. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17727. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17728. bodyParameters = {
  17729. type: 'sphere',
  17730. /* bug with oimo : sphere needs 3 sizes in this case */
  17731. size: [size, -1, -1],
  17732. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17733. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17734. };
  17735. break;
  17736. case BABYLON.PhysicsEngine.PlaneImpostor:
  17737. case BABYLON.PhysicsEngine.BoxImpostor:
  17738. bbox = mesh.getBoundingInfo().boundingBox;
  17739. var min = bbox.minimumWorld;
  17740. var max = bbox.maximumWorld;
  17741. var box = max.subtract(min);
  17742. var sizeX = this._checkWithEpsilon(box.x);
  17743. var sizeY = this._checkWithEpsilon(box.y);
  17744. var sizeZ = this._checkWithEpsilon(box.z);
  17745. var relativePosition = mesh.position;
  17746. bodyParameters = {
  17747. type: 'box',
  17748. size: [sizeX, sizeY, sizeZ],
  17749. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17750. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17751. };
  17752. break;
  17753. }
  17754. return bodyParameters;
  17755. };
  17756. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17757. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17758. var registeredMesh = this._registeredMeshes[index];
  17759. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17760. if (registeredMesh.body) {
  17761. this._world.removeRigidBody(registeredMesh.body.body);
  17762. this._unbindBody(registeredMesh.body);
  17763. }
  17764. this._registeredMeshes.splice(index, 1);
  17765. return;
  17766. }
  17767. }
  17768. };
  17769. OimoJSPlugin.prototype._unbindBody = function (body) {
  17770. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17771. var registeredMesh = this._registeredMeshes[index];
  17772. if (registeredMesh.body === body) {
  17773. registeredMesh.body = null;
  17774. }
  17775. }
  17776. };
  17777. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17778. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17779. var registeredMesh = this._registeredMeshes[index];
  17780. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17781. // Get object mass to have a behaviour similar to cannon.js
  17782. var mass = registeredMesh.body.body.massInfo.mass;
  17783. // The force is scaled with the mass of object
  17784. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17785. return;
  17786. }
  17787. }
  17788. };
  17789. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17790. var body1 = null, body2 = null;
  17791. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17792. var registeredMesh = this._registeredMeshes[index];
  17793. if (registeredMesh.mesh === mesh1) {
  17794. body1 = registeredMesh.body.body;
  17795. }
  17796. else if (registeredMesh.mesh === mesh2) {
  17797. body2 = registeredMesh.body.body;
  17798. }
  17799. }
  17800. if (!body1 || !body2) {
  17801. return false;
  17802. }
  17803. if (!options) {
  17804. options = {};
  17805. }
  17806. new OIMO.Link({
  17807. type: options.type,
  17808. body1: body1,
  17809. body2: body2,
  17810. min: options.min,
  17811. max: options.max,
  17812. axe1: options.axe1,
  17813. axe2: options.axe2,
  17814. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17815. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17816. collision: options.collision,
  17817. spring: options.spring,
  17818. world: this._world
  17819. });
  17820. return true;
  17821. };
  17822. OimoJSPlugin.prototype.dispose = function () {
  17823. this._world.clear();
  17824. while (this._registeredMeshes.length) {
  17825. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17826. }
  17827. };
  17828. OimoJSPlugin.prototype.isSupported = function () {
  17829. return OIMO !== undefined;
  17830. };
  17831. OimoJSPlugin.prototype._getLastShape = function (body) {
  17832. var lastShape = body.shapes;
  17833. while (lastShape.next) {
  17834. lastShape = lastShape.next;
  17835. }
  17836. return lastShape;
  17837. };
  17838. OimoJSPlugin.prototype.runOneStep = function (time) {
  17839. this._world.step();
  17840. // Update the position of all registered meshes
  17841. var i = this._registeredMeshes.length;
  17842. var m;
  17843. while (i--) {
  17844. var body = this._registeredMeshes[i].body.body;
  17845. var mesh = this._registeredMeshes[i].mesh;
  17846. var delta = this._registeredMeshes[i].delta;
  17847. if (!body.sleeping) {
  17848. if (body.shapes.next) {
  17849. var parentShape = this._getLastShape(body);
  17850. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17851. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17852. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17853. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17854. if (!mesh.rotationQuaternion) {
  17855. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17856. }
  17857. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17858. mesh.computeWorldMatrix();
  17859. }
  17860. else {
  17861. m = body.getMatrix();
  17862. mtx = BABYLON.Matrix.FromArray(m);
  17863. // Body position
  17864. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17865. if (!delta) {
  17866. mesh.position.x = bodyX;
  17867. mesh.position.y = bodyY;
  17868. mesh.position.z = bodyZ;
  17869. }
  17870. else {
  17871. mesh.position.x = bodyX + delta.x;
  17872. mesh.position.y = bodyY + delta.y;
  17873. mesh.position.z = bodyZ + delta.z;
  17874. }
  17875. if (!mesh.rotationQuaternion) {
  17876. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17877. }
  17878. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17879. mesh.computeWorldMatrix();
  17880. }
  17881. }
  17882. }
  17883. };
  17884. return OimoJSPlugin;
  17885. })();
  17886. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17887. })(BABYLON || (BABYLON = {}));
  17888. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17889. (function (BABYLON) {
  17890. var PhysicsEngine = (function () {
  17891. function PhysicsEngine(plugin) {
  17892. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17893. }
  17894. PhysicsEngine.prototype._initialize = function (gravity) {
  17895. this._currentPlugin.initialize();
  17896. this._setGravity(gravity);
  17897. };
  17898. PhysicsEngine.prototype._runOneStep = function (delta) {
  17899. if (delta > 0.1) {
  17900. delta = 0.1;
  17901. }
  17902. else if (delta <= 0) {
  17903. delta = 1.0 / 60.0;
  17904. }
  17905. this._currentPlugin.runOneStep(delta);
  17906. };
  17907. PhysicsEngine.prototype._setGravity = function (gravity) {
  17908. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17909. this._currentPlugin.setGravity(this.gravity);
  17910. };
  17911. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17912. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17913. };
  17914. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17915. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17916. };
  17917. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17918. this._currentPlugin.unregisterMesh(mesh);
  17919. };
  17920. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17921. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17922. };
  17923. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17924. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17925. };
  17926. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17927. this._currentPlugin.updateBodyPosition(mesh);
  17928. };
  17929. PhysicsEngine.prototype.dispose = function () {
  17930. this._currentPlugin.dispose();
  17931. };
  17932. PhysicsEngine.prototype.isSupported = function () {
  17933. return this._currentPlugin.isSupported();
  17934. };
  17935. // Statics
  17936. PhysicsEngine.NoImpostor = 0;
  17937. PhysicsEngine.SphereImpostor = 1;
  17938. PhysicsEngine.BoxImpostor = 2;
  17939. PhysicsEngine.PlaneImpostor = 3;
  17940. PhysicsEngine.MeshImpostor = 4;
  17941. PhysicsEngine.CapsuleImpostor = 5;
  17942. PhysicsEngine.ConeImpostor = 6;
  17943. PhysicsEngine.CylinderImpostor = 7;
  17944. PhysicsEngine.ConvexHullImpostor = 8;
  17945. PhysicsEngine.Epsilon = 0.001;
  17946. return PhysicsEngine;
  17947. })();
  17948. BABYLON.PhysicsEngine = PhysicsEngine;
  17949. })(BABYLON || (BABYLON = {}));
  17950. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17951. (function (BABYLON) {
  17952. var serializeLight = function (light) {
  17953. var serializationObject = {};
  17954. serializationObject.name = light.name;
  17955. serializationObject.id = light.id;
  17956. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17957. if (light instanceof BABYLON.PointLight) {
  17958. serializationObject.type = 0;
  17959. serializationObject.position = light.position.asArray();
  17960. }
  17961. else if (light instanceof BABYLON.DirectionalLight) {
  17962. serializationObject.type = 1;
  17963. var directionalLight = light;
  17964. serializationObject.position = directionalLight.position.asArray();
  17965. serializationObject.direction = directionalLight.direction.asArray();
  17966. }
  17967. else if (light instanceof BABYLON.SpotLight) {
  17968. serializationObject.type = 2;
  17969. var spotLight = light;
  17970. serializationObject.position = spotLight.position.asArray();
  17971. serializationObject.direction = spotLight.position.asArray();
  17972. serializationObject.angle = spotLight.angle;
  17973. serializationObject.exponent = spotLight.exponent;
  17974. }
  17975. else if (light instanceof BABYLON.HemisphericLight) {
  17976. serializationObject.type = 3;
  17977. var hemisphericLight = light;
  17978. serializationObject.direction = hemisphericLight.direction.asArray();
  17979. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17980. }
  17981. if (light.intensity) {
  17982. serializationObject.intensity = light.intensity;
  17983. }
  17984. serializationObject.range = light.range;
  17985. serializationObject.diffuse = light.diffuse.asArray();
  17986. serializationObject.specular = light.specular.asArray();
  17987. return serializationObject;
  17988. };
  17989. var serializeFresnelParameter = function (fresnelParameter) {
  17990. var serializationObject = {};
  17991. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17992. serializationObject.leftColor = fresnelParameter.leftColor;
  17993. serializationObject.rightColor = fresnelParameter.rightColor;
  17994. serializationObject.bias = fresnelParameter.bias;
  17995. serializationObject.power = fresnelParameter.power;
  17996. return serializationObject;
  17997. };
  17998. var serializeCamera = function (camera) {
  17999. var serializationObject = {};
  18000. serializationObject.name = camera.name;
  18001. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  18002. serializationObject.id = camera.id;
  18003. serializationObject.position = camera.position.asArray();
  18004. // Parent
  18005. if (camera.parent) {
  18006. serializationObject.parentId = camera.parent.id;
  18007. }
  18008. serializationObject.fov = camera.fov;
  18009. serializationObject.minZ = camera.minZ;
  18010. serializationObject.maxZ = camera.maxZ;
  18011. serializationObject.inertia = camera.inertia;
  18012. //setting the type
  18013. if (camera instanceof BABYLON.FreeCamera) {
  18014. serializationObject.type = "FreeCamera";
  18015. }
  18016. else if (camera instanceof BABYLON.ArcRotateCamera) {
  18017. serializationObject.type = "ArcRotateCamera";
  18018. }
  18019. else if (camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18020. serializationObject.type = "AnaglyphArcRotateCamera";
  18021. }
  18022. else if (camera instanceof BABYLON.GamepadCamera) {
  18023. serializationObject.type = "GamepadCamera";
  18024. }
  18025. else if (camera instanceof BABYLON.AnaglyphFreeCamera) {
  18026. serializationObject.type = "AnaglyphFreeCamera";
  18027. }
  18028. else if (camera instanceof BABYLON.DeviceOrientationCamera) {
  18029. serializationObject.type = "DeviceOrientationCamera";
  18030. }
  18031. else if (camera instanceof BABYLON.FollowCamera) {
  18032. serializationObject.type = "FollowCamera";
  18033. }
  18034. else if (camera instanceof BABYLON.OculusCamera) {
  18035. serializationObject.type = "OculusCamera";
  18036. }
  18037. else if (camera instanceof BABYLON.OculusGamepadCamera) {
  18038. serializationObject.type = "OculusGamepadCamera";
  18039. }
  18040. else if (camera instanceof BABYLON.TouchCamera) {
  18041. serializationObject.type = "TouchCamera";
  18042. }
  18043. else if (camera instanceof BABYLON.VirtualJoysticksCamera) {
  18044. serializationObject.type = "VirtualJoysticksCamera";
  18045. }
  18046. else if (camera instanceof BABYLON.WebVRCamera) {
  18047. serializationObject.type = "WebVRCamera";
  18048. }
  18049. else if (camera instanceof BABYLON.VRDeviceOrientationCamera) {
  18050. serializationObject.type = "VRDeviceOrientationCamera";
  18051. }
  18052. //special properties of specific cameras
  18053. if (camera instanceof BABYLON.ArcRotateCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18054. var arcCamera = camera;
  18055. serializationObject.alpha = arcCamera.alpha;
  18056. serializationObject.beta = arcCamera.beta;
  18057. serializationObject.radius = arcCamera.radius;
  18058. }
  18059. else if (camera instanceof BABYLON.FollowCamera) {
  18060. var followCam = camera;
  18061. serializationObject.radius = followCam.radius;
  18062. serializationObject.heightOffset = followCam.heightOffset;
  18063. serializationObject.rotationOffset = followCam.rotationOffset;
  18064. }
  18065. else if (camera instanceof BABYLON.AnaglyphFreeCamera || camera instanceof BABYLON.AnaglyphArcRotateCamera) {
  18066. //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.
  18067. if (camera['_eyeSpace'] !== undefined) {
  18068. serializationObject.eye_space = BABYLON.Tools.ToDegrees(camera['_eyeSpace']);
  18069. }
  18070. }
  18071. //general properties that not all cameras have. The [] is due to typescript's type safety
  18072. if (camera['speed'] !== undefined) {
  18073. serializationObject.speed = camera['speed'];
  18074. }
  18075. // Target
  18076. if (camera['rotation'] && camera['rotation'] instanceof BABYLON.Vector3) {
  18077. serializationObject.rotation = camera['rotation'].asArray();
  18078. }
  18079. // Locked target
  18080. if (camera['lockedTarget'] && camera['lockedTarget'].id) {
  18081. serializationObject.lockedTargetId = camera['lockedTarget'].id;
  18082. }
  18083. if (camera['checkCollisions'] !== undefined) {
  18084. serializationObject.checkCollisions = camera['checkCollisions'];
  18085. }
  18086. if (camera['applyGravity'] !== undefined) {
  18087. serializationObject.applyGravity = camera['applyGravity'];
  18088. }
  18089. if (camera['ellipsoid']) {
  18090. serializationObject.ellipsoid = camera['ellipsoid'].asArray();
  18091. }
  18092. // Animations
  18093. appendAnimations(camera, serializationObject);
  18094. // Layer mask
  18095. serializationObject.layerMask = camera.layerMask;
  18096. return serializationObject;
  18097. };
  18098. var appendAnimations = function (source, destination) {
  18099. if (source.animations) {
  18100. destination.animations = [];
  18101. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  18102. var animation = source.animations[animationIndex];
  18103. destination.animations.push(serializeAnimation(animation));
  18104. }
  18105. }
  18106. };
  18107. var serializeAnimation = function (animation) {
  18108. var serializationObject = {};
  18109. serializationObject.name = animation.name;
  18110. serializationObject.property = animation.targetProperty;
  18111. serializationObject.framePerSecond = animation.framePerSecond;
  18112. serializationObject.dataType = animation.dataType;
  18113. serializationObject.loopBehavior = animation.loopMode;
  18114. var dataType = animation.dataType;
  18115. serializationObject.keys = [];
  18116. var keys = animation.getKeys();
  18117. for (var index = 0; index < keys.length; index++) {
  18118. var animationKey = keys[index];
  18119. var key = {};
  18120. key.frame = animationKey.frame;
  18121. switch (dataType) {
  18122. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18123. key.values = [animationKey.value];
  18124. break;
  18125. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18126. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18127. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18128. key.values = animationKey.value.asArray();
  18129. break;
  18130. }
  18131. serializationObject.keys.push(key);
  18132. }
  18133. return serializationObject;
  18134. };
  18135. var serializeMultiMaterial = function (material) {
  18136. var serializationObject = {};
  18137. serializationObject.name = material.name;
  18138. serializationObject.id = material.id;
  18139. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18140. serializationObject.materials = [];
  18141. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  18142. var subMat = material.subMaterials[matIndex];
  18143. if (subMat) {
  18144. serializationObject.materials.push(subMat.id);
  18145. }
  18146. else {
  18147. serializationObject.materials.push(null);
  18148. }
  18149. }
  18150. return serializationObject;
  18151. };
  18152. var serializeMaterial = function (material) {
  18153. var serializationObject = {};
  18154. serializationObject.name = material.name;
  18155. serializationObject.ambient = material.ambientColor.asArray();
  18156. serializationObject.diffuse = material.diffuseColor.asArray();
  18157. serializationObject.specular = material.specularColor.asArray();
  18158. serializationObject.specularPower = material.specularPower;
  18159. serializationObject.emissive = material.emissiveColor.asArray();
  18160. serializationObject.alpha = material.alpha;
  18161. serializationObject.id = material.id;
  18162. serializationObject.tags = BABYLON.Tags.GetTags(material);
  18163. serializationObject.backFaceCulling = material.backFaceCulling;
  18164. if (material.diffuseTexture) {
  18165. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  18166. }
  18167. if (material.diffuseFresnelParameters) {
  18168. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  18169. }
  18170. if (material.ambientTexture) {
  18171. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  18172. }
  18173. if (material.opacityTexture) {
  18174. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  18175. }
  18176. if (material.opacityFresnelParameters) {
  18177. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  18178. }
  18179. if (material.reflectionTexture) {
  18180. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  18181. }
  18182. if (material.reflectionFresnelParameters) {
  18183. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  18184. }
  18185. if (material.emissiveTexture) {
  18186. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  18187. }
  18188. if (material.emissiveFresnelParameters) {
  18189. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  18190. }
  18191. if (material.specularTexture) {
  18192. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  18193. }
  18194. if (material.bumpTexture) {
  18195. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  18196. }
  18197. return serializationObject;
  18198. };
  18199. var serializeTexture = function (texture) {
  18200. var serializationObject = {};
  18201. if (!texture.name) {
  18202. return null;
  18203. }
  18204. if (texture instanceof BABYLON.CubeTexture) {
  18205. serializationObject.name = texture.name;
  18206. serializationObject.hasAlpha = texture.hasAlpha;
  18207. serializationObject.level = texture.level;
  18208. serializationObject.coordinatesMode = texture.coordinatesMode;
  18209. return serializationObject;
  18210. }
  18211. if (texture instanceof BABYLON.MirrorTexture) {
  18212. var mirrorTexture = texture;
  18213. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  18214. serializationObject.renderList = [];
  18215. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  18216. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  18217. }
  18218. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  18219. }
  18220. else if (texture instanceof BABYLON.RenderTargetTexture) {
  18221. var renderTargetTexture = texture;
  18222. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  18223. serializationObject.renderList = [];
  18224. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  18225. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  18226. }
  18227. }
  18228. var regularTexture = texture;
  18229. serializationObject.name = texture.name;
  18230. serializationObject.hasAlpha = texture.hasAlpha;
  18231. serializationObject.level = texture.level;
  18232. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  18233. serializationObject.coordinatesMode = texture.coordinatesMode;
  18234. serializationObject.uOffset = regularTexture.uOffset;
  18235. serializationObject.vOffset = regularTexture.vOffset;
  18236. serializationObject.uScale = regularTexture.uScale;
  18237. serializationObject.vScale = regularTexture.vScale;
  18238. serializationObject.uAng = regularTexture.uAng;
  18239. serializationObject.vAng = regularTexture.vAng;
  18240. serializationObject.wAng = regularTexture.wAng;
  18241. serializationObject.wrapU = texture.wrapU;
  18242. serializationObject.wrapV = texture.wrapV;
  18243. // Animations
  18244. appendAnimations(texture, serializationObject);
  18245. return serializationObject;
  18246. };
  18247. var serializeSkeleton = function (skeleton) {
  18248. var serializationObject = {};
  18249. serializationObject.name = skeleton.name;
  18250. serializationObject.id = skeleton.id;
  18251. serializationObject.bones = [];
  18252. for (var index = 0; index < skeleton.bones.length; index++) {
  18253. var bone = skeleton.bones[index];
  18254. var serializedBone = {
  18255. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  18256. name: bone.name,
  18257. matrix: bone.getLocalMatrix().toArray()
  18258. };
  18259. serializationObject.bones.push(serializedBone);
  18260. if (bone.animations && bone.animations.length > 0) {
  18261. serializedBone.animation = serializeAnimation(bone.animations[0]);
  18262. }
  18263. }
  18264. return serializationObject;
  18265. };
  18266. var serializeParticleSystem = function (particleSystem) {
  18267. var serializationObject = {};
  18268. serializationObject.emitterId = particleSystem.emitter.id;
  18269. serializationObject.capacity = particleSystem.getCapacity();
  18270. if (particleSystem.particleTexture) {
  18271. serializationObject.textureName = particleSystem.particleTexture.name;
  18272. }
  18273. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18274. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18275. serializationObject.minSize = particleSystem.minSize;
  18276. serializationObject.maxSize = particleSystem.maxSize;
  18277. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18278. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18279. serializationObject.emitRate = particleSystem.emitRate;
  18280. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18281. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18282. serializationObject.gravity = particleSystem.gravity.asArray();
  18283. serializationObject.direction1 = particleSystem.direction1.asArray();
  18284. serializationObject.direction2 = particleSystem.direction2.asArray();
  18285. serializationObject.color1 = particleSystem.color1.asArray();
  18286. serializationObject.color2 = particleSystem.color2.asArray();
  18287. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18288. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18289. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18290. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18291. serializationObject.blendMode = particleSystem.blendMode;
  18292. return serializationObject;
  18293. };
  18294. var serializeLensFlareSystem = function (lensFlareSystem) {
  18295. var serializationObject = {};
  18296. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18297. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18298. serializationObject.flares = [];
  18299. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18300. var flare = lensFlareSystem.lensFlares[index];
  18301. serializationObject.flares.push({
  18302. size: flare.size,
  18303. position: flare.position,
  18304. color: flare.color.asArray(),
  18305. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18306. });
  18307. }
  18308. return serializationObject;
  18309. };
  18310. var serializeShadowGenerator = function (light) {
  18311. var serializationObject = {};
  18312. var shadowGenerator = light.getShadowGenerator();
  18313. serializationObject.lightId = light.id;
  18314. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18315. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18316. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18317. serializationObject.renderList = [];
  18318. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18319. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18320. serializationObject.renderList.push(mesh.id);
  18321. }
  18322. return serializationObject;
  18323. };
  18324. var serializedGeometries = [];
  18325. var serializeGeometry = function (geometry, serializationGeometries) {
  18326. if (serializedGeometries[geometry.id]) {
  18327. return;
  18328. }
  18329. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18330. serializationGeometries.boxes.push(serializeBox(geometry));
  18331. }
  18332. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18333. serializationGeometries.spheres.push(serializeSphere(geometry));
  18334. }
  18335. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18336. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18337. }
  18338. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18339. serializationGeometries.toruses.push(serializeTorus(geometry));
  18340. }
  18341. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18342. serializationGeometries.grounds.push(serializeGround(geometry));
  18343. }
  18344. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18345. serializationGeometries.planes.push(serializePlane(geometry));
  18346. }
  18347. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18348. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18349. }
  18350. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18351. throw new Error("Unknow primitive type");
  18352. }
  18353. else {
  18354. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18355. }
  18356. serializedGeometries[geometry.id] = true;
  18357. };
  18358. var serializeGeometryBase = function (geometry) {
  18359. var serializationObject = {};
  18360. serializationObject.id = geometry.id;
  18361. if (BABYLON.Tags.HasTags(geometry)) {
  18362. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18363. }
  18364. return serializationObject;
  18365. };
  18366. var serializeVertexData = function (vertexData) {
  18367. var serializationObject = serializeGeometryBase(vertexData);
  18368. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18369. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18370. }
  18371. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18372. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18373. }
  18374. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18375. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18376. }
  18377. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18378. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18379. }
  18380. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18381. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18382. }
  18383. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18384. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18385. serializationObject.matricesIndices._isExpanded = true;
  18386. }
  18387. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18388. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18389. }
  18390. serializationObject.indices = vertexData.getIndices();
  18391. return serializationObject;
  18392. };
  18393. var serializePrimitive = function (primitive) {
  18394. var serializationObject = serializeGeometryBase(primitive);
  18395. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18396. return serializationObject;
  18397. };
  18398. var serializeBox = function (box) {
  18399. var serializationObject = serializePrimitive(box);
  18400. serializationObject.size = box.size;
  18401. return serializationObject;
  18402. };
  18403. var serializeSphere = function (sphere) {
  18404. var serializationObject = serializePrimitive(sphere);
  18405. serializationObject.segments = sphere.segments;
  18406. serializationObject.diameter = sphere.diameter;
  18407. return serializationObject;
  18408. };
  18409. var serializeCylinder = function (cylinder) {
  18410. var serializationObject = serializePrimitive(cylinder);
  18411. serializationObject.height = cylinder.height;
  18412. serializationObject.diameterTop = cylinder.diameterTop;
  18413. serializationObject.diameterBottom = cylinder.diameterBottom;
  18414. serializationObject.tessellation = cylinder.tessellation;
  18415. return serializationObject;
  18416. };
  18417. var serializeTorus = function (torus) {
  18418. var serializationObject = serializePrimitive(torus);
  18419. serializationObject.diameter = torus.diameter;
  18420. serializationObject.thickness = torus.thickness;
  18421. serializationObject.tessellation = torus.tessellation;
  18422. return serializationObject;
  18423. };
  18424. var serializeGround = function (ground) {
  18425. var serializationObject = serializePrimitive(ground);
  18426. serializationObject.width = ground.width;
  18427. serializationObject.height = ground.height;
  18428. serializationObject.subdivisions = ground.subdivisions;
  18429. return serializationObject;
  18430. };
  18431. var serializePlane = function (plane) {
  18432. var serializationObject = serializePrimitive(plane);
  18433. serializationObject.size = plane.size;
  18434. return serializationObject;
  18435. };
  18436. var serializeTorusKnot = function (torusKnot) {
  18437. var serializationObject = serializePrimitive(torusKnot);
  18438. serializationObject.radius = torusKnot.radius;
  18439. serializationObject.tube = torusKnot.tube;
  18440. serializationObject.radialSegments = torusKnot.radialSegments;
  18441. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18442. serializationObject.p = torusKnot.p;
  18443. serializationObject.q = torusKnot.q;
  18444. return serializationObject;
  18445. };
  18446. var serializeMesh = function (mesh, serializationScene) {
  18447. var serializationObject = {};
  18448. serializationObject.name = mesh.name;
  18449. serializationObject.id = mesh.id;
  18450. if (BABYLON.Tags.HasTags(mesh)) {
  18451. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18452. }
  18453. serializationObject.position = mesh.position.asArray();
  18454. if (mesh.rotationQuaternion) {
  18455. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18456. }
  18457. else if (mesh.rotation) {
  18458. serializationObject.rotation = mesh.rotation.asArray();
  18459. }
  18460. serializationObject.scaling = mesh.scaling.asArray();
  18461. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18462. serializationObject.isEnabled = mesh.isEnabled();
  18463. serializationObject.isVisible = mesh.isVisible;
  18464. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18465. serializationObject.pickable = mesh.isPickable;
  18466. serializationObject.receiveShadows = mesh.receiveShadows;
  18467. serializationObject.billboardMode = mesh.billboardMode;
  18468. serializationObject.visibility = mesh.visibility;
  18469. serializationObject.checkCollisions = mesh.checkCollisions;
  18470. // Parent
  18471. if (mesh.parent) {
  18472. serializationObject.parentId = mesh.parent.id;
  18473. }
  18474. // Geometry
  18475. var geometry = mesh._geometry;
  18476. if (geometry) {
  18477. var geometryId = geometry.id;
  18478. serializationObject.geometryId = geometryId;
  18479. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18480. // 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
  18481. serializeGeometry(geometry, serializationScene.geometries);
  18482. }
  18483. // SubMeshes
  18484. serializationObject.subMeshes = [];
  18485. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18486. var subMesh = mesh.subMeshes[subIndex];
  18487. serializationObject.subMeshes.push({
  18488. materialIndex: subMesh.materialIndex,
  18489. verticesStart: subMesh.verticesStart,
  18490. verticesCount: subMesh.verticesCount,
  18491. indexStart: subMesh.indexStart,
  18492. indexCount: subMesh.indexCount
  18493. });
  18494. }
  18495. }
  18496. // Material
  18497. if (mesh.material) {
  18498. serializationObject.materialId = mesh.material.id;
  18499. }
  18500. else {
  18501. mesh.material = null;
  18502. }
  18503. // Skeleton
  18504. if (mesh.skeleton) {
  18505. serializationObject.skeletonId = mesh.skeleton.id;
  18506. }
  18507. // Physics
  18508. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18509. serializationObject.physicsMass = mesh.getPhysicsMass();
  18510. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18511. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18512. switch (mesh.getPhysicsImpostor()) {
  18513. case BABYLON.PhysicsEngine.BoxImpostor:
  18514. serializationObject.physicsImpostor = 1;
  18515. break;
  18516. case BABYLON.PhysicsEngine.SphereImpostor:
  18517. serializationObject.physicsImpostor = 2;
  18518. break;
  18519. }
  18520. }
  18521. // Instances
  18522. serializationObject.instances = [];
  18523. for (var index = 0; index < mesh.instances.length; index++) {
  18524. var instance = mesh.instances[index];
  18525. var serializationInstance = {
  18526. name: instance.name,
  18527. position: instance.position,
  18528. rotation: instance.rotation,
  18529. rotationQuaternion: instance.rotationQuaternion,
  18530. scaling: instance.scaling
  18531. };
  18532. serializationObject.instances.push(serializationInstance);
  18533. // Animations
  18534. appendAnimations(instance, serializationInstance);
  18535. }
  18536. // Animations
  18537. appendAnimations(mesh, serializationObject);
  18538. // Layer mask
  18539. serializationObject.layerMask = mesh.layerMask;
  18540. return serializationObject;
  18541. };
  18542. var SceneSerializer = (function () {
  18543. function SceneSerializer() {
  18544. }
  18545. SceneSerializer.Serialize = function (scene) {
  18546. var serializationObject = {};
  18547. // Scene
  18548. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18549. serializationObject.autoClear = scene.autoClear;
  18550. serializationObject.clearColor = scene.clearColor.asArray();
  18551. serializationObject.ambientColor = scene.ambientColor.asArray();
  18552. serializationObject.gravity = scene.gravity.asArray();
  18553. // Fog
  18554. if (scene.fogMode && scene.fogMode !== 0) {
  18555. serializationObject.fogMode = scene.fogMode;
  18556. serializationObject.fogColor = scene.fogColor.asArray();
  18557. serializationObject.fogStart = scene.fogStart;
  18558. serializationObject.fogEnd = scene.fogEnd;
  18559. serializationObject.fogDensity = scene.fogDensity;
  18560. }
  18561. // Lights
  18562. serializationObject.lights = [];
  18563. for (var index = 0; index < scene.lights.length; index++) {
  18564. var light = scene.lights[index];
  18565. serializationObject.lights.push(serializeLight(light));
  18566. }
  18567. // Cameras
  18568. serializationObject.cameras = [];
  18569. for (index = 0; index < scene.cameras.length; index++) {
  18570. var camera = scene.cameras[index];
  18571. serializationObject.cameras.push(serializeCamera(camera));
  18572. }
  18573. if (scene.activeCamera) {
  18574. serializationObject.activeCameraID = scene.activeCamera.id;
  18575. }
  18576. // Materials
  18577. serializationObject.materials = [];
  18578. serializationObject.multiMaterials = [];
  18579. for (index = 0; index < scene.materials.length; index++) {
  18580. var material = scene.materials[index];
  18581. if (material instanceof BABYLON.StandardMaterial) {
  18582. serializationObject.materials.push(serializeMaterial(material));
  18583. }
  18584. else if (material instanceof BABYLON.MultiMaterial) {
  18585. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18586. }
  18587. }
  18588. // Skeletons
  18589. serializationObject.skeletons = [];
  18590. for (index = 0; index < scene.skeletons.length; index++) {
  18591. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18592. }
  18593. // Geometries
  18594. serializationObject.geometries = {};
  18595. serializationObject.geometries.boxes = [];
  18596. serializationObject.geometries.spheres = [];
  18597. serializationObject.geometries.cylinders = [];
  18598. serializationObject.geometries.toruses = [];
  18599. serializationObject.geometries.grounds = [];
  18600. serializationObject.geometries.planes = [];
  18601. serializationObject.geometries.torusKnots = [];
  18602. serializationObject.geometries.vertexData = [];
  18603. serializedGeometries = [];
  18604. var geometries = scene.getGeometries();
  18605. for (var index = 0; index < geometries.length; index++) {
  18606. var geometry = geometries[index];
  18607. if (geometry.isReady()) {
  18608. serializeGeometry(geometry, serializationObject.geometries);
  18609. }
  18610. }
  18611. // Meshes
  18612. serializationObject.meshes = [];
  18613. for (index = 0; index < scene.meshes.length; index++) {
  18614. var abstractMesh = scene.meshes[index];
  18615. if (abstractMesh instanceof BABYLON.Mesh) {
  18616. var mesh = abstractMesh;
  18617. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18618. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18619. }
  18620. }
  18621. }
  18622. // Particles Systems
  18623. serializationObject.particleSystems = [];
  18624. for (index = 0; index < scene.particleSystems.length; index++) {
  18625. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18626. }
  18627. // Lens flares
  18628. serializationObject.lensFlareSystems = [];
  18629. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18630. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18631. }
  18632. // Shadows
  18633. serializationObject.shadowGenerators = [];
  18634. for (index = 0; index < scene.lights.length; index++) {
  18635. light = scene.lights[index];
  18636. if (light.getShadowGenerator()) {
  18637. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18638. }
  18639. }
  18640. return serializationObject;
  18641. };
  18642. return SceneSerializer;
  18643. })();
  18644. BABYLON.SceneSerializer = SceneSerializer;
  18645. })(BABYLON || (BABYLON = {}));
  18646. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18647. (function (BABYLON) {
  18648. var SceneLoader = (function () {
  18649. function SceneLoader() {
  18650. }
  18651. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18652. get: function () {
  18653. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18654. },
  18655. set: function (value) {
  18656. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18657. },
  18658. enumerable: true,
  18659. configurable: true
  18660. });
  18661. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18662. get: function () {
  18663. return SceneLoader._ShowLoadingScreen;
  18664. },
  18665. set: function (value) {
  18666. SceneLoader._ShowLoadingScreen = value;
  18667. },
  18668. enumerable: true,
  18669. configurable: true
  18670. });
  18671. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18672. var dotPosition = sceneFilename.lastIndexOf(".");
  18673. var queryStringPosition = sceneFilename.indexOf("?");
  18674. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18675. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18676. var plugin = this._registeredPlugins[index];
  18677. if (plugin.extensions.indexOf(extension) !== -1) {
  18678. return plugin;
  18679. }
  18680. }
  18681. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18682. };
  18683. // Public functions
  18684. SceneLoader.RegisterPlugin = function (plugin) {
  18685. plugin.extensions = plugin.extensions.toLowerCase();
  18686. SceneLoader._registeredPlugins.push(plugin);
  18687. };
  18688. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18689. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18690. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18691. return;
  18692. }
  18693. var manifestChecked = function (success) {
  18694. scene.database = database;
  18695. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18696. var importMeshFromData = function (data) {
  18697. var meshes = [];
  18698. var particleSystems = [];
  18699. var skeletons = [];
  18700. try {
  18701. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18702. if (onerror) {
  18703. onerror(scene, 'unable to load the scene');
  18704. }
  18705. return;
  18706. }
  18707. }
  18708. catch (e) {
  18709. if (onerror) {
  18710. onerror(scene, e);
  18711. }
  18712. return;
  18713. }
  18714. if (onsuccess) {
  18715. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18716. onsuccess(meshes, particleSystems, skeletons);
  18717. }
  18718. };
  18719. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18720. // Direct load
  18721. importMeshFromData(sceneFilename.substr(5));
  18722. return;
  18723. }
  18724. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18725. importMeshFromData(data);
  18726. }, progressCallBack, database);
  18727. };
  18728. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18729. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18730. };
  18731. /**
  18732. * Load a scene
  18733. * @param rootUrl a string that defines the root url for scene and resources
  18734. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18735. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18736. */
  18737. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18738. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18739. };
  18740. /**
  18741. * Append a scene
  18742. * @param rootUrl a string that defines the root url for scene and resources
  18743. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18744. * @param scene is the instance of BABYLON.Scene to append to
  18745. */
  18746. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18747. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18748. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18749. return;
  18750. }
  18751. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18752. var database;
  18753. if (SceneLoader.ShowLoadingScreen) {
  18754. scene.getEngine().displayLoadingUI();
  18755. }
  18756. var loadSceneFromData = function (data) {
  18757. scene.database = database;
  18758. if (!plugin.load(scene, data, rootUrl)) {
  18759. if (onerror) {
  18760. onerror(scene);
  18761. }
  18762. scene.getEngine().hideLoadingUI();
  18763. return;
  18764. }
  18765. if (onsuccess) {
  18766. onsuccess(scene);
  18767. }
  18768. if (SceneLoader.ShowLoadingScreen) {
  18769. scene.executeWhenReady(function () {
  18770. scene.getEngine().hideLoadingUI();
  18771. });
  18772. }
  18773. };
  18774. var manifestChecked = function (success) {
  18775. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18776. };
  18777. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18778. // Direct load
  18779. loadSceneFromData(sceneFilename.substr(5));
  18780. return;
  18781. }
  18782. if (rootUrl.indexOf("file:") === -1) {
  18783. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18784. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18785. }
  18786. else {
  18787. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18788. }
  18789. };
  18790. // Flags
  18791. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18792. SceneLoader._ShowLoadingScreen = true;
  18793. // Members
  18794. SceneLoader._registeredPlugins = new Array();
  18795. return SceneLoader;
  18796. })();
  18797. BABYLON.SceneLoader = SceneLoader;
  18798. ;
  18799. })(BABYLON || (BABYLON = {}));
  18800. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18801. (function (BABYLON) {
  18802. var Internals;
  18803. (function (Internals) {
  18804. var checkColors4 = function (colors, count) {
  18805. // Check if color3 was used
  18806. if (colors.length === count * 3) {
  18807. var colors4 = [];
  18808. for (var index = 0; index < colors.length; index += 3) {
  18809. var newIndex = (index / 3) * 4;
  18810. colors4[newIndex] = colors[index];
  18811. colors4[newIndex + 1] = colors[index + 1];
  18812. colors4[newIndex + 2] = colors[index + 2];
  18813. colors4[newIndex + 3] = 1.0;
  18814. }
  18815. return colors4;
  18816. }
  18817. return colors;
  18818. };
  18819. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18820. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18821. texture.name = parsedTexture.name;
  18822. texture.hasAlpha = parsedTexture.hasAlpha;
  18823. texture.level = parsedTexture.level;
  18824. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18825. return texture;
  18826. };
  18827. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18828. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18829. return null;
  18830. }
  18831. if (parsedTexture.isCube) {
  18832. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18833. }
  18834. var texture;
  18835. if (parsedTexture.mirrorPlane) {
  18836. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18837. texture._waitingRenderList = parsedTexture.renderList;
  18838. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18839. }
  18840. else if (parsedTexture.isRenderTarget) {
  18841. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18842. texture._waitingRenderList = parsedTexture.renderList;
  18843. }
  18844. else {
  18845. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18846. }
  18847. texture.name = parsedTexture.name;
  18848. texture.hasAlpha = parsedTexture.hasAlpha;
  18849. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18850. texture.level = parsedTexture.level;
  18851. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18852. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18853. texture.uOffset = parsedTexture.uOffset;
  18854. texture.vOffset = parsedTexture.vOffset;
  18855. texture.uScale = parsedTexture.uScale;
  18856. texture.vScale = parsedTexture.vScale;
  18857. texture.uAng = parsedTexture.uAng;
  18858. texture.vAng = parsedTexture.vAng;
  18859. texture.wAng = parsedTexture.wAng;
  18860. texture.wrapU = parsedTexture.wrapU;
  18861. texture.wrapV = parsedTexture.wrapV;
  18862. // Animations
  18863. if (parsedTexture.animations) {
  18864. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18865. var parsedAnimation = parsedTexture.animations[animationIndex];
  18866. texture.animations.push(parseAnimation(parsedAnimation));
  18867. }
  18868. }
  18869. return texture;
  18870. };
  18871. var parseSkeleton = function (parsedSkeleton, scene) {
  18872. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18873. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18874. var parsedBone = parsedSkeleton.bones[index];
  18875. var parentBone = null;
  18876. if (parsedBone.parentBoneIndex > -1) {
  18877. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18878. }
  18879. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18880. if (parsedBone.animation) {
  18881. bone.animations.push(parseAnimation(parsedBone.animation));
  18882. }
  18883. }
  18884. return skeleton;
  18885. };
  18886. var parseFresnelParameters = function (parsedFresnelParameters) {
  18887. var fresnelParameters = new BABYLON.FresnelParameters();
  18888. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18889. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18890. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18891. fresnelParameters.bias = parsedFresnelParameters.bias;
  18892. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18893. return fresnelParameters;
  18894. };
  18895. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18896. var material;
  18897. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18898. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18899. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18900. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18901. material.specularPower = parsedMaterial.specularPower;
  18902. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18903. material.alpha = parsedMaterial.alpha;
  18904. material.id = parsedMaterial.id;
  18905. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18906. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18907. material.wireframe = parsedMaterial.wireframe;
  18908. if (parsedMaterial.diffuseTexture) {
  18909. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18910. }
  18911. if (parsedMaterial.diffuseFresnelParameters) {
  18912. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18913. }
  18914. if (parsedMaterial.ambientTexture) {
  18915. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18916. }
  18917. if (parsedMaterial.opacityTexture) {
  18918. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18919. }
  18920. if (parsedMaterial.opacityFresnelParameters) {
  18921. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18922. }
  18923. if (parsedMaterial.reflectionTexture) {
  18924. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18925. }
  18926. if (parsedMaterial.reflectionFresnelParameters) {
  18927. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18928. }
  18929. if (parsedMaterial.emissiveTexture) {
  18930. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18931. }
  18932. if (parsedMaterial.emissiveFresnelParameters) {
  18933. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18934. }
  18935. if (parsedMaterial.specularTexture) {
  18936. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18937. }
  18938. if (parsedMaterial.bumpTexture) {
  18939. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18940. }
  18941. return material;
  18942. };
  18943. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18944. for (var index = 0; index < parsedData.materials.length; index++) {
  18945. var parsedMaterial = parsedData.materials[index];
  18946. if (parsedMaterial.id === id) {
  18947. return parseMaterial(parsedMaterial, scene, rootUrl);
  18948. }
  18949. }
  18950. return null;
  18951. };
  18952. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18953. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18954. multiMaterial.id = parsedMultiMaterial.id;
  18955. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18956. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18957. var subMatId = parsedMultiMaterial.materials[matIndex];
  18958. if (subMatId) {
  18959. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18960. }
  18961. else {
  18962. multiMaterial.subMaterials.push(null);
  18963. }
  18964. }
  18965. return multiMaterial;
  18966. };
  18967. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18968. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18969. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18970. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18971. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18972. var parsedFlare = parsedLensFlareSystem.flares[index];
  18973. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18974. }
  18975. return lensFlareSystem;
  18976. };
  18977. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18978. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18979. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18980. if (parsedParticleSystem.textureName) {
  18981. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18982. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18983. }
  18984. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18985. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18986. particleSystem.minSize = parsedParticleSystem.minSize;
  18987. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18988. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18989. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18990. particleSystem.emitter = emitter;
  18991. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18992. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18993. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18994. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18995. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18996. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18997. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18998. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18999. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  19000. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  19001. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  19002. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  19003. particleSystem.blendMode = parsedParticleSystem.blendMode;
  19004. particleSystem.start();
  19005. return particleSystem;
  19006. };
  19007. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  19008. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  19009. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  19010. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  19011. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  19012. shadowGenerator.getShadowMap().renderList.push(mesh);
  19013. }
  19014. if (parsedShadowGenerator.usePoissonSampling) {
  19015. shadowGenerator.usePoissonSampling = true;
  19016. }
  19017. else if (parsedShadowGenerator.useVarianceShadowMap) {
  19018. shadowGenerator.useVarianceShadowMap = true;
  19019. }
  19020. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  19021. shadowGenerator.useBlurVarianceShadowMap = true;
  19022. }
  19023. if (parsedShadowGenerator.bias) {
  19024. shadowGenerator.bias = parsedShadowGenerator.bias;
  19025. }
  19026. return shadowGenerator;
  19027. };
  19028. var parseAnimation = function (parsedAnimation) {
  19029. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  19030. var dataType = parsedAnimation.dataType;
  19031. var keys = [];
  19032. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  19033. var key = parsedAnimation.keys[index];
  19034. var data;
  19035. switch (dataType) {
  19036. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  19037. data = key.values[0];
  19038. break;
  19039. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  19040. data = BABYLON.Quaternion.FromArray(key.values);
  19041. break;
  19042. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  19043. data = BABYLON.Matrix.FromArray(key.values);
  19044. break;
  19045. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  19046. default:
  19047. data = BABYLON.Vector3.FromArray(key.values);
  19048. break;
  19049. }
  19050. keys.push({
  19051. frame: key.frame,
  19052. value: data
  19053. });
  19054. }
  19055. animation.setKeys(keys);
  19056. return animation;
  19057. };
  19058. var parseLight = function (parsedLight, scene) {
  19059. var light;
  19060. switch (parsedLight.type) {
  19061. case 0:
  19062. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  19063. break;
  19064. case 1:
  19065. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19066. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  19067. break;
  19068. case 2:
  19069. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  19070. break;
  19071. case 3:
  19072. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  19073. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  19074. break;
  19075. }
  19076. light.id = parsedLight.id;
  19077. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  19078. if (parsedLight.intensity !== undefined) {
  19079. light.intensity = parsedLight.intensity;
  19080. }
  19081. if (parsedLight.range) {
  19082. light.range = parsedLight.range;
  19083. }
  19084. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  19085. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  19086. if (parsedLight.excludedMeshesIds) {
  19087. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19088. }
  19089. // Parent
  19090. if (parsedLight.parentId) {
  19091. light._waitingParentId = parsedLight.parentId;
  19092. }
  19093. if (parsedLight.includedOnlyMeshesIds) {
  19094. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19095. }
  19096. // Animations
  19097. if (parsedLight.animations) {
  19098. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19099. var parsedAnimation = parsedLight.animations[animationIndex];
  19100. light.animations.push(parseAnimation(parsedAnimation));
  19101. }
  19102. }
  19103. if (parsedLight.autoAnimate) {
  19104. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  19105. }
  19106. };
  19107. var parseCamera = function (parsedCamera, scene) {
  19108. var camera;
  19109. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  19110. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  19111. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  19112. var alpha = parsedCamera.alpha;
  19113. var beta = parsedCamera.beta;
  19114. var radius = parsedCamera.radius;
  19115. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  19116. var eye_space = parsedCamera.eye_space;
  19117. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  19118. }
  19119. else {
  19120. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  19121. }
  19122. }
  19123. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  19124. eye_space = parsedCamera.eye_space;
  19125. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  19126. }
  19127. else if (parsedCamera.type === "DeviceOrientationCamera") {
  19128. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  19129. }
  19130. else if (parsedCamera.type === "FollowCamera") {
  19131. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  19132. camera.heightOffset = parsedCamera.heightOffset;
  19133. camera.radius = parsedCamera.radius;
  19134. camera.rotationOffset = parsedCamera.rotationOffset;
  19135. if (lockedTargetMesh)
  19136. camera.target = lockedTargetMesh;
  19137. }
  19138. else if (parsedCamera.type === "GamepadCamera") {
  19139. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  19140. }
  19141. else if (parsedCamera.type === "OculusCamera") {
  19142. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  19143. }
  19144. else if (parsedCamera.type === "OculusGamepadCamera") {
  19145. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  19146. }
  19147. else if (parsedCamera.type === "TouchCamera") {
  19148. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  19149. }
  19150. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  19151. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  19152. }
  19153. else if (parsedCamera.type === "WebVRCamera") {
  19154. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  19155. }
  19156. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  19157. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  19158. }
  19159. else {
  19160. // Free Camera is the default value
  19161. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  19162. }
  19163. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  19164. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  19165. camera.lockedTarget = lockedTargetMesh;
  19166. }
  19167. camera.id = parsedCamera.id;
  19168. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  19169. // Parent
  19170. if (parsedCamera.parentId) {
  19171. camera._waitingParentId = parsedCamera.parentId;
  19172. }
  19173. // Target
  19174. if (parsedCamera.target) {
  19175. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  19176. }
  19177. else {
  19178. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  19179. }
  19180. camera.fov = parsedCamera.fov;
  19181. camera.minZ = parsedCamera.minZ;
  19182. camera.maxZ = parsedCamera.maxZ;
  19183. camera.speed = parsedCamera.speed;
  19184. camera.inertia = parsedCamera.inertia;
  19185. camera.checkCollisions = parsedCamera.checkCollisions;
  19186. camera.applyGravity = parsedCamera.applyGravity;
  19187. if (parsedCamera.ellipsoid) {
  19188. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  19189. }
  19190. // Animations
  19191. if (parsedCamera.animations) {
  19192. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  19193. var parsedAnimation = parsedCamera.animations[animationIndex];
  19194. camera.animations.push(parseAnimation(parsedAnimation));
  19195. }
  19196. }
  19197. if (parsedCamera.autoAnimate) {
  19198. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  19199. }
  19200. // Layer Mask
  19201. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  19202. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  19203. }
  19204. else {
  19205. camera.layerMask = 0xFFFFFFFF;
  19206. }
  19207. return camera;
  19208. };
  19209. var parseGeometry = function (parsedGeometry, scene) {
  19210. var id = parsedGeometry.id;
  19211. return scene.getGeometryByID(id);
  19212. };
  19213. var parseBox = function (parsedBox, scene) {
  19214. if (parseGeometry(parsedBox, scene)) {
  19215. return null; // null since geometry could be something else than a box...
  19216. }
  19217. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  19218. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  19219. scene.pushGeometry(box, true);
  19220. return box;
  19221. };
  19222. var parseSphere = function (parsedSphere, scene) {
  19223. if (parseGeometry(parsedSphere, scene)) {
  19224. return null; // null since geometry could be something else than a sphere...
  19225. }
  19226. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  19227. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  19228. scene.pushGeometry(sphere, true);
  19229. return sphere;
  19230. };
  19231. var parseCylinder = function (parsedCylinder, scene) {
  19232. if (parseGeometry(parsedCylinder, scene)) {
  19233. return null; // null since geometry could be something else than a cylinder...
  19234. }
  19235. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  19236. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  19237. scene.pushGeometry(cylinder, true);
  19238. return cylinder;
  19239. };
  19240. var parseTorus = function (parsedTorus, scene) {
  19241. if (parseGeometry(parsedTorus, scene)) {
  19242. return null; // null since geometry could be something else than a torus...
  19243. }
  19244. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  19245. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  19246. scene.pushGeometry(torus, true);
  19247. return torus;
  19248. };
  19249. var parseGround = function (parsedGround, scene) {
  19250. if (parseGeometry(parsedGround, scene)) {
  19251. return null; // null since geometry could be something else than a ground...
  19252. }
  19253. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  19254. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  19255. scene.pushGeometry(ground, true);
  19256. return ground;
  19257. };
  19258. var parsePlane = function (parsedPlane, scene) {
  19259. if (parseGeometry(parsedPlane, scene)) {
  19260. return null; // null since geometry could be something else than a plane...
  19261. }
  19262. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  19263. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  19264. scene.pushGeometry(plane, true);
  19265. return plane;
  19266. };
  19267. var parseTorusKnot = function (parsedTorusKnot, scene) {
  19268. if (parseGeometry(parsedTorusKnot, scene)) {
  19269. return null; // null since geometry could be something else than a torusKnot...
  19270. }
  19271. 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);
  19272. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19273. scene.pushGeometry(torusKnot, true);
  19274. return torusKnot;
  19275. };
  19276. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19277. if (parseGeometry(parsedVertexData, scene)) {
  19278. return null; // null since geometry could be a primitive
  19279. }
  19280. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19281. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19282. if (parsedVertexData.delayLoadingFile) {
  19283. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19284. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19285. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19286. geometry._delayInfo = [];
  19287. if (parsedVertexData.hasUVs) {
  19288. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19289. }
  19290. if (parsedVertexData.hasUVs2) {
  19291. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19292. }
  19293. if (parsedVertexData.hasColors) {
  19294. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19295. }
  19296. if (parsedVertexData.hasMatricesIndices) {
  19297. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19298. }
  19299. if (parsedVertexData.hasMatricesWeights) {
  19300. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19301. }
  19302. geometry._delayLoadingFunction = importVertexData;
  19303. }
  19304. else {
  19305. importVertexData(parsedVertexData, geometry);
  19306. }
  19307. scene.pushGeometry(geometry, true);
  19308. return geometry;
  19309. };
  19310. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19311. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19312. mesh.id = parsedMesh.id;
  19313. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19314. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19315. if (parsedMesh.rotationQuaternion) {
  19316. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19317. }
  19318. else if (parsedMesh.rotation) {
  19319. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19320. }
  19321. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19322. if (parsedMesh.localMatrix) {
  19323. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19324. }
  19325. else if (parsedMesh.pivotMatrix) {
  19326. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19327. }
  19328. mesh.setEnabled(parsedMesh.isEnabled);
  19329. mesh.isVisible = parsedMesh.isVisible;
  19330. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19331. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19332. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19333. if (parsedMesh.applyFog !== undefined) {
  19334. mesh.applyFog = parsedMesh.applyFog;
  19335. }
  19336. if (parsedMesh.pickable !== undefined) {
  19337. mesh.isPickable = parsedMesh.pickable;
  19338. }
  19339. if (parsedMesh.alphaIndex !== undefined) {
  19340. mesh.alphaIndex = parsedMesh.alphaIndex;
  19341. }
  19342. mesh.receiveShadows = parsedMesh.receiveShadows;
  19343. mesh.billboardMode = parsedMesh.billboardMode;
  19344. if (parsedMesh.visibility !== undefined) {
  19345. mesh.visibility = parsedMesh.visibility;
  19346. }
  19347. mesh.checkCollisions = parsedMesh.checkCollisions;
  19348. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19349. // Parent
  19350. if (parsedMesh.parentId) {
  19351. mesh._waitingParentId = parsedMesh.parentId;
  19352. }
  19353. // Actions
  19354. if (parsedMesh.actions !== undefined) {
  19355. mesh._waitingActions = parsedMesh.actions;
  19356. }
  19357. // Geometry
  19358. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19359. if (parsedMesh.delayLoadingFile) {
  19360. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19361. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19362. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19363. if (parsedMesh._binaryInfo) {
  19364. mesh._binaryInfo = parsedMesh._binaryInfo;
  19365. }
  19366. mesh._delayInfo = [];
  19367. if (parsedMesh.hasUVs) {
  19368. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19369. }
  19370. if (parsedMesh.hasUVs2) {
  19371. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19372. }
  19373. if (parsedMesh.hasColors) {
  19374. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19375. }
  19376. if (parsedMesh.hasMatricesIndices) {
  19377. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19378. }
  19379. if (parsedMesh.hasMatricesWeights) {
  19380. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19381. }
  19382. mesh._delayLoadingFunction = importGeometry;
  19383. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19384. mesh._checkDelayState();
  19385. }
  19386. }
  19387. else {
  19388. importGeometry(parsedMesh, mesh);
  19389. }
  19390. // Material
  19391. if (parsedMesh.materialId) {
  19392. mesh.setMaterialByID(parsedMesh.materialId);
  19393. }
  19394. else {
  19395. mesh.material = null;
  19396. }
  19397. // Skeleton
  19398. if (parsedMesh.skeletonId > -1) {
  19399. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19400. }
  19401. // Physics
  19402. if (parsedMesh.physicsImpostor) {
  19403. if (!scene.isPhysicsEnabled()) {
  19404. scene.enablePhysics();
  19405. }
  19406. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19407. }
  19408. // Animations
  19409. if (parsedMesh.animations) {
  19410. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19411. var parsedAnimation = parsedMesh.animations[animationIndex];
  19412. mesh.animations.push(parseAnimation(parsedAnimation));
  19413. }
  19414. }
  19415. if (parsedMesh.autoAnimate) {
  19416. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19417. }
  19418. // Layer Mask
  19419. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19420. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19421. }
  19422. else {
  19423. mesh.layerMask = 0xFFFFFFFF;
  19424. }
  19425. // Instances
  19426. if (parsedMesh.instances) {
  19427. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19428. var parsedInstance = parsedMesh.instances[index];
  19429. var instance = mesh.createInstance(parsedInstance.name);
  19430. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19431. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19432. if (parsedInstance.rotationQuaternion) {
  19433. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19434. }
  19435. else if (parsedInstance.rotation) {
  19436. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19437. }
  19438. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19439. instance.checkCollisions = mesh.checkCollisions;
  19440. if (parsedMesh.animations) {
  19441. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19442. parsedAnimation = parsedMesh.animations[animationIndex];
  19443. instance.animations.push(parseAnimation(parsedAnimation));
  19444. }
  19445. }
  19446. }
  19447. }
  19448. return mesh;
  19449. };
  19450. var parseActions = function (parsedActions, object, scene) {
  19451. var actionManager = new BABYLON.ActionManager(scene);
  19452. if (object === null)
  19453. scene.actionManager = actionManager;
  19454. else
  19455. object.actionManager = actionManager;
  19456. // instanciate a new object
  19457. var instanciate = function (name, params) {
  19458. var newInstance = Object.create(BABYLON[name].prototype);
  19459. newInstance.constructor.apply(newInstance, params);
  19460. return newInstance;
  19461. };
  19462. var parseParameter = function (name, value, target, propertyPath) {
  19463. if (propertyPath === null) {
  19464. // String, boolean or float
  19465. var floatValue = parseFloat(value);
  19466. if (value === "true" || value === "false")
  19467. return value === "true";
  19468. else
  19469. return isNaN(floatValue) ? value : floatValue;
  19470. }
  19471. var effectiveTarget = propertyPath.split(".");
  19472. var values = value.split(",");
  19473. for (var i = 0; i < effectiveTarget.length; i++) {
  19474. target = target[effectiveTarget[i]];
  19475. }
  19476. // Return appropriate value with its type
  19477. if (target instanceof Boolean)
  19478. return values[0] === "true";
  19479. if (target instanceof String)
  19480. return values[0];
  19481. // Parameters with multiple values such as Vector3 etc.
  19482. var split = new Array();
  19483. for (var i = 0; i < values.length; i++)
  19484. split.push(parseFloat(values[i]));
  19485. if (target instanceof BABYLON.Vector3)
  19486. return BABYLON.Vector3.FromArray(split);
  19487. if (target instanceof BABYLON.Vector4)
  19488. return BABYLON.Vector4.FromArray(split);
  19489. if (target instanceof BABYLON.Color3)
  19490. return BABYLON.Color3.FromArray(split);
  19491. if (target instanceof BABYLON.Color4)
  19492. return BABYLON.Color4.FromArray(split);
  19493. return parseFloat(values[0]);
  19494. };
  19495. // traverse graph per trigger
  19496. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19497. if (combineArray === void 0) { combineArray = null; }
  19498. if (parsedAction.detached)
  19499. return;
  19500. var parameters = new Array();
  19501. var target = null;
  19502. var propertyPath = null;
  19503. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19504. // Parameters
  19505. if (parsedAction.type === 2)
  19506. parameters.push(actionManager);
  19507. else
  19508. parameters.push(trigger);
  19509. if (combine) {
  19510. var actions = new Array();
  19511. for (var j = 0; j < parsedAction.combine.length; j++) {
  19512. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19513. }
  19514. parameters.push(actions);
  19515. }
  19516. else {
  19517. for (var i = 0; i < parsedAction.properties.length; i++) {
  19518. var value = parsedAction.properties[i].value;
  19519. var name = parsedAction.properties[i].name;
  19520. if (name === "target")
  19521. value = target = scene.getNodeByName(value);
  19522. else if (name === "parent")
  19523. value = scene.getNodeByName(value);
  19524. else if (name === "sound")
  19525. value = scene.getSoundByName(value);
  19526. else if (name !== "propertyPath") {
  19527. if (parsedAction.type === 2 && name === "operator")
  19528. value = BABYLON.ValueCondition[value];
  19529. else
  19530. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19531. }
  19532. else {
  19533. propertyPath = value;
  19534. }
  19535. parameters.push(value);
  19536. }
  19537. }
  19538. parameters.push(condition);
  19539. // If interpolate value action
  19540. if (parsedAction.name === "InterpolateValueAction") {
  19541. var param = parameters[parameters.length - 2];
  19542. parameters[parameters.length - 1] = param;
  19543. parameters[parameters.length - 2] = condition;
  19544. }
  19545. // Action or condition(s) and not CombineAction
  19546. var newAction = instanciate(parsedAction.name, parameters);
  19547. if (combineArray === null) {
  19548. if (newAction instanceof BABYLON.Condition) {
  19549. condition = newAction;
  19550. newAction = action;
  19551. }
  19552. else {
  19553. condition = null;
  19554. if (action)
  19555. action.then(newAction);
  19556. else
  19557. actionManager.registerAction(newAction);
  19558. }
  19559. }
  19560. else {
  19561. combineArray.push(newAction);
  19562. }
  19563. for (var i = 0; i < parsedAction.children.length; i++)
  19564. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19565. };
  19566. for (var i = 0; i < parsedActions.children.length; i++) {
  19567. var triggerParams;
  19568. var trigger = parsedActions.children[i];
  19569. if (trigger.properties.length > 0) {
  19570. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19571. }
  19572. else
  19573. triggerParams = BABYLON.ActionManager[trigger.name];
  19574. for (var j = 0; j < trigger.children.length; j++)
  19575. traverse(trigger.children[j], triggerParams, null, null);
  19576. }
  19577. };
  19578. var parseSound = function (parsedSound, scene, rootUrl) {
  19579. var soundName = parsedSound.name;
  19580. var soundUrl = rootUrl + soundName;
  19581. var options = {
  19582. autoplay: parsedSound.autoplay,
  19583. loop: parsedSound.loop,
  19584. volume: parsedSound.volume,
  19585. spatialSound: parsedSound.spatialSound,
  19586. maxDistance: parsedSound.maxDistance,
  19587. rolloffFactor: parsedSound.rolloffFactor,
  19588. refDistance: parsedSound.refDistance,
  19589. distanceModel: parsedSound.distanceModel,
  19590. playbackRate: parsedSound.playbackRate
  19591. };
  19592. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19593. scene._removePendingData(newSound);
  19594. }, options);
  19595. scene._addPendingData(newSound);
  19596. if (parsedSound.position) {
  19597. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19598. newSound.setPosition(soundPosition);
  19599. }
  19600. if (parsedSound.isDirectional) {
  19601. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19602. if (parsedSound.localDirectionToMesh) {
  19603. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19604. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19605. }
  19606. }
  19607. if (parsedSound.connectedMeshId) {
  19608. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19609. if (connectedMesh) {
  19610. newSound.attachToMesh(connectedMesh);
  19611. }
  19612. }
  19613. };
  19614. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19615. names = (names instanceof Array) ? names : [names];
  19616. for (var i in names) {
  19617. if (mesh.name === names[i]) {
  19618. hierarchyIds.push(mesh.id);
  19619. return true;
  19620. }
  19621. }
  19622. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19623. hierarchyIds.push(mesh.id);
  19624. return true;
  19625. }
  19626. return false;
  19627. };
  19628. var importVertexData = function (parsedVertexData, geometry) {
  19629. var vertexData = new BABYLON.VertexData();
  19630. // positions
  19631. var positions = parsedVertexData.positions;
  19632. if (positions) {
  19633. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19634. }
  19635. // normals
  19636. var normals = parsedVertexData.normals;
  19637. if (normals) {
  19638. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19639. }
  19640. // uvs
  19641. var uvs = parsedVertexData.uvs;
  19642. if (uvs) {
  19643. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19644. }
  19645. // uv2s
  19646. var uv2s = parsedVertexData.uv2s;
  19647. if (uv2s) {
  19648. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19649. }
  19650. // colors
  19651. var colors = parsedVertexData.colors;
  19652. if (colors) {
  19653. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19654. }
  19655. // matricesIndices
  19656. var matricesIndices = parsedVertexData.matricesIndices;
  19657. if (matricesIndices) {
  19658. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19659. }
  19660. // matricesWeights
  19661. var matricesWeights = parsedVertexData.matricesWeights;
  19662. if (matricesWeights) {
  19663. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19664. }
  19665. // indices
  19666. var indices = parsedVertexData.indices;
  19667. if (indices) {
  19668. vertexData.indices = indices;
  19669. }
  19670. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19671. };
  19672. var importGeometry = function (parsedGeometry, mesh) {
  19673. var scene = mesh.getScene();
  19674. // Geometry
  19675. var geometryId = parsedGeometry.geometryId;
  19676. if (geometryId) {
  19677. var geometry = scene.getGeometryByID(geometryId);
  19678. if (geometry) {
  19679. geometry.applyToMesh(mesh);
  19680. }
  19681. }
  19682. else if (parsedGeometry instanceof ArrayBuffer) {
  19683. var binaryInfo = mesh._binaryInfo;
  19684. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19685. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19686. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19687. }
  19688. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19689. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19690. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19691. }
  19692. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19693. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19694. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19695. }
  19696. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19697. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19698. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19699. }
  19700. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19701. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19702. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19703. }
  19704. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19705. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19706. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19707. }
  19708. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19709. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19710. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19711. }
  19712. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19713. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19714. mesh.setIndices(indicesData);
  19715. }
  19716. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19717. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19718. mesh.subMeshes = [];
  19719. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19720. var materialIndex = subMeshesData[(i * 5) + 0];
  19721. var verticesStart = subMeshesData[(i * 5) + 1];
  19722. var verticesCount = subMeshesData[(i * 5) + 2];
  19723. var indexStart = subMeshesData[(i * 5) + 3];
  19724. var indexCount = subMeshesData[(i * 5) + 4];
  19725. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19726. }
  19727. }
  19728. }
  19729. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19730. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19731. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19732. if (parsedGeometry.uvs) {
  19733. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19734. }
  19735. if (parsedGeometry.uvs2) {
  19736. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19737. }
  19738. if (parsedGeometry.colors) {
  19739. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19740. }
  19741. if (parsedGeometry.matricesIndices) {
  19742. if (!parsedGeometry.matricesIndices._isExpanded) {
  19743. var floatIndices = [];
  19744. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19745. var matricesIndex = parsedGeometry.matricesIndices[i];
  19746. floatIndices.push(matricesIndex & 0x000000FF);
  19747. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19748. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19749. floatIndices.push(matricesIndex >> 24);
  19750. }
  19751. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19752. }
  19753. else {
  19754. delete parsedGeometry.matricesIndices._isExpanded;
  19755. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19756. }
  19757. }
  19758. if (parsedGeometry.matricesWeights) {
  19759. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19760. }
  19761. mesh.setIndices(parsedGeometry.indices);
  19762. // SubMeshes
  19763. if (parsedGeometry.subMeshes) {
  19764. mesh.subMeshes = [];
  19765. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19766. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19767. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19768. }
  19769. }
  19770. }
  19771. // Flat shading
  19772. if (mesh._shouldGenerateFlatShading) {
  19773. mesh.convertToFlatShadedMesh();
  19774. delete mesh._shouldGenerateFlatShading;
  19775. }
  19776. // Update
  19777. mesh.computeWorldMatrix(true);
  19778. // Octree
  19779. if (scene._selectionOctree) {
  19780. scene._selectionOctree.addMesh(mesh);
  19781. }
  19782. };
  19783. BABYLON.SceneLoader.RegisterPlugin({
  19784. extensions: ".babylon",
  19785. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19786. var parsedData = JSON.parse(data);
  19787. var loadedSkeletonsIds = [];
  19788. var loadedMaterialsIds = [];
  19789. var hierarchyIds = [];
  19790. for (var index = 0; index < parsedData.meshes.length; index++) {
  19791. var parsedMesh = parsedData.meshes[index];
  19792. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19793. if (meshesNames instanceof Array) {
  19794. // Remove found mesh name from list.
  19795. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19796. }
  19797. // Material ?
  19798. if (parsedMesh.materialId) {
  19799. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19800. if (!materialFound) {
  19801. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19802. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19803. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19804. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19805. var subMatId = parsedMultiMaterial.materials[matIndex];
  19806. loadedMaterialsIds.push(subMatId);
  19807. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19808. }
  19809. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19810. parseMultiMaterial(parsedMultiMaterial, scene);
  19811. materialFound = true;
  19812. break;
  19813. }
  19814. }
  19815. }
  19816. if (!materialFound) {
  19817. loadedMaterialsIds.push(parsedMesh.materialId);
  19818. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19819. }
  19820. }
  19821. // Skeleton ?
  19822. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19823. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19824. if (!skeletonAlreadyLoaded) {
  19825. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19826. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19827. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19828. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19829. loadedSkeletonsIds.push(parsedSkeleton.id);
  19830. }
  19831. }
  19832. }
  19833. }
  19834. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19835. meshes.push(mesh);
  19836. }
  19837. }
  19838. for (index = 0; index < scene.meshes.length; index++) {
  19839. var currentMesh = scene.meshes[index];
  19840. if (currentMesh._waitingParentId) {
  19841. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19842. currentMesh._waitingParentId = undefined;
  19843. }
  19844. }
  19845. // Particles
  19846. if (parsedData.particleSystems) {
  19847. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19848. var parsedParticleSystem = parsedData.particleSystems[index];
  19849. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19850. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19851. }
  19852. }
  19853. }
  19854. return true;
  19855. },
  19856. load: function (scene, data, rootUrl) {
  19857. var parsedData = JSON.parse(data);
  19858. // Scene
  19859. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19860. scene.autoClear = parsedData.autoClear;
  19861. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19862. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19863. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19864. // Fog
  19865. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19866. scene.fogMode = parsedData.fogMode;
  19867. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19868. scene.fogStart = parsedData.fogStart;
  19869. scene.fogEnd = parsedData.fogEnd;
  19870. scene.fogDensity = parsedData.fogDensity;
  19871. }
  19872. for (var index = 0; index < parsedData.lights.length; index++) {
  19873. var parsedLight = parsedData.lights[index];
  19874. parseLight(parsedLight, scene);
  19875. }
  19876. // Materials
  19877. if (parsedData.materials) {
  19878. for (index = 0; index < parsedData.materials.length; index++) {
  19879. var parsedMaterial = parsedData.materials[index];
  19880. parseMaterial(parsedMaterial, scene, rootUrl);
  19881. }
  19882. }
  19883. if (parsedData.multiMaterials) {
  19884. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19885. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19886. parseMultiMaterial(parsedMultiMaterial, scene);
  19887. }
  19888. }
  19889. // Skeletons
  19890. if (parsedData.skeletons) {
  19891. for (index = 0; index < parsedData.skeletons.length; index++) {
  19892. var parsedSkeleton = parsedData.skeletons[index];
  19893. parseSkeleton(parsedSkeleton, scene);
  19894. }
  19895. }
  19896. // Geometries
  19897. var geometries = parsedData.geometries;
  19898. if (geometries) {
  19899. // Boxes
  19900. var boxes = geometries.boxes;
  19901. if (boxes) {
  19902. for (index = 0; index < boxes.length; index++) {
  19903. var parsedBox = boxes[index];
  19904. parseBox(parsedBox, scene);
  19905. }
  19906. }
  19907. // Spheres
  19908. var spheres = geometries.spheres;
  19909. if (spheres) {
  19910. for (index = 0; index < spheres.length; index++) {
  19911. var parsedSphere = spheres[index];
  19912. parseSphere(parsedSphere, scene);
  19913. }
  19914. }
  19915. // Cylinders
  19916. var cylinders = geometries.cylinders;
  19917. if (cylinders) {
  19918. for (index = 0; index < cylinders.length; index++) {
  19919. var parsedCylinder = cylinders[index];
  19920. parseCylinder(parsedCylinder, scene);
  19921. }
  19922. }
  19923. // Toruses
  19924. var toruses = geometries.toruses;
  19925. if (toruses) {
  19926. for (index = 0; index < toruses.length; index++) {
  19927. var parsedTorus = toruses[index];
  19928. parseTorus(parsedTorus, scene);
  19929. }
  19930. }
  19931. // Grounds
  19932. var grounds = geometries.grounds;
  19933. if (grounds) {
  19934. for (index = 0; index < grounds.length; index++) {
  19935. var parsedGround = grounds[index];
  19936. parseGround(parsedGround, scene);
  19937. }
  19938. }
  19939. // Planes
  19940. var planes = geometries.planes;
  19941. if (planes) {
  19942. for (index = 0; index < planes.length; index++) {
  19943. var parsedPlane = planes[index];
  19944. parsePlane(parsedPlane, scene);
  19945. }
  19946. }
  19947. // TorusKnots
  19948. var torusKnots = geometries.torusKnots;
  19949. if (torusKnots) {
  19950. for (index = 0; index < torusKnots.length; index++) {
  19951. var parsedTorusKnot = torusKnots[index];
  19952. parseTorusKnot(parsedTorusKnot, scene);
  19953. }
  19954. }
  19955. // VertexData
  19956. var vertexData = geometries.vertexData;
  19957. if (vertexData) {
  19958. for (index = 0; index < vertexData.length; index++) {
  19959. var parsedVertexData = vertexData[index];
  19960. parseVertexData(parsedVertexData, scene, rootUrl);
  19961. }
  19962. }
  19963. }
  19964. for (index = 0; index < parsedData.meshes.length; index++) {
  19965. var parsedMesh = parsedData.meshes[index];
  19966. parseMesh(parsedMesh, scene, rootUrl);
  19967. }
  19968. for (index = 0; index < parsedData.cameras.length; index++) {
  19969. var parsedCamera = parsedData.cameras[index];
  19970. parseCamera(parsedCamera, scene);
  19971. }
  19972. if (parsedData.activeCameraID) {
  19973. scene.setActiveCameraByID(parsedData.activeCameraID);
  19974. }
  19975. for (index = 0; index < scene.cameras.length; index++) {
  19976. var camera = scene.cameras[index];
  19977. if (camera._waitingParentId) {
  19978. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19979. camera._waitingParentId = undefined;
  19980. }
  19981. }
  19982. for (index = 0; index < scene.lights.length; index++) {
  19983. var light = scene.lights[index];
  19984. if (light._waitingParentId) {
  19985. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19986. light._waitingParentId = undefined;
  19987. }
  19988. }
  19989. // Sounds
  19990. if (parsedData.sounds) {
  19991. for (index = 0; index < parsedData.sounds.length; index++) {
  19992. var parsedSound = parsedData.sounds[index];
  19993. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19994. parseSound(parsedSound, scene, rootUrl);
  19995. }
  19996. else {
  19997. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19998. }
  19999. }
  20000. }
  20001. for (index = 0; index < scene.meshes.length; index++) {
  20002. var mesh = scene.meshes[index];
  20003. if (mesh._waitingParentId) {
  20004. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  20005. mesh._waitingParentId = undefined;
  20006. }
  20007. if (mesh._waitingActions) {
  20008. parseActions(mesh._waitingActions, mesh, scene);
  20009. mesh._waitingActions = undefined;
  20010. }
  20011. }
  20012. // Particles Systems
  20013. if (parsedData.particleSystems) {
  20014. for (index = 0; index < parsedData.particleSystems.length; index++) {
  20015. var parsedParticleSystem = parsedData.particleSystems[index];
  20016. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  20017. }
  20018. }
  20019. // Lens flares
  20020. if (parsedData.lensFlareSystems) {
  20021. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  20022. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  20023. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  20024. }
  20025. }
  20026. // Shadows
  20027. if (parsedData.shadowGenerators) {
  20028. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  20029. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  20030. parseShadowGenerator(parsedShadowGenerator, scene);
  20031. }
  20032. }
  20033. // Actions (scene)
  20034. if (parsedData.actions) {
  20035. parseActions(parsedData.actions, null, scene);
  20036. }
  20037. // Finish
  20038. return true;
  20039. }
  20040. });
  20041. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  20042. })(BABYLON || (BABYLON = {}));
  20043. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  20044. (function (BABYLON) {
  20045. // Unique ID when we import meshes from Babylon to CSG
  20046. var currentCSGMeshId = 0;
  20047. // # class Vertex
  20048. // Represents a vertex of a polygon. Use your own vertex class instead of this
  20049. // one to provide additional features like texture coordinates and vertex
  20050. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  20051. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  20052. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  20053. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  20054. // is not used anywhere else.
  20055. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  20056. var Vertex = (function () {
  20057. function Vertex(pos, normal, uv) {
  20058. this.pos = pos;
  20059. this.normal = normal;
  20060. this.uv = uv;
  20061. }
  20062. Vertex.prototype.clone = function () {
  20063. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  20064. };
  20065. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  20066. // orientation of a polygon is flipped.
  20067. Vertex.prototype.flip = function () {
  20068. this.normal = this.normal.scale(-1);
  20069. };
  20070. // Create a new vertex between this vertex and `other` by linearly
  20071. // interpolating all properties using a parameter of `t`. Subclasses should
  20072. // override this to interpolate additional properties.
  20073. Vertex.prototype.interpolate = function (other, t) {
  20074. 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));
  20075. };
  20076. return Vertex;
  20077. })();
  20078. // # class Plane
  20079. // Represents a plane in 3D space.
  20080. var Plane = (function () {
  20081. function Plane(normal, w) {
  20082. this.normal = normal;
  20083. this.w = w;
  20084. }
  20085. Plane.FromPoints = function (a, b, c) {
  20086. var v0 = c.subtract(a);
  20087. var v1 = b.subtract(a);
  20088. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  20089. return null;
  20090. }
  20091. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  20092. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  20093. };
  20094. Plane.prototype.clone = function () {
  20095. return new Plane(this.normal.clone(), this.w);
  20096. };
  20097. Plane.prototype.flip = function () {
  20098. this.normal.scaleInPlace(-1);
  20099. this.w = -this.w;
  20100. };
  20101. // Split `polygon` by this plane if needed, then put the polygon or polygon
  20102. // fragments in the appropriate lists. Coplanar polygons go into either
  20103. // `coplanarFront` or `coplanarBack` depending on their orientation with
  20104. // respect to this plane. Polygons in front or in back of this plane go into
  20105. // either `front` or `back`.
  20106. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  20107. var COPLANAR = 0;
  20108. var FRONT = 1;
  20109. var BACK = 2;
  20110. var SPANNING = 3;
  20111. // Classify each point as well as the entire polygon into one of the above
  20112. // four classes.
  20113. var polygonType = 0;
  20114. var types = [];
  20115. for (var i = 0; i < polygon.vertices.length; i++) {
  20116. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  20117. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  20118. polygonType |= type;
  20119. types.push(type);
  20120. }
  20121. switch (polygonType) {
  20122. case COPLANAR:
  20123. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  20124. break;
  20125. case FRONT:
  20126. front.push(polygon);
  20127. break;
  20128. case BACK:
  20129. back.push(polygon);
  20130. break;
  20131. case SPANNING:
  20132. var f = [], b = [];
  20133. for (i = 0; i < polygon.vertices.length; i++) {
  20134. var j = (i + 1) % polygon.vertices.length;
  20135. var ti = types[i], tj = types[j];
  20136. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  20137. if (ti != BACK)
  20138. f.push(vi);
  20139. if (ti != FRONT)
  20140. b.push(ti != BACK ? vi.clone() : vi);
  20141. if ((ti | tj) == SPANNING) {
  20142. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  20143. var v = vi.interpolate(vj, t);
  20144. f.push(v);
  20145. b.push(v.clone());
  20146. }
  20147. }
  20148. if (f.length >= 3) {
  20149. var poly = new Polygon(f, polygon.shared);
  20150. if (poly.plane)
  20151. front.push(poly);
  20152. }
  20153. if (b.length >= 3) {
  20154. poly = new Polygon(b, polygon.shared);
  20155. if (poly.plane)
  20156. back.push(poly);
  20157. }
  20158. break;
  20159. }
  20160. };
  20161. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  20162. // point is on the plane.
  20163. Plane.EPSILON = 1e-5;
  20164. return Plane;
  20165. })();
  20166. // # class Polygon
  20167. // Represents a convex polygon. The vertices used to initialize a polygon must
  20168. // be coplanar and form a convex loop.
  20169. //
  20170. // Each convex polygon has a `shared` property, which is shared between all
  20171. // polygons that are clones of each other or were split from the same polygon.
  20172. // This can be used to define per-polygon properties (such as surface color).
  20173. var Polygon = (function () {
  20174. function Polygon(vertices, shared) {
  20175. this.vertices = vertices;
  20176. this.shared = shared;
  20177. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  20178. }
  20179. Polygon.prototype.clone = function () {
  20180. var vertices = this.vertices.map(function (v) { return v.clone(); });
  20181. return new Polygon(vertices, this.shared);
  20182. };
  20183. Polygon.prototype.flip = function () {
  20184. this.vertices.reverse().map(function (v) {
  20185. v.flip();
  20186. });
  20187. this.plane.flip();
  20188. };
  20189. return Polygon;
  20190. })();
  20191. // # class Node
  20192. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  20193. // by picking a polygon to split along. That polygon (and all other coplanar
  20194. // polygons) are added directly to that node and the other polygons are added to
  20195. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  20196. // no distinction between internal and leaf nodes.
  20197. var Node = (function () {
  20198. function Node(polygons) {
  20199. this.plane = null;
  20200. this.front = null;
  20201. this.back = null;
  20202. this.polygons = [];
  20203. if (polygons) {
  20204. this.build(polygons);
  20205. }
  20206. }
  20207. Node.prototype.clone = function () {
  20208. var node = new Node();
  20209. node.plane = this.plane && this.plane.clone();
  20210. node.front = this.front && this.front.clone();
  20211. node.back = this.back && this.back.clone();
  20212. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  20213. return node;
  20214. };
  20215. // Convert solid space to empty space and empty space to solid space.
  20216. Node.prototype.invert = function () {
  20217. for (var i = 0; i < this.polygons.length; i++) {
  20218. this.polygons[i].flip();
  20219. }
  20220. if (this.plane) {
  20221. this.plane.flip();
  20222. }
  20223. if (this.front) {
  20224. this.front.invert();
  20225. }
  20226. if (this.back) {
  20227. this.back.invert();
  20228. }
  20229. var temp = this.front;
  20230. this.front = this.back;
  20231. this.back = temp;
  20232. };
  20233. // Recursively remove all polygons in `polygons` that are inside this BSP
  20234. // tree.
  20235. Node.prototype.clipPolygons = function (polygons) {
  20236. if (!this.plane)
  20237. return polygons.slice();
  20238. var front = [], back = [];
  20239. for (var i = 0; i < polygons.length; i++) {
  20240. this.plane.splitPolygon(polygons[i], front, back, front, back);
  20241. }
  20242. if (this.front) {
  20243. front = this.front.clipPolygons(front);
  20244. }
  20245. if (this.back) {
  20246. back = this.back.clipPolygons(back);
  20247. }
  20248. else {
  20249. back = [];
  20250. }
  20251. return front.concat(back);
  20252. };
  20253. // Remove all polygons in this BSP tree that are inside the other BSP tree
  20254. // `bsp`.
  20255. Node.prototype.clipTo = function (bsp) {
  20256. this.polygons = bsp.clipPolygons(this.polygons);
  20257. if (this.front)
  20258. this.front.clipTo(bsp);
  20259. if (this.back)
  20260. this.back.clipTo(bsp);
  20261. };
  20262. // Return a list of all polygons in this BSP tree.
  20263. Node.prototype.allPolygons = function () {
  20264. var polygons = this.polygons.slice();
  20265. if (this.front)
  20266. polygons = polygons.concat(this.front.allPolygons());
  20267. if (this.back)
  20268. polygons = polygons.concat(this.back.allPolygons());
  20269. return polygons;
  20270. };
  20271. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20272. // new polygons are filtered down to the bottom of the tree and become new
  20273. // nodes there. Each set of polygons is partitioned using the first polygon
  20274. // (no heuristic is used to pick a good split).
  20275. Node.prototype.build = function (polygons) {
  20276. if (!polygons.length)
  20277. return;
  20278. if (!this.plane)
  20279. this.plane = polygons[0].plane.clone();
  20280. var front = [], back = [];
  20281. for (var i = 0; i < polygons.length; i++) {
  20282. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20283. }
  20284. if (front.length) {
  20285. if (!this.front)
  20286. this.front = new Node();
  20287. this.front.build(front);
  20288. }
  20289. if (back.length) {
  20290. if (!this.back)
  20291. this.back = new Node();
  20292. this.back.build(back);
  20293. }
  20294. };
  20295. return Node;
  20296. })();
  20297. var CSG = (function () {
  20298. function CSG() {
  20299. this.polygons = new Array();
  20300. }
  20301. // Convert BABYLON.Mesh to BABYLON.CSG
  20302. CSG.FromMesh = function (mesh) {
  20303. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20304. if (mesh instanceof BABYLON.Mesh) {
  20305. mesh.computeWorldMatrix(true);
  20306. var matrix = mesh.getWorldMatrix();
  20307. var meshPosition = mesh.position.clone();
  20308. var meshRotation = mesh.rotation.clone();
  20309. var meshScaling = mesh.scaling.clone();
  20310. }
  20311. else {
  20312. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20313. }
  20314. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20315. var subMeshes = mesh.subMeshes;
  20316. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20317. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20318. vertices = [];
  20319. for (var j = 0; j < 3; j++) {
  20320. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20321. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20322. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20323. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20324. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20325. vertex = new Vertex(position, normal, uv);
  20326. vertices.push(vertex);
  20327. }
  20328. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20329. // To handle the case of degenerated triangle
  20330. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20331. if (polygon.plane)
  20332. polygons.push(polygon);
  20333. }
  20334. }
  20335. var csg = CSG.FromPolygons(polygons);
  20336. csg.matrix = matrix;
  20337. csg.position = meshPosition;
  20338. csg.rotation = meshRotation;
  20339. csg.scaling = meshScaling;
  20340. currentCSGMeshId++;
  20341. return csg;
  20342. };
  20343. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20344. CSG.FromPolygons = function (polygons) {
  20345. var csg = new BABYLON.CSG();
  20346. csg.polygons = polygons;
  20347. return csg;
  20348. };
  20349. CSG.prototype.clone = function () {
  20350. var csg = new BABYLON.CSG();
  20351. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20352. csg.copyTransformAttributes(this);
  20353. return csg;
  20354. };
  20355. CSG.prototype.toPolygons = function () {
  20356. return this.polygons;
  20357. };
  20358. CSG.prototype.union = function (csg) {
  20359. var a = new Node(this.clone().polygons);
  20360. var b = new Node(csg.clone().polygons);
  20361. a.clipTo(b);
  20362. b.clipTo(a);
  20363. b.invert();
  20364. b.clipTo(a);
  20365. b.invert();
  20366. a.build(b.allPolygons());
  20367. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20368. };
  20369. CSG.prototype.unionInPlace = function (csg) {
  20370. var a = new Node(this.polygons);
  20371. var b = new Node(csg.polygons);
  20372. a.clipTo(b);
  20373. b.clipTo(a);
  20374. b.invert();
  20375. b.clipTo(a);
  20376. b.invert();
  20377. a.build(b.allPolygons());
  20378. this.polygons = a.allPolygons();
  20379. };
  20380. CSG.prototype.subtract = function (csg) {
  20381. var a = new Node(this.clone().polygons);
  20382. var b = new Node(csg.clone().polygons);
  20383. a.invert();
  20384. a.clipTo(b);
  20385. b.clipTo(a);
  20386. b.invert();
  20387. b.clipTo(a);
  20388. b.invert();
  20389. a.build(b.allPolygons());
  20390. a.invert();
  20391. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20392. };
  20393. CSG.prototype.subtractInPlace = function (csg) {
  20394. var a = new Node(this.polygons);
  20395. var b = new Node(csg.polygons);
  20396. a.invert();
  20397. a.clipTo(b);
  20398. b.clipTo(a);
  20399. b.invert();
  20400. b.clipTo(a);
  20401. b.invert();
  20402. a.build(b.allPolygons());
  20403. a.invert();
  20404. this.polygons = a.allPolygons();
  20405. };
  20406. CSG.prototype.intersect = function (csg) {
  20407. var a = new Node(this.clone().polygons);
  20408. var b = new Node(csg.clone().polygons);
  20409. a.invert();
  20410. b.clipTo(a);
  20411. b.invert();
  20412. a.clipTo(b);
  20413. b.clipTo(a);
  20414. a.build(b.allPolygons());
  20415. a.invert();
  20416. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20417. };
  20418. CSG.prototype.intersectInPlace = function (csg) {
  20419. var a = new Node(this.polygons);
  20420. var b = new Node(csg.polygons);
  20421. a.invert();
  20422. b.clipTo(a);
  20423. b.invert();
  20424. a.clipTo(b);
  20425. b.clipTo(a);
  20426. a.build(b.allPolygons());
  20427. a.invert();
  20428. this.polygons = a.allPolygons();
  20429. };
  20430. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20431. // not modified.
  20432. CSG.prototype.inverse = function () {
  20433. var csg = this.clone();
  20434. csg.inverseInPlace();
  20435. return csg;
  20436. };
  20437. CSG.prototype.inverseInPlace = function () {
  20438. this.polygons.map(function (p) {
  20439. p.flip();
  20440. });
  20441. };
  20442. // This is used to keep meshes transformations so they can be restored
  20443. // when we build back a Babylon Mesh
  20444. // NB : All CSG operations are performed in world coordinates
  20445. CSG.prototype.copyTransformAttributes = function (csg) {
  20446. this.matrix = csg.matrix;
  20447. this.position = csg.position;
  20448. this.rotation = csg.rotation;
  20449. this.scaling = csg.scaling;
  20450. return this;
  20451. };
  20452. // Build Raw mesh from CSG
  20453. // Coordinates here are in world space
  20454. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20455. var matrix = this.matrix.clone();
  20456. matrix.invert();
  20457. 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;
  20458. if (keepSubMeshes) {
  20459. // Sort Polygons, since subMeshes are indices range
  20460. polygons.sort(function (a, b) {
  20461. if (a.shared.meshId === b.shared.meshId) {
  20462. return a.shared.subMeshId - b.shared.subMeshId;
  20463. }
  20464. else {
  20465. return a.shared.meshId - b.shared.meshId;
  20466. }
  20467. });
  20468. }
  20469. for (var i = 0, il = polygons.length; i < il; i++) {
  20470. polygon = polygons[i];
  20471. // Building SubMeshes
  20472. if (!subMesh_dict[polygon.shared.meshId]) {
  20473. subMesh_dict[polygon.shared.meshId] = {};
  20474. }
  20475. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20476. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20477. indexStart: +Infinity,
  20478. indexEnd: -Infinity,
  20479. materialIndex: polygon.shared.materialIndex
  20480. };
  20481. }
  20482. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20483. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20484. polygonIndices[0] = 0;
  20485. polygonIndices[1] = j - 1;
  20486. polygonIndices[2] = j;
  20487. for (var k = 0; k < 3; k++) {
  20488. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20489. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20490. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20491. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20492. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20493. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20494. // Check if 2 points can be merged
  20495. 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)) {
  20496. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20497. uvs.push(uv.x, uv.y);
  20498. normals.push(normal.x, normal.y, normal.z);
  20499. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20500. }
  20501. indices.push(vertex_idx);
  20502. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20503. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20504. currentIndex++;
  20505. }
  20506. }
  20507. }
  20508. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20509. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20510. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20511. mesh.setIndices(indices);
  20512. if (keepSubMeshes) {
  20513. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20514. var materialIndexOffset = 0, materialMaxIndex;
  20515. mesh.subMeshes.length = 0;
  20516. for (var m in subMesh_dict) {
  20517. materialMaxIndex = -1;
  20518. for (var sm in subMesh_dict[m]) {
  20519. subMesh_obj = subMesh_dict[m][sm];
  20520. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20521. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20522. }
  20523. materialIndexOffset += ++materialMaxIndex;
  20524. }
  20525. }
  20526. return mesh;
  20527. };
  20528. // Build Mesh from CSG taking material and transforms into account
  20529. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20530. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20531. mesh.material = material;
  20532. mesh.position.copyFrom(this.position);
  20533. mesh.rotation.copyFrom(this.rotation);
  20534. mesh.scaling.copyFrom(this.scaling);
  20535. mesh.computeWorldMatrix(true);
  20536. return mesh;
  20537. };
  20538. return CSG;
  20539. })();
  20540. BABYLON.CSG = CSG;
  20541. })(BABYLON || (BABYLON = {}));
  20542. //# sourceMappingURL=babylon.csg.js.map
  20543. var BABYLON;
  20544. (function (BABYLON) {
  20545. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20546. __extends(OculusDistortionCorrectionPostProcess, _super);
  20547. //ANY
  20548. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20549. var _this = this;
  20550. _super.call(this, name, "oculusDistortionCorrection", [
  20551. 'LensCenter',
  20552. 'Scale',
  20553. 'ScaleIn',
  20554. 'HmdWarpParam'
  20555. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20556. this._isRightEye = isRightEye;
  20557. this._distortionFactors = cameraSettings.DistortionK;
  20558. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20559. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20560. this.onSizeChanged = function () {
  20561. _this.aspectRatio = _this.width * .5 / _this.height;
  20562. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20563. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20564. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20565. };
  20566. this.onApply = function (effect) {
  20567. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20568. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20569. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20570. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20571. };
  20572. }
  20573. return OculusDistortionCorrectionPostProcess;
  20574. })(BABYLON.PostProcess);
  20575. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20576. })(BABYLON || (BABYLON = {}));
  20577. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20578. // 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
  20579. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20580. var BABYLON;
  20581. (function (BABYLON) {
  20582. (function (JoystickAxis) {
  20583. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20584. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20585. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20586. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20587. var JoystickAxis = BABYLON.JoystickAxis;
  20588. var VirtualJoystick = (function () {
  20589. function VirtualJoystick(leftJoystick) {
  20590. var _this = this;
  20591. if (leftJoystick) {
  20592. this._leftJoystick = true;
  20593. }
  20594. else {
  20595. this._leftJoystick = false;
  20596. }
  20597. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20598. VirtualJoystick._globalJoystickIndex++;
  20599. // By default left & right arrow keys are moving the X
  20600. // and up & down keys are moving the Y
  20601. this._axisTargetedByLeftAndRight = 0 /* X */;
  20602. this._axisTargetedByUpAndDown = 1 /* Y */;
  20603. this.reverseLeftRight = false;
  20604. this.reverseUpDown = false;
  20605. // collections of pointers
  20606. this._touches = new BABYLON.VirtualJoystick.Collection();
  20607. this.deltaPosition = BABYLON.Vector3.Zero();
  20608. this._joystickSensibility = 25;
  20609. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20610. this._rotationSpeed = 25;
  20611. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20612. this._rotateOnAxisRelativeToMesh = false;
  20613. // injecting a canvas element on top of the canvas 3D game
  20614. if (!VirtualJoystick.vjCanvas) {
  20615. window.addEventListener("resize", function () {
  20616. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20617. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20618. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20619. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20620. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20621. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20622. }, false);
  20623. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20624. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20625. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20626. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20627. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20628. VirtualJoystick.vjCanvas.style.width = "100%";
  20629. VirtualJoystick.vjCanvas.style.height = "100%";
  20630. VirtualJoystick.vjCanvas.style.position = "absolute";
  20631. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20632. VirtualJoystick.vjCanvas.style.top = "0px";
  20633. VirtualJoystick.vjCanvas.style.left = "0px";
  20634. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20635. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20636. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20637. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20638. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20639. document.body.appendChild(VirtualJoystick.vjCanvas);
  20640. }
  20641. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20642. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20643. this.pressed = false;
  20644. // default joystick color
  20645. this._joystickColor = "cyan";
  20646. this._joystickPointerID = -1;
  20647. // current joystick position
  20648. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20649. // origin joystick position
  20650. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20651. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20652. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20653. _this._onPointerDown(evt);
  20654. }, false);
  20655. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20656. _this._onPointerMove(evt);
  20657. }, false);
  20658. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20659. _this._onPointerUp(evt);
  20660. }, false);
  20661. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20662. _this._onPointerUp(evt);
  20663. }, false);
  20664. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20665. evt.preventDefault(); // Disables system menu
  20666. }, false);
  20667. requestAnimationFrame(function () {
  20668. _this._drawVirtualJoystick();
  20669. });
  20670. }
  20671. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20672. this._joystickSensibility = newJoystickSensibility;
  20673. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20674. };
  20675. VirtualJoystick.prototype._onPointerDown = function (e) {
  20676. var positionOnScreenCondition;
  20677. e.preventDefault();
  20678. if (this._leftJoystick === true) {
  20679. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20680. }
  20681. else {
  20682. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20683. }
  20684. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20685. // First contact will be dedicated to the virtual joystick
  20686. this._joystickPointerID = e.pointerId;
  20687. this._joystickPointerStartPos.x = e.clientX;
  20688. this._joystickPointerStartPos.y = e.clientY;
  20689. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20690. this._deltaJoystickVector.x = 0;
  20691. this._deltaJoystickVector.y = 0;
  20692. this.pressed = true;
  20693. this._touches.add(e.pointerId.toString(), e);
  20694. }
  20695. else {
  20696. // You can only trigger the action buttons with a joystick declared
  20697. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20698. this._action();
  20699. this._touches.add(e.pointerId.toString(), e);
  20700. }
  20701. }
  20702. };
  20703. VirtualJoystick.prototype._onPointerMove = function (e) {
  20704. // If the current pointer is the one associated to the joystick (first touch contact)
  20705. if (this._joystickPointerID == e.pointerId) {
  20706. this._joystickPointerPos.x = e.clientX;
  20707. this._joystickPointerPos.y = e.clientY;
  20708. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20709. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20710. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20711. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20712. switch (this._axisTargetedByLeftAndRight) {
  20713. case 0 /* X */:
  20714. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20715. break;
  20716. case 1 /* Y */:
  20717. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20718. break;
  20719. case 2 /* Z */:
  20720. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20721. break;
  20722. }
  20723. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20724. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20725. switch (this._axisTargetedByUpAndDown) {
  20726. case 0 /* X */:
  20727. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20728. break;
  20729. case 1 /* Y */:
  20730. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20731. break;
  20732. case 2 /* Z */:
  20733. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20734. break;
  20735. }
  20736. }
  20737. else {
  20738. if (this._touches.item(e.pointerId.toString())) {
  20739. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20740. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20741. }
  20742. }
  20743. };
  20744. VirtualJoystick.prototype._onPointerUp = function (e) {
  20745. this._clearCanvas();
  20746. if (this._joystickPointerID == e.pointerId) {
  20747. this._joystickPointerID = -1;
  20748. this.pressed = false;
  20749. }
  20750. this._deltaJoystickVector.x = 0;
  20751. this._deltaJoystickVector.y = 0;
  20752. this._touches.remove(e.pointerId.toString());
  20753. };
  20754. /**
  20755. * Change the color of the virtual joystick
  20756. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20757. */
  20758. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20759. this._joystickColor = newColor;
  20760. };
  20761. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20762. this._action = action;
  20763. };
  20764. // Define which axis you'd like to control for left & right
  20765. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20766. switch (axis) {
  20767. case 0 /* X */:
  20768. case 1 /* Y */:
  20769. case 2 /* Z */:
  20770. this._axisTargetedByLeftAndRight = axis;
  20771. break;
  20772. default:
  20773. this._axisTargetedByLeftAndRight = 0 /* X */;
  20774. break;
  20775. }
  20776. };
  20777. // Define which axis you'd like to control for up & down
  20778. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20779. switch (axis) {
  20780. case 0 /* X */:
  20781. case 1 /* Y */:
  20782. case 2 /* Z */:
  20783. this._axisTargetedByUpAndDown = axis;
  20784. break;
  20785. default:
  20786. this._axisTargetedByUpAndDown = 1 /* Y */;
  20787. break;
  20788. }
  20789. };
  20790. VirtualJoystick.prototype._clearCanvas = function () {
  20791. if (this._leftJoystick) {
  20792. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20793. }
  20794. else {
  20795. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20796. }
  20797. };
  20798. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20799. var _this = this;
  20800. if (this.pressed) {
  20801. this._clearCanvas();
  20802. this._touches.forEach(function (touch) {
  20803. if (touch.pointerId === _this._joystickPointerID) {
  20804. VirtualJoystick.vjCanvasContext.beginPath();
  20805. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20806. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20807. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20808. VirtualJoystick.vjCanvasContext.stroke();
  20809. VirtualJoystick.vjCanvasContext.beginPath();
  20810. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20811. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20812. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20813. VirtualJoystick.vjCanvasContext.stroke();
  20814. VirtualJoystick.vjCanvasContext.beginPath();
  20815. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20816. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20817. VirtualJoystick.vjCanvasContext.stroke();
  20818. }
  20819. else {
  20820. VirtualJoystick.vjCanvasContext.beginPath();
  20821. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20822. VirtualJoystick.vjCanvasContext.beginPath();
  20823. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20824. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20825. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20826. VirtualJoystick.vjCanvasContext.stroke();
  20827. }
  20828. ;
  20829. });
  20830. }
  20831. requestAnimationFrame(function () {
  20832. _this._drawVirtualJoystick();
  20833. });
  20834. };
  20835. VirtualJoystick.prototype.releaseCanvas = function () {
  20836. if (VirtualJoystick.vjCanvas) {
  20837. document.body.removeChild(VirtualJoystick.vjCanvas);
  20838. VirtualJoystick.vjCanvas = null;
  20839. }
  20840. };
  20841. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20842. VirtualJoystick._globalJoystickIndex = 0;
  20843. return VirtualJoystick;
  20844. })();
  20845. BABYLON.VirtualJoystick = VirtualJoystick;
  20846. })(BABYLON || (BABYLON = {}));
  20847. var BABYLON;
  20848. (function (BABYLON) {
  20849. var VirtualJoystick;
  20850. (function (VirtualJoystick) {
  20851. var Collection = (function () {
  20852. function Collection() {
  20853. this._count = 0;
  20854. this._collection = new Array();
  20855. }
  20856. Collection.prototype.Count = function () {
  20857. return this._count;
  20858. };
  20859. Collection.prototype.add = function (key, item) {
  20860. if (this._collection[key] != undefined) {
  20861. return undefined;
  20862. }
  20863. this._collection[key] = item;
  20864. return ++this._count;
  20865. };
  20866. Collection.prototype.remove = function (key) {
  20867. if (this._collection[key] == undefined) {
  20868. return undefined;
  20869. }
  20870. delete this._collection[key];
  20871. return --this._count;
  20872. };
  20873. Collection.prototype.item = function (key) {
  20874. return this._collection[key];
  20875. };
  20876. Collection.prototype.forEach = function (block) {
  20877. var key;
  20878. for (key in this._collection) {
  20879. if (this._collection.hasOwnProperty(key)) {
  20880. block(this._collection[key]);
  20881. }
  20882. }
  20883. };
  20884. return Collection;
  20885. })();
  20886. VirtualJoystick.Collection = Collection;
  20887. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20888. })(BABYLON || (BABYLON = {}));
  20889. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20890. var BABYLON;
  20891. (function (BABYLON) {
  20892. var OculusRiftDevKit2013_Metric = {
  20893. HResolution: 1280,
  20894. VResolution: 800,
  20895. HScreenSize: 0.149759993,
  20896. VScreenSize: 0.0935999975,
  20897. VScreenCenter: 0.0467999987,
  20898. EyeToScreenDistance: 0.0410000011,
  20899. LensSeparationDistance: 0.0635000020,
  20900. InterpupillaryDistance: 0.0640000030,
  20901. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20902. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20903. PostProcessScaleFactor: 1.714605507808412,
  20904. LensCenterOffset: 0.151976421
  20905. };
  20906. var _OculusInnerCamera = (function (_super) {
  20907. __extends(_OculusInnerCamera, _super);
  20908. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20909. _super.call(this, name, position, scene);
  20910. this._workMatrix = new BABYLON.Matrix();
  20911. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20912. // Constants
  20913. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20914. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20915. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20916. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20917. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20918. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20919. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20920. // Postprocess
  20921. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20922. }
  20923. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20924. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20925. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20926. return this._projectionMatrix;
  20927. };
  20928. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20929. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20930. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20931. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20932. // Computing target and final matrix
  20933. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20934. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20935. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20936. return this._viewMatrix;
  20937. };
  20938. return _OculusInnerCamera;
  20939. })(BABYLON.FreeCamera);
  20940. var OculusCamera = (function (_super) {
  20941. __extends(OculusCamera, _super);
  20942. function OculusCamera(name, position, scene) {
  20943. _super.call(this, name, position, scene);
  20944. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20945. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20946. this.subCameras.push(this._leftCamera);
  20947. this.subCameras.push(this._rightCamera);
  20948. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20949. }
  20950. OculusCamera.prototype._update = function () {
  20951. this._leftCamera.position.copyFrom(this.position);
  20952. this._rightCamera.position.copyFrom(this.position);
  20953. this._updateCamera(this._leftCamera);
  20954. this._updateCamera(this._rightCamera);
  20955. _super.prototype._update.call(this);
  20956. };
  20957. OculusCamera.prototype._updateCamera = function (camera) {
  20958. camera.minZ = this.minZ;
  20959. camera.maxZ = this.maxZ;
  20960. camera.rotation.x = this.rotation.x;
  20961. camera.rotation.y = this.rotation.y;
  20962. camera.rotation.z = this.rotation.z;
  20963. };
  20964. // Oculus events
  20965. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20966. var yaw = evt.alpha / 180 * Math.PI;
  20967. var pitch = evt.beta / 180 * Math.PI;
  20968. var roll = evt.gamma / 180 * Math.PI;
  20969. if (!this._offsetOrientation) {
  20970. this._offsetOrientation = {
  20971. yaw: yaw,
  20972. pitch: pitch,
  20973. roll: roll
  20974. };
  20975. return;
  20976. }
  20977. else {
  20978. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20979. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20980. this.rotation.z += this._offsetOrientation.roll - roll;
  20981. this._offsetOrientation.yaw = yaw;
  20982. this._offsetOrientation.pitch = pitch;
  20983. this._offsetOrientation.roll = roll;
  20984. }
  20985. };
  20986. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20987. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20988. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20989. };
  20990. OculusCamera.prototype.detachControl = function (element) {
  20991. _super.prototype.detachControl.call(this, element);
  20992. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20993. };
  20994. return OculusCamera;
  20995. })(BABYLON.FreeCamera);
  20996. BABYLON.OculusCamera = OculusCamera;
  20997. })(BABYLON || (BABYLON = {}));
  20998. //# sourceMappingURL=babylon.oculusCamera.js.map
  20999. var BABYLON;
  21000. (function (BABYLON) {
  21001. var OculusRiftDevKit2013_Metric = {
  21002. HResolution: 1280,
  21003. VResolution: 800,
  21004. HScreenSize: 0.149759993,
  21005. VScreenSize: 0.0935999975,
  21006. VScreenCenter: 0.0467999987,
  21007. EyeToScreenDistance: 0.0410000011,
  21008. LensSeparationDistance: 0.0635000020,
  21009. InterpupillaryDistance: 0.0640000030,
  21010. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  21011. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  21012. PostProcessScaleFactor: 1.714605507808412,
  21013. LensCenterOffset: 0.151976421
  21014. };
  21015. var _OculusInnerGamepadCamera = (function (_super) {
  21016. __extends(_OculusInnerGamepadCamera, _super);
  21017. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  21018. _super.call(this, name, position, scene);
  21019. this._workMatrix = new BABYLON.Matrix();
  21020. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  21021. // Constants
  21022. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  21023. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  21024. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  21025. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  21026. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  21027. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  21028. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  21029. // Postprocess
  21030. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  21031. }
  21032. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  21033. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  21034. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  21035. return this._projectionMatrix;
  21036. };
  21037. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  21038. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  21039. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  21040. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  21041. // Computing target and final matrix
  21042. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  21043. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  21044. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  21045. return this._viewMatrix;
  21046. };
  21047. return _OculusInnerGamepadCamera;
  21048. })(BABYLON.FreeCamera);
  21049. var OculusGamepadCamera = (function (_super) {
  21050. __extends(OculusGamepadCamera, _super);
  21051. function OculusGamepadCamera(name, position, scene) {
  21052. var _this = this;
  21053. _super.call(this, name, position, scene);
  21054. this.angularSensibility = 200;
  21055. this.moveSensibility = 75;
  21056. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  21057. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  21058. this.subCameras.push(this._leftCamera);
  21059. this.subCameras.push(this._rightCamera);
  21060. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  21061. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  21062. _this._onNewGameConnected(gamepad);
  21063. });
  21064. }
  21065. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  21066. // Only the first gamepad can control the camera
  21067. if (gamepad.index === 0) {
  21068. this._gamepad = gamepad;
  21069. }
  21070. };
  21071. OculusGamepadCamera.prototype._update = function () {
  21072. this._leftCamera.position.copyFrom(this.position);
  21073. this._rightCamera.position.copyFrom(this.position);
  21074. this._updateCamera(this._leftCamera);
  21075. this._updateCamera(this._rightCamera);
  21076. _super.prototype._update.call(this);
  21077. };
  21078. OculusGamepadCamera.prototype._checkInputs = function () {
  21079. if (!this._gamepad) {
  21080. return;
  21081. }
  21082. var LSValues = this._gamepad.leftStick;
  21083. var normalizedLX = LSValues.x / this.moveSensibility;
  21084. var normalizedLY = LSValues.y / this.moveSensibility;
  21085. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  21086. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  21087. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21088. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  21089. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21090. };
  21091. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  21092. camera.minZ = this.minZ;
  21093. camera.maxZ = this.maxZ;
  21094. camera.rotation.x = this.rotation.x;
  21095. camera.rotation.y = this.rotation.y;
  21096. camera.rotation.z = this.rotation.z;
  21097. };
  21098. // Oculus events
  21099. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  21100. var yaw = evt.alpha / 180 * Math.PI;
  21101. var pitch = evt.beta / 180 * Math.PI;
  21102. var roll = evt.gamma / 180 * Math.PI;
  21103. if (!this._offsetOrientation) {
  21104. this._offsetOrientation = {
  21105. yaw: yaw,
  21106. pitch: pitch,
  21107. roll: roll
  21108. };
  21109. return;
  21110. }
  21111. else {
  21112. this.rotation.y += yaw - this._offsetOrientation.yaw;
  21113. this.rotation.x += pitch - this._offsetOrientation.pitch;
  21114. this.rotation.z += this._offsetOrientation.roll - roll;
  21115. this._offsetOrientation.yaw = yaw;
  21116. this._offsetOrientation.pitch = pitch;
  21117. this._offsetOrientation.roll = roll;
  21118. }
  21119. };
  21120. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  21121. _super.prototype.attachControl.call(this, element, noPreventDefault);
  21122. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  21123. };
  21124. OculusGamepadCamera.prototype.detachControl = function (element) {
  21125. _super.prototype.detachControl.call(this, element);
  21126. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  21127. };
  21128. OculusGamepadCamera.prototype.dispose = function () {
  21129. this._gamepads.dispose();
  21130. _super.prototype.dispose.call(this);
  21131. };
  21132. return OculusGamepadCamera;
  21133. })(BABYLON.FreeCamera);
  21134. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  21135. })(BABYLON || (BABYLON = {}));
  21136. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  21137. var BABYLON;
  21138. (function (BABYLON) {
  21139. // We're mainly based on the logic defined into the FreeCamera code
  21140. var VirtualJoysticksCamera = (function (_super) {
  21141. __extends(VirtualJoysticksCamera, _super);
  21142. function VirtualJoysticksCamera(name, position, scene) {
  21143. _super.call(this, name, position, scene);
  21144. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  21145. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  21146. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  21147. this._leftjoystick.setJoystickSensibility(0.15);
  21148. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  21149. this._rightjoystick.setAxisForUpDown(0 /* X */);
  21150. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  21151. this._rightjoystick.reverseUpDown = true;
  21152. this._rightjoystick.setJoystickSensibility(0.05);
  21153. this._rightjoystick.setJoystickColor("yellow");
  21154. }
  21155. VirtualJoysticksCamera.prototype._checkInputs = function () {
  21156. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  21157. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  21158. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  21159. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  21160. if (!this._leftjoystick.pressed) {
  21161. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  21162. }
  21163. if (!this._rightjoystick.pressed) {
  21164. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  21165. }
  21166. };
  21167. VirtualJoysticksCamera.prototype.dispose = function () {
  21168. this._leftjoystick.releaseCanvas();
  21169. _super.prototype.dispose.call(this);
  21170. };
  21171. return VirtualJoysticksCamera;
  21172. })(BABYLON.FreeCamera);
  21173. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  21174. })(BABYLON || (BABYLON = {}));
  21175. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  21176. var BABYLON;
  21177. (function (BABYLON) {
  21178. var ShaderMaterial = (function (_super) {
  21179. __extends(ShaderMaterial, _super);
  21180. function ShaderMaterial(name, scene, shaderPath, options) {
  21181. _super.call(this, name, scene);
  21182. this._textures = new Array();
  21183. this._floats = new Array();
  21184. this._floatsArrays = {};
  21185. this._colors3 = new Array();
  21186. this._colors4 = new Array();
  21187. this._vectors2 = new Array();
  21188. this._vectors3 = new Array();
  21189. this._matrices = new Array();
  21190. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  21191. this._shaderPath = shaderPath;
  21192. options.needAlphaBlending = options.needAlphaBlending || false;
  21193. options.needAlphaTesting = options.needAlphaTesting || false;
  21194. options.attributes = options.attributes || ["position", "normal", "uv"];
  21195. options.uniforms = options.uniforms || ["worldViewProjection"];
  21196. options.samplers = options.samplers || [];
  21197. this._options = options;
  21198. }
  21199. ShaderMaterial.prototype.needAlphaBlending = function () {
  21200. return this._options.needAlphaBlending;
  21201. };
  21202. ShaderMaterial.prototype.needAlphaTesting = function () {
  21203. return this._options.needAlphaTesting;
  21204. };
  21205. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  21206. if (this._options.uniforms.indexOf(uniformName) === -1) {
  21207. this._options.uniforms.push(uniformName);
  21208. }
  21209. };
  21210. ShaderMaterial.prototype.setTexture = function (name, texture) {
  21211. if (this._options.samplers.indexOf(name) === -1) {
  21212. this._options.samplers.push(name);
  21213. }
  21214. this._textures[name] = texture;
  21215. return this;
  21216. };
  21217. ShaderMaterial.prototype.setFloat = function (name, value) {
  21218. this._checkUniform(name);
  21219. this._floats[name] = value;
  21220. return this;
  21221. };
  21222. ShaderMaterial.prototype.setFloats = function (name, value) {
  21223. this._checkUniform(name);
  21224. this._floatsArrays[name] = value;
  21225. return this;
  21226. };
  21227. ShaderMaterial.prototype.setColor3 = function (name, value) {
  21228. this._checkUniform(name);
  21229. this._colors3[name] = value;
  21230. return this;
  21231. };
  21232. ShaderMaterial.prototype.setColor4 = function (name, value) {
  21233. this._checkUniform(name);
  21234. this._colors4[name] = value;
  21235. return this;
  21236. };
  21237. ShaderMaterial.prototype.setVector2 = function (name, value) {
  21238. this._checkUniform(name);
  21239. this._vectors2[name] = value;
  21240. return this;
  21241. };
  21242. ShaderMaterial.prototype.setVector3 = function (name, value) {
  21243. this._checkUniform(name);
  21244. this._vectors3[name] = value;
  21245. return this;
  21246. };
  21247. ShaderMaterial.prototype.setMatrix = function (name, value) {
  21248. this._checkUniform(name);
  21249. this._matrices[name] = value;
  21250. return this;
  21251. };
  21252. ShaderMaterial.prototype.isReady = function () {
  21253. var scene = this.getScene();
  21254. var engine = scene.getEngine();
  21255. if (!this.checkReadyOnEveryCall) {
  21256. if (this._renderId === scene.getRenderId()) {
  21257. return true;
  21258. }
  21259. }
  21260. var previousEffect = this._effect;
  21261. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  21262. if (!this._effect.isReady()) {
  21263. return false;
  21264. }
  21265. if (previousEffect !== this._effect) {
  21266. scene.resetCachedMaterial();
  21267. }
  21268. this._renderId = scene.getRenderId();
  21269. return true;
  21270. };
  21271. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21272. var scene = this.getScene();
  21273. if (this._options.uniforms.indexOf("world") !== -1) {
  21274. this._effect.setMatrix("world", world);
  21275. }
  21276. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21277. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21278. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21279. }
  21280. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21281. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21282. }
  21283. };
  21284. ShaderMaterial.prototype.bind = function (world) {
  21285. // Std values
  21286. this.bindOnlyWorldMatrix(world);
  21287. if (this.getScene().getCachedMaterial() !== this) {
  21288. if (this._options.uniforms.indexOf("view") !== -1) {
  21289. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21290. }
  21291. if (this._options.uniforms.indexOf("projection") !== -1) {
  21292. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21293. }
  21294. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21295. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21296. }
  21297. for (var name in this._textures) {
  21298. this._effect.setTexture(name, this._textures[name]);
  21299. }
  21300. for (name in this._floats) {
  21301. this._effect.setFloat(name, this._floats[name]);
  21302. }
  21303. for (name in this._floatsArrays) {
  21304. this._effect.setArray(name, this._floatsArrays[name]);
  21305. }
  21306. for (name in this._colors3) {
  21307. this._effect.setColor3(name, this._colors3[name]);
  21308. }
  21309. for (name in this._colors4) {
  21310. var color = this._colors4[name];
  21311. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21312. }
  21313. for (name in this._vectors2) {
  21314. this._effect.setVector2(name, this._vectors2[name]);
  21315. }
  21316. for (name in this._vectors3) {
  21317. this._effect.setVector3(name, this._vectors3[name]);
  21318. }
  21319. for (name in this._matrices) {
  21320. this._effect.setMatrix(name, this._matrices[name]);
  21321. }
  21322. }
  21323. _super.prototype.bind.call(this, world, null);
  21324. };
  21325. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21326. for (var name in this._textures) {
  21327. this._textures[name].dispose();
  21328. }
  21329. this._textures = [];
  21330. _super.prototype.dispose.call(this, forceDisposeEffect);
  21331. };
  21332. return ShaderMaterial;
  21333. })(BABYLON.Material);
  21334. BABYLON.ShaderMaterial = ShaderMaterial;
  21335. })(BABYLON || (BABYLON = {}));
  21336. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21337. (function (BABYLON) {
  21338. var VertexData = (function () {
  21339. function VertexData() {
  21340. }
  21341. VertexData.prototype.set = function (data, kind) {
  21342. switch (kind) {
  21343. case BABYLON.VertexBuffer.PositionKind:
  21344. this.positions = data;
  21345. break;
  21346. case BABYLON.VertexBuffer.NormalKind:
  21347. this.normals = data;
  21348. break;
  21349. case BABYLON.VertexBuffer.UVKind:
  21350. this.uvs = data;
  21351. break;
  21352. case BABYLON.VertexBuffer.UV2Kind:
  21353. this.uv2s = data;
  21354. break;
  21355. case BABYLON.VertexBuffer.ColorKind:
  21356. this.colors = data;
  21357. break;
  21358. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21359. this.matricesIndices = data;
  21360. break;
  21361. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21362. this.matricesWeights = data;
  21363. break;
  21364. }
  21365. };
  21366. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21367. this._applyTo(mesh, updatable);
  21368. };
  21369. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21370. this._applyTo(geometry, updatable);
  21371. };
  21372. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21373. this._update(mesh);
  21374. };
  21375. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21376. this._update(geometry);
  21377. };
  21378. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21379. if (this.positions) {
  21380. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21381. }
  21382. if (this.normals) {
  21383. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21384. }
  21385. if (this.uvs) {
  21386. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21387. }
  21388. if (this.uv2s) {
  21389. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21390. }
  21391. if (this.colors) {
  21392. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21393. }
  21394. if (this.matricesIndices) {
  21395. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21396. }
  21397. if (this.matricesWeights) {
  21398. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21399. }
  21400. if (this.indices) {
  21401. meshOrGeometry.setIndices(this.indices);
  21402. }
  21403. };
  21404. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21405. if (this.positions) {
  21406. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21407. }
  21408. if (this.normals) {
  21409. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21410. }
  21411. if (this.uvs) {
  21412. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21413. }
  21414. if (this.uv2s) {
  21415. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21416. }
  21417. if (this.colors) {
  21418. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21419. }
  21420. if (this.matricesIndices) {
  21421. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21422. }
  21423. if (this.matricesWeights) {
  21424. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21425. }
  21426. if (this.indices) {
  21427. meshOrGeometry.setIndices(this.indices);
  21428. }
  21429. };
  21430. VertexData.prototype.transform = function (matrix) {
  21431. var transformed = BABYLON.Vector3.Zero();
  21432. if (this.positions) {
  21433. var position = BABYLON.Vector3.Zero();
  21434. for (var index = 0; index < this.positions.length; index += 3) {
  21435. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21436. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21437. this.positions[index] = transformed.x;
  21438. this.positions[index + 1] = transformed.y;
  21439. this.positions[index + 2] = transformed.z;
  21440. }
  21441. }
  21442. if (this.normals) {
  21443. var normal = BABYLON.Vector3.Zero();
  21444. for (index = 0; index < this.normals.length; index += 3) {
  21445. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21446. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21447. this.normals[index] = transformed.x;
  21448. this.normals[index + 1] = transformed.y;
  21449. this.normals[index + 2] = transformed.z;
  21450. }
  21451. }
  21452. };
  21453. VertexData.prototype.merge = function (other) {
  21454. if (other.indices) {
  21455. if (!this.indices) {
  21456. this.indices = [];
  21457. }
  21458. var offset = this.positions ? this.positions.length / 3 : 0;
  21459. for (var index = 0; index < other.indices.length; index++) {
  21460. this.indices.push(other.indices[index] + offset);
  21461. }
  21462. }
  21463. if (other.positions) {
  21464. if (!this.positions) {
  21465. this.positions = [];
  21466. }
  21467. for (index = 0; index < other.positions.length; index++) {
  21468. this.positions.push(other.positions[index]);
  21469. }
  21470. }
  21471. if (other.normals) {
  21472. if (!this.normals) {
  21473. this.normals = [];
  21474. }
  21475. for (index = 0; index < other.normals.length; index++) {
  21476. this.normals.push(other.normals[index]);
  21477. }
  21478. }
  21479. if (other.uvs) {
  21480. if (!this.uvs) {
  21481. this.uvs = [];
  21482. }
  21483. for (index = 0; index < other.uvs.length; index++) {
  21484. this.uvs.push(other.uvs[index]);
  21485. }
  21486. }
  21487. if (other.uv2s) {
  21488. if (!this.uv2s) {
  21489. this.uv2s = [];
  21490. }
  21491. for (index = 0; index < other.uv2s.length; index++) {
  21492. this.uv2s.push(other.uv2s[index]);
  21493. }
  21494. }
  21495. if (other.matricesIndices) {
  21496. if (!this.matricesIndices) {
  21497. this.matricesIndices = [];
  21498. }
  21499. for (index = 0; index < other.matricesIndices.length; index++) {
  21500. this.matricesIndices.push(other.matricesIndices[index]);
  21501. }
  21502. }
  21503. if (other.matricesWeights) {
  21504. if (!this.matricesWeights) {
  21505. this.matricesWeights = [];
  21506. }
  21507. for (index = 0; index < other.matricesWeights.length; index++) {
  21508. this.matricesWeights.push(other.matricesWeights[index]);
  21509. }
  21510. }
  21511. if (other.colors) {
  21512. if (!this.colors) {
  21513. this.colors = [];
  21514. }
  21515. for (index = 0; index < other.colors.length; index++) {
  21516. this.colors.push(other.colors[index]);
  21517. }
  21518. }
  21519. };
  21520. // Statics
  21521. VertexData.ExtractFromMesh = function (mesh) {
  21522. return VertexData._ExtractFrom(mesh);
  21523. };
  21524. VertexData.ExtractFromGeometry = function (geometry) {
  21525. return VertexData._ExtractFrom(geometry);
  21526. };
  21527. VertexData._ExtractFrom = function (meshOrGeometry) {
  21528. var result = new VertexData();
  21529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21530. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21531. }
  21532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21533. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21534. }
  21535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21536. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21537. }
  21538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21539. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21540. }
  21541. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21542. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21543. }
  21544. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21545. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21546. }
  21547. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21548. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21549. }
  21550. result.indices = meshOrGeometry.getIndices();
  21551. return result;
  21552. };
  21553. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21554. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21555. closeArray = closeArray || false;
  21556. closePath = closePath || false;
  21557. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21558. offset = offset || defaultOffset;
  21559. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21560. var positions = [];
  21561. var indices = [];
  21562. var normals = [];
  21563. var uvs = [];
  21564. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21565. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21566. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21567. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21568. var minlg; // minimal length among all paths from pathArray
  21569. var lg = []; // array of path lengths : nb of vertex per path
  21570. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21571. var p; // path iterator
  21572. var i; // point iterator
  21573. var j; // point iterator
  21574. // if single path in pathArray
  21575. if (pathArray.length < 2) {
  21576. var ar1 = [];
  21577. var ar2 = [];
  21578. for (i = 0; i < pathArray[0].length - offset; i++) {
  21579. ar1.push(pathArray[0][i]);
  21580. ar2.push(pathArray[0][i + offset]);
  21581. }
  21582. pathArray = [ar1, ar2];
  21583. }
  21584. // positions and horizontal distances (u)
  21585. var idc = 0;
  21586. minlg = pathArray[0].length;
  21587. for (p = 0; p < pathArray.length; p++) {
  21588. uTotalDistance[p] = 0;
  21589. us[p] = [0];
  21590. var path = pathArray[p];
  21591. var l = path.length;
  21592. minlg = (minlg < l) ? minlg : l;
  21593. lg[p] = l;
  21594. idx[p] = idc;
  21595. j = 0;
  21596. while (j < l) {
  21597. positions.push(path[j].x, path[j].y, path[j].z);
  21598. if (j > 0) {
  21599. var vectlg = path[j].subtract(path[j - 1]).length();
  21600. var dist = vectlg + uTotalDistance[p];
  21601. us[p].push(dist);
  21602. uTotalDistance[p] = dist;
  21603. }
  21604. j++;
  21605. }
  21606. if (closePath) {
  21607. vectlg = path[0].subtract(path[j - 1]).length();
  21608. dist = vectlg + uTotalDistance[p];
  21609. uTotalDistance[p] = dist;
  21610. }
  21611. idc += l;
  21612. }
  21613. for (i = 0; i < minlg; i++) {
  21614. vTotalDistance[i] = 0;
  21615. vs[i] = [0];
  21616. var path1;
  21617. var path2;
  21618. for (p = 0; p < pathArray.length - 1; p++) {
  21619. path1 = pathArray[p];
  21620. path2 = pathArray[p + 1];
  21621. vectlg = path2[i].subtract(path1[i]).length();
  21622. dist = vectlg + vTotalDistance[i];
  21623. vs[i].push(dist);
  21624. vTotalDistance[i] = dist;
  21625. }
  21626. if (closeArray) {
  21627. path1 = pathArray[p];
  21628. path2 = pathArray[0];
  21629. vectlg = path2[i].subtract(path1[i]).length();
  21630. dist = vectlg + vTotalDistance[i];
  21631. vTotalDistance[i] = dist;
  21632. }
  21633. }
  21634. // uvs
  21635. var u;
  21636. var v;
  21637. for (p = 0; p < pathArray.length; p++) {
  21638. for (i = 0; i < minlg; i++) {
  21639. u = us[p][i] / uTotalDistance[p];
  21640. v = vs[i][p] / vTotalDistance[i];
  21641. uvs.push(u, v);
  21642. }
  21643. }
  21644. // indices
  21645. p = 0; // path index
  21646. var pi = 0; // positions array index
  21647. var l1 = lg[p] - 1; // path1 length
  21648. var l2 = lg[p + 1] - 1; // path2 length
  21649. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21650. var shft = idx[1] - idx[0]; // shift
  21651. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21652. var t1; // two consecutive triangles, so 4 points : point1
  21653. var t2; // point2
  21654. var t3; // point3
  21655. var t4; // point4
  21656. while (pi <= min && p < path1nb) {
  21657. // 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
  21658. t1 = pi;
  21659. t2 = pi + shft;
  21660. t3 = pi + 1;
  21661. t4 = pi + shft + 1;
  21662. indices.push(pi, pi + shft, pi + 1);
  21663. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21664. pi += 1;
  21665. if (pi === min) {
  21666. if (closePath) {
  21667. indices.push(pi, pi + shft, idx[p]);
  21668. indices.push(idx[p] + shft, idx[p], pi + shft);
  21669. t3 = idx[p];
  21670. t4 = idx[p] + shft;
  21671. }
  21672. p++;
  21673. if (p === lg.length - 1) {
  21674. shft = idx[0] - idx[p];
  21675. l1 = lg[p] - 1;
  21676. l2 = lg[0] - 1;
  21677. }
  21678. else {
  21679. shft = idx[p + 1] - idx[p];
  21680. l1 = lg[p] - 1;
  21681. l2 = lg[p + 1] - 1;
  21682. }
  21683. pi = idx[p];
  21684. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21685. }
  21686. }
  21687. // normals
  21688. VertexData.ComputeNormals(positions, indices, normals);
  21689. // sides
  21690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21691. // Result
  21692. var vertexData = new VertexData();
  21693. vertexData.indices = indices;
  21694. vertexData.positions = positions;
  21695. vertexData.normals = normals;
  21696. vertexData.uvs = uvs;
  21697. return vertexData;
  21698. };
  21699. VertexData.CreateBox = function (size, sideOrientation) {
  21700. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21701. var normalsSource = [
  21702. new BABYLON.Vector3(0, 0, 1),
  21703. new BABYLON.Vector3(0, 0, -1),
  21704. new BABYLON.Vector3(1, 0, 0),
  21705. new BABYLON.Vector3(-1, 0, 0),
  21706. new BABYLON.Vector3(0, 1, 0),
  21707. new BABYLON.Vector3(0, -1, 0)
  21708. ];
  21709. var indices = [];
  21710. var positions = [];
  21711. var normals = [];
  21712. var uvs = [];
  21713. size = size || 1;
  21714. for (var index = 0; index < normalsSource.length; index++) {
  21715. var normal = normalsSource[index];
  21716. // Get two vectors perpendicular to the face normal and to each other.
  21717. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21718. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21719. // Six indices (two triangles) per face.
  21720. var verticesLength = positions.length / 3;
  21721. indices.push(verticesLength);
  21722. indices.push(verticesLength + 1);
  21723. indices.push(verticesLength + 2);
  21724. indices.push(verticesLength);
  21725. indices.push(verticesLength + 2);
  21726. indices.push(verticesLength + 3);
  21727. // Four vertices per face.
  21728. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21729. positions.push(vertex.x, vertex.y, vertex.z);
  21730. normals.push(normal.x, normal.y, normal.z);
  21731. uvs.push(1.0, 1.0);
  21732. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21733. positions.push(vertex.x, vertex.y, vertex.z);
  21734. normals.push(normal.x, normal.y, normal.z);
  21735. uvs.push(0.0, 1.0);
  21736. vertex = normal.add(side1).add(side2).scale(size / 2);
  21737. positions.push(vertex.x, vertex.y, vertex.z);
  21738. normals.push(normal.x, normal.y, normal.z);
  21739. uvs.push(0.0, 0.0);
  21740. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21741. positions.push(vertex.x, vertex.y, vertex.z);
  21742. normals.push(normal.x, normal.y, normal.z);
  21743. uvs.push(1.0, 0.0);
  21744. }
  21745. // sides
  21746. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21747. // Result
  21748. var vertexData = new VertexData();
  21749. vertexData.indices = indices;
  21750. vertexData.positions = positions;
  21751. vertexData.normals = normals;
  21752. vertexData.uvs = uvs;
  21753. return vertexData;
  21754. };
  21755. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21756. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21757. segments = segments || 32;
  21758. diameter = diameter || 1;
  21759. var radius = diameter / 2;
  21760. var totalZRotationSteps = 2 + segments;
  21761. var totalYRotationSteps = 2 * totalZRotationSteps;
  21762. var indices = [];
  21763. var positions = [];
  21764. var normals = [];
  21765. var uvs = [];
  21766. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21767. var normalizedZ = zRotationStep / totalZRotationSteps;
  21768. var angleZ = (normalizedZ * Math.PI);
  21769. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21770. var normalizedY = yRotationStep / totalYRotationSteps;
  21771. var angleY = normalizedY * Math.PI * 2;
  21772. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21773. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21774. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21775. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21776. var vertex = complete.scale(radius);
  21777. var normal = BABYLON.Vector3.Normalize(vertex);
  21778. positions.push(vertex.x, vertex.y, vertex.z);
  21779. normals.push(normal.x, normal.y, normal.z);
  21780. uvs.push(normalizedZ, normalizedY);
  21781. }
  21782. if (zRotationStep > 0) {
  21783. var verticesCount = positions.length / 3;
  21784. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21785. indices.push((firstIndex));
  21786. indices.push((firstIndex + 1));
  21787. indices.push(firstIndex + totalYRotationSteps + 1);
  21788. indices.push((firstIndex + totalYRotationSteps + 1));
  21789. indices.push((firstIndex + 1));
  21790. indices.push((firstIndex + totalYRotationSteps + 2));
  21791. }
  21792. }
  21793. }
  21794. // Sides
  21795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21796. // Result
  21797. var vertexData = new VertexData();
  21798. vertexData.indices = indices;
  21799. vertexData.positions = positions;
  21800. vertexData.normals = normals;
  21801. vertexData.uvs = uvs;
  21802. return vertexData;
  21803. };
  21804. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21805. if (subdivisions === void 0) { subdivisions = 1; }
  21806. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21807. var radiusTop = diameterTop / 2;
  21808. var radiusBottom = diameterBottom / 2;
  21809. var indices = [];
  21810. var positions = [];
  21811. var normals = [];
  21812. var uvs = [];
  21813. height = height || 1;
  21814. diameterTop = diameterTop || 0.5;
  21815. diameterBottom = diameterBottom || 1;
  21816. tessellation = tessellation || 16;
  21817. subdivisions = subdivisions || 1;
  21818. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21819. var getCircleVector = function (i) {
  21820. var angle = (i * 2.0 * Math.PI / tessellation);
  21821. var dx = Math.cos(angle);
  21822. var dz = Math.sin(angle);
  21823. return new BABYLON.Vector3(dx, 0, dz);
  21824. };
  21825. var createCylinderCap = function (isTop) {
  21826. var radius = isTop ? radiusTop : radiusBottom;
  21827. if (radius === 0) {
  21828. return;
  21829. }
  21830. var vbase = positions.length / 3;
  21831. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21832. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21833. if (!isTop) {
  21834. offset.scaleInPlace(-1);
  21835. textureScale.x = -textureScale.x;
  21836. }
  21837. for (var i = 0; i < tessellation; i++) {
  21838. var circleVector = getCircleVector(i);
  21839. var position = circleVector.scale(radius).add(offset);
  21840. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21841. positions.push(position.x, position.y, position.z);
  21842. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21843. }
  21844. for (i = 0; i < tessellation - 2; i++) {
  21845. if (!isTop) {
  21846. indices.push(vbase);
  21847. indices.push(vbase + (i + 2) % tessellation);
  21848. indices.push(vbase + (i + 1) % tessellation);
  21849. }
  21850. else {
  21851. indices.push(vbase);
  21852. indices.push(vbase + (i + 1) % tessellation);
  21853. indices.push(vbase + (i + 2) % tessellation);
  21854. }
  21855. }
  21856. };
  21857. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21858. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21859. var stride = tessellation + 1;
  21860. for (var i = 0; i <= tessellation; i++) {
  21861. var circleVector = getCircleVector(i);
  21862. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21863. var position, radius = radiusBottom;
  21864. for (var s = 0; s <= subdivisions; s++) {
  21865. // Update variables
  21866. position = circleVector.scale(radius);
  21867. position.addInPlace(base.add(offset.scale(s)));
  21868. textureCoordinate.y += 1 / subdivisions;
  21869. radius += (radiusTop - radiusBottom) / subdivisions;
  21870. // Push in arrays
  21871. positions.push(position.x, position.y, position.z);
  21872. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21873. }
  21874. }
  21875. subdivisions += 1;
  21876. for (s = 0; s < subdivisions - 1; s++) {
  21877. for (i = 0; i <= tessellation; i++) {
  21878. indices.push(i * subdivisions + s);
  21879. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21880. indices.push(i * subdivisions + (s + 1));
  21881. indices.push(i * subdivisions + (s + 1));
  21882. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21883. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21884. }
  21885. }
  21886. // Create flat triangle fan caps to seal the top and bottom.
  21887. createCylinderCap(true);
  21888. createCylinderCap(false);
  21889. // Normals
  21890. VertexData.ComputeNormals(positions, indices, normals);
  21891. // Sides
  21892. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21893. // Result
  21894. var vertexData = new VertexData();
  21895. vertexData.indices = indices;
  21896. vertexData.positions = positions;
  21897. vertexData.normals = normals;
  21898. vertexData.uvs = uvs;
  21899. return vertexData;
  21900. };
  21901. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21902. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21903. var indices = [];
  21904. var positions = [];
  21905. var normals = [];
  21906. var uvs = [];
  21907. diameter = diameter || 1;
  21908. thickness = thickness || 0.5;
  21909. tessellation = tessellation || 16;
  21910. var stride = tessellation + 1;
  21911. for (var i = 0; i <= tessellation; i++) {
  21912. var u = i / tessellation;
  21913. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21914. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21915. for (var j = 0; j <= tessellation; j++) {
  21916. var v = 1 - j / tessellation;
  21917. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21918. var dx = Math.cos(innerAngle);
  21919. var dy = Math.sin(innerAngle);
  21920. // Create a vertex.
  21921. var normal = new BABYLON.Vector3(dx, dy, 0);
  21922. var position = normal.scale(thickness / 2);
  21923. var textureCoordinate = new BABYLON.Vector2(u, v);
  21924. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21925. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21926. positions.push(position.x, position.y, position.z);
  21927. normals.push(normal.x, normal.y, normal.z);
  21928. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21929. // And create indices for two triangles.
  21930. var nextI = (i + 1) % stride;
  21931. var nextJ = (j + 1) % stride;
  21932. indices.push(i * stride + j);
  21933. indices.push(i * stride + nextJ);
  21934. indices.push(nextI * stride + j);
  21935. indices.push(i * stride + nextJ);
  21936. indices.push(nextI * stride + nextJ);
  21937. indices.push(nextI * stride + j);
  21938. }
  21939. }
  21940. // Sides
  21941. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21942. // Result
  21943. var vertexData = new VertexData();
  21944. vertexData.indices = indices;
  21945. vertexData.positions = positions;
  21946. vertexData.normals = normals;
  21947. vertexData.uvs = uvs;
  21948. return vertexData;
  21949. };
  21950. VertexData.CreateLines = function (points) {
  21951. var indices = [];
  21952. var positions = [];
  21953. for (var index = 0; index < points.length; index++) {
  21954. positions.push(points[index].x, points[index].y, points[index].z);
  21955. if (index > 0) {
  21956. indices.push(index - 1);
  21957. indices.push(index);
  21958. }
  21959. }
  21960. // Result
  21961. var vertexData = new VertexData();
  21962. vertexData.indices = indices;
  21963. vertexData.positions = positions;
  21964. return vertexData;
  21965. };
  21966. VertexData.CreateGround = function (width, height, subdivisions) {
  21967. var indices = [];
  21968. var positions = [];
  21969. var normals = [];
  21970. var uvs = [];
  21971. var row, col;
  21972. width = width || 1;
  21973. height = height || 1;
  21974. subdivisions = subdivisions || 1;
  21975. for (row = 0; row <= subdivisions; row++) {
  21976. for (col = 0; col <= subdivisions; col++) {
  21977. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21978. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21979. positions.push(position.x, position.y, position.z);
  21980. normals.push(normal.x, normal.y, normal.z);
  21981. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21982. }
  21983. }
  21984. for (row = 0; row < subdivisions; row++) {
  21985. for (col = 0; col < subdivisions; col++) {
  21986. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21987. indices.push(col + 1 + row * (subdivisions + 1));
  21988. indices.push(col + row * (subdivisions + 1));
  21989. indices.push(col + (row + 1) * (subdivisions + 1));
  21990. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21991. indices.push(col + row * (subdivisions + 1));
  21992. }
  21993. }
  21994. // Result
  21995. var vertexData = new VertexData();
  21996. vertexData.indices = indices;
  21997. vertexData.positions = positions;
  21998. vertexData.normals = normals;
  21999. vertexData.uvs = uvs;
  22000. return vertexData;
  22001. };
  22002. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  22003. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  22004. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  22005. var indices = [];
  22006. var positions = [];
  22007. var normals = [];
  22008. var uvs = [];
  22009. var row, col, tileRow, tileCol;
  22010. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  22011. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  22012. precision.w = (precision.w < 1) ? 1 : precision.w;
  22013. precision.h = (precision.h < 1) ? 1 : precision.h;
  22014. var tileSize = {
  22015. 'w': (xmax - xmin) / subdivisions.w,
  22016. 'h': (zmax - zmin) / subdivisions.h
  22017. };
  22018. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  22019. // Indices
  22020. var base = positions.length / 3;
  22021. var rowLength = precision.w + 1;
  22022. for (row = 0; row < precision.h; row++) {
  22023. for (col = 0; col < precision.w; col++) {
  22024. var square = [
  22025. base + col + row * rowLength,
  22026. base + (col + 1) + row * rowLength,
  22027. base + (col + 1) + (row + 1) * rowLength,
  22028. base + col + (row + 1) * rowLength
  22029. ];
  22030. indices.push(square[1]);
  22031. indices.push(square[2]);
  22032. indices.push(square[3]);
  22033. indices.push(square[0]);
  22034. indices.push(square[1]);
  22035. indices.push(square[3]);
  22036. }
  22037. }
  22038. // Position, normals and uvs
  22039. var position = BABYLON.Vector3.Zero();
  22040. var normal = new BABYLON.Vector3(0, 1.0, 0);
  22041. for (row = 0; row <= precision.h; row++) {
  22042. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  22043. for (col = 0; col <= precision.w; col++) {
  22044. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  22045. position.y = 0;
  22046. positions.push(position.x, position.y, position.z);
  22047. normals.push(normal.x, normal.y, normal.z);
  22048. uvs.push(col / precision.w, row / precision.h);
  22049. }
  22050. }
  22051. }
  22052. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  22053. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  22054. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  22055. }
  22056. }
  22057. // Result
  22058. var vertexData = new VertexData();
  22059. vertexData.indices = indices;
  22060. vertexData.positions = positions;
  22061. vertexData.normals = normals;
  22062. vertexData.uvs = uvs;
  22063. return vertexData;
  22064. };
  22065. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  22066. var indices = [];
  22067. var positions = [];
  22068. var normals = [];
  22069. var uvs = [];
  22070. var row, col;
  22071. for (row = 0; row <= subdivisions; row++) {
  22072. for (col = 0; col <= subdivisions; col++) {
  22073. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  22074. // Compute height
  22075. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  22076. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  22077. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  22078. var r = buffer[pos] / 255.0;
  22079. var g = buffer[pos + 1] / 255.0;
  22080. var b = buffer[pos + 2] / 255.0;
  22081. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22082. position.y = minHeight + (maxHeight - minHeight) * gradient;
  22083. // Add vertex
  22084. positions.push(position.x, position.y, position.z);
  22085. normals.push(0, 0, 0);
  22086. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  22087. }
  22088. }
  22089. for (row = 0; row < subdivisions; row++) {
  22090. for (col = 0; col < subdivisions; col++) {
  22091. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22092. indices.push(col + 1 + row * (subdivisions + 1));
  22093. indices.push(col + row * (subdivisions + 1));
  22094. indices.push(col + (row + 1) * (subdivisions + 1));
  22095. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  22096. indices.push(col + row * (subdivisions + 1));
  22097. }
  22098. }
  22099. // Normals
  22100. VertexData.ComputeNormals(positions, indices, normals);
  22101. // Result
  22102. var vertexData = new VertexData();
  22103. vertexData.indices = indices;
  22104. vertexData.positions = positions;
  22105. vertexData.normals = normals;
  22106. vertexData.uvs = uvs;
  22107. return vertexData;
  22108. };
  22109. VertexData.CreatePlane = function (size, sideOrientation) {
  22110. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22111. var indices = [];
  22112. var positions = [];
  22113. var normals = [];
  22114. var uvs = [];
  22115. size = size || 1;
  22116. // Vertices
  22117. var halfSize = size / 2.0;
  22118. positions.push(-halfSize, -halfSize, 0);
  22119. normals.push(0, 0, -1.0);
  22120. uvs.push(0.0, 0.0);
  22121. positions.push(halfSize, -halfSize, 0);
  22122. normals.push(0, 0, -1.0);
  22123. uvs.push(1.0, 0.0);
  22124. positions.push(halfSize, halfSize, 0);
  22125. normals.push(0, 0, -1.0);
  22126. uvs.push(1.0, 1.0);
  22127. positions.push(-halfSize, halfSize, 0);
  22128. normals.push(0, 0, -1.0);
  22129. uvs.push(0.0, 1.0);
  22130. // Indices
  22131. indices.push(0);
  22132. indices.push(1);
  22133. indices.push(2);
  22134. indices.push(0);
  22135. indices.push(2);
  22136. indices.push(3);
  22137. // Sides
  22138. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22139. // Result
  22140. var vertexData = new VertexData();
  22141. vertexData.indices = indices;
  22142. vertexData.positions = positions;
  22143. vertexData.normals = normals;
  22144. vertexData.uvs = uvs;
  22145. return vertexData;
  22146. };
  22147. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  22148. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  22149. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  22150. var indices = [];
  22151. var positions = [];
  22152. var normals = [];
  22153. var uvs = [];
  22154. radius = radius || 2;
  22155. tube = tube || 0.5;
  22156. radialSegments = radialSegments || 32;
  22157. tubularSegments = tubularSegments || 32;
  22158. p = p || 2;
  22159. q = q || 3;
  22160. // Helper
  22161. var getPos = function (angle) {
  22162. var cu = Math.cos(angle);
  22163. var su = Math.sin(angle);
  22164. var quOverP = q / p * angle;
  22165. var cs = Math.cos(quOverP);
  22166. var tx = radius * (2 + cs) * 0.5 * cu;
  22167. var ty = radius * (2 + cs) * su * 0.5;
  22168. var tz = radius * Math.sin(quOverP) * 0.5;
  22169. return new BABYLON.Vector3(tx, ty, tz);
  22170. };
  22171. for (var i = 0; i <= radialSegments; i++) {
  22172. var modI = i % radialSegments;
  22173. var u = modI / radialSegments * 2 * p * Math.PI;
  22174. var p1 = getPos(u);
  22175. var p2 = getPos(u + 0.01);
  22176. var tang = p2.subtract(p1);
  22177. var n = p2.add(p1);
  22178. var bitan = BABYLON.Vector3.Cross(tang, n);
  22179. n = BABYLON.Vector3.Cross(bitan, tang);
  22180. bitan.normalize();
  22181. n.normalize();
  22182. for (var j = 0; j < tubularSegments; j++) {
  22183. var modJ = j % tubularSegments;
  22184. var v = modJ / tubularSegments * 2 * Math.PI;
  22185. var cx = -tube * Math.cos(v);
  22186. var cy = tube * Math.sin(v);
  22187. positions.push(p1.x + cx * n.x + cy * bitan.x);
  22188. positions.push(p1.y + cx * n.y + cy * bitan.y);
  22189. positions.push(p1.z + cx * n.z + cy * bitan.z);
  22190. uvs.push(i / radialSegments);
  22191. uvs.push(j / tubularSegments);
  22192. }
  22193. }
  22194. for (i = 0; i < radialSegments; i++) {
  22195. for (j = 0; j < tubularSegments; j++) {
  22196. var jNext = (j + 1) % tubularSegments;
  22197. var a = i * tubularSegments + j;
  22198. var b = (i + 1) * tubularSegments + j;
  22199. var c = (i + 1) * tubularSegments + jNext;
  22200. var d = i * tubularSegments + jNext;
  22201. indices.push(d);
  22202. indices.push(b);
  22203. indices.push(a);
  22204. indices.push(d);
  22205. indices.push(c);
  22206. indices.push(b);
  22207. }
  22208. }
  22209. // Normals
  22210. VertexData.ComputeNormals(positions, indices, normals);
  22211. // Sides
  22212. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  22213. // Result
  22214. var vertexData = new VertexData();
  22215. vertexData.indices = indices;
  22216. vertexData.positions = positions;
  22217. vertexData.normals = normals;
  22218. vertexData.uvs = uvs;
  22219. return vertexData;
  22220. };
  22221. // Tools
  22222. VertexData.ComputeNormals = function (positions, indices, normals) {
  22223. var positionVectors = [];
  22224. var facesOfVertices = [];
  22225. var index;
  22226. for (index = 0; index < positions.length; index += 3) {
  22227. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  22228. positionVectors.push(vector3);
  22229. facesOfVertices.push([]);
  22230. }
  22231. // Compute normals
  22232. var facesNormals = [];
  22233. for (index = 0; index < indices.length / 3; index++) {
  22234. var i1 = indices[index * 3];
  22235. var i2 = indices[index * 3 + 1];
  22236. var i3 = indices[index * 3 + 2];
  22237. var p1 = positionVectors[i1];
  22238. var p2 = positionVectors[i2];
  22239. var p3 = positionVectors[i3];
  22240. var p1p2 = p1.subtract(p2);
  22241. var p3p2 = p3.subtract(p2);
  22242. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22243. facesOfVertices[i1].push(index);
  22244. facesOfVertices[i2].push(index);
  22245. facesOfVertices[i3].push(index);
  22246. }
  22247. for (index = 0; index < positionVectors.length; index++) {
  22248. var faces = facesOfVertices[index];
  22249. var normal = BABYLON.Vector3.Zero();
  22250. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  22251. normal.addInPlace(facesNormals[faces[faceIndex]]);
  22252. }
  22253. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  22254. normals[index * 3] = normal.x;
  22255. normals[index * 3 + 1] = normal.y;
  22256. normals[index * 3 + 2] = normal.z;
  22257. }
  22258. };
  22259. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  22260. var li = indices.length;
  22261. var ln = normals.length;
  22262. var i;
  22263. var n;
  22264. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  22265. switch (sideOrientation) {
  22266. case BABYLON.Mesh.FRONTSIDE:
  22267. break;
  22268. case BABYLON.Mesh.BACKSIDE:
  22269. var tmp;
  22270. for (i = 0; i < li; i += 3) {
  22271. tmp = indices[i];
  22272. indices[i] = indices[i + 2];
  22273. indices[i + 2] = tmp;
  22274. }
  22275. for (n = 0; n < ln; n++) {
  22276. normals[n] = -normals[n];
  22277. }
  22278. break;
  22279. case BABYLON.Mesh.DOUBLESIDE:
  22280. // positions
  22281. var lp = positions.length;
  22282. var l = lp / 3;
  22283. for (var p = 0; p < lp; p++) {
  22284. positions[lp + p] = positions[p];
  22285. }
  22286. for (i = 0; i < li; i += 3) {
  22287. indices[i + li] = indices[i + 2] + l;
  22288. indices[i + 1 + li] = indices[i + 1] + l;
  22289. indices[i + 2 + li] = indices[i] + l;
  22290. }
  22291. for (n = 0; n < ln; n++) {
  22292. normals[ln + n] = -normals[n];
  22293. }
  22294. // uvs
  22295. var lu = uvs.length;
  22296. for (var u = 0; u < lu; u++) {
  22297. uvs[u + lu] = uvs[u];
  22298. }
  22299. break;
  22300. }
  22301. };
  22302. return VertexData;
  22303. })();
  22304. BABYLON.VertexData = VertexData;
  22305. })(BABYLON || (BABYLON = {}));
  22306. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22307. var BABYLON;
  22308. (function (BABYLON) {
  22309. var buildCamera = function (that, name) {
  22310. that._leftCamera.isIntermediate = true;
  22311. that.subCameras.push(that._leftCamera);
  22312. that.subCameras.push(that._rightCamera);
  22313. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22314. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22315. that._anaglyphPostProcess.onApply = function (effect) {
  22316. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22317. };
  22318. that._update();
  22319. };
  22320. var AnaglyphArcRotateCamera = (function (_super) {
  22321. __extends(AnaglyphArcRotateCamera, _super);
  22322. // ANY
  22323. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22324. _super.call(this, name, alpha, beta, radius, target, scene);
  22325. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22326. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22327. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22328. buildCamera(this, name);
  22329. }
  22330. AnaglyphArcRotateCamera.prototype._update = function () {
  22331. this._updateCamera(this._leftCamera);
  22332. this._updateCamera(this._rightCamera);
  22333. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22334. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22335. _super.prototype._update.call(this);
  22336. };
  22337. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22338. camera.beta = this.beta;
  22339. camera.radius = this.radius;
  22340. camera.minZ = this.minZ;
  22341. camera.maxZ = this.maxZ;
  22342. camera.fov = this.fov;
  22343. camera.target = this.target;
  22344. };
  22345. return AnaglyphArcRotateCamera;
  22346. })(BABYLON.ArcRotateCamera);
  22347. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22348. var AnaglyphFreeCamera = (function (_super) {
  22349. __extends(AnaglyphFreeCamera, _super);
  22350. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22351. _super.call(this, name, position, scene);
  22352. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22353. this._transformMatrix = new BABYLON.Matrix();
  22354. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22355. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22356. buildCamera(this, name);
  22357. }
  22358. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22359. var target = this.getTarget();
  22360. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22361. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22362. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22363. };
  22364. AnaglyphFreeCamera.prototype._update = function () {
  22365. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22366. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22367. this._updateCamera(this._leftCamera);
  22368. this._updateCamera(this._rightCamera);
  22369. _super.prototype._update.call(this);
  22370. };
  22371. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22372. camera.minZ = this.minZ;
  22373. camera.maxZ = this.maxZ;
  22374. camera.fov = this.fov;
  22375. camera.viewport = this.viewport;
  22376. camera.setTarget(this.getTarget());
  22377. };
  22378. return AnaglyphFreeCamera;
  22379. })(BABYLON.FreeCamera);
  22380. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22381. })(BABYLON || (BABYLON = {}));
  22382. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22383. var BABYLON;
  22384. (function (BABYLON) {
  22385. var AnaglyphPostProcess = (function (_super) {
  22386. __extends(AnaglyphPostProcess, _super);
  22387. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22388. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22389. }
  22390. return AnaglyphPostProcess;
  22391. })(BABYLON.PostProcess);
  22392. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22393. })(BABYLON || (BABYLON = {}));
  22394. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22395. (function (BABYLON) {
  22396. var Tags = (function () {
  22397. function Tags() {
  22398. }
  22399. Tags.EnableFor = function (obj) {
  22400. obj._tags = obj._tags || {};
  22401. obj.hasTags = function () {
  22402. return Tags.HasTags(obj);
  22403. };
  22404. obj.addTags = function (tagsString) {
  22405. return Tags.AddTagsTo(obj, tagsString);
  22406. };
  22407. obj.removeTags = function (tagsString) {
  22408. return Tags.RemoveTagsFrom(obj, tagsString);
  22409. };
  22410. obj.matchesTagsQuery = function (tagsQuery) {
  22411. return Tags.MatchesQuery(obj, tagsQuery);
  22412. };
  22413. };
  22414. Tags.DisableFor = function (obj) {
  22415. delete obj._tags;
  22416. delete obj.hasTags;
  22417. delete obj.addTags;
  22418. delete obj.removeTags;
  22419. delete obj.matchesTagsQuery;
  22420. };
  22421. Tags.HasTags = function (obj) {
  22422. if (!obj._tags) {
  22423. return false;
  22424. }
  22425. return !BABYLON.Tools.IsEmpty(obj._tags);
  22426. };
  22427. Tags.GetTags = function (obj) {
  22428. if (!obj._tags) {
  22429. return null;
  22430. }
  22431. return obj._tags;
  22432. };
  22433. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22434. // a tag cannot start with '||', '&&', and '!'
  22435. // it cannot contain whitespaces
  22436. Tags.AddTagsTo = function (obj, tagsString) {
  22437. if (!tagsString) {
  22438. return;
  22439. }
  22440. var tags = tagsString.split(" ");
  22441. for (var t in tags) {
  22442. Tags._AddTagTo(obj, tags[t]);
  22443. }
  22444. };
  22445. Tags._AddTagTo = function (obj, tag) {
  22446. tag = tag.trim();
  22447. if (tag === "" || tag === "true" || tag === "false") {
  22448. return;
  22449. }
  22450. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22451. return;
  22452. }
  22453. Tags.EnableFor(obj);
  22454. obj._tags[tag] = true;
  22455. };
  22456. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22457. if (!Tags.HasTags(obj)) {
  22458. return;
  22459. }
  22460. var tags = tagsString.split(" ");
  22461. for (var t in tags) {
  22462. Tags._RemoveTagFrom(obj, tags[t]);
  22463. }
  22464. };
  22465. Tags._RemoveTagFrom = function (obj, tag) {
  22466. delete obj._tags[tag];
  22467. };
  22468. Tags.MatchesQuery = function (obj, tagsQuery) {
  22469. if (tagsQuery === undefined) {
  22470. return true;
  22471. }
  22472. if (tagsQuery === "") {
  22473. return Tags.HasTags(obj);
  22474. }
  22475. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22476. };
  22477. return Tags;
  22478. })();
  22479. BABYLON.Tags = Tags;
  22480. })(BABYLON || (BABYLON = {}));
  22481. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22482. (function (BABYLON) {
  22483. var Internals;
  22484. (function (Internals) {
  22485. var AndOrNotEvaluator = (function () {
  22486. function AndOrNotEvaluator() {
  22487. }
  22488. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22489. if (!query.match(/\([^\(\)]*\)/g)) {
  22490. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22491. }
  22492. else {
  22493. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22494. // remove parenthesis
  22495. r = r.slice(1, r.length - 1);
  22496. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22497. });
  22498. }
  22499. if (query === "true") {
  22500. return true;
  22501. }
  22502. if (query === "false") {
  22503. return false;
  22504. }
  22505. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22506. };
  22507. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22508. evaluateCallback = evaluateCallback || (function (r) {
  22509. return r === "true" ? true : false;
  22510. });
  22511. var result;
  22512. var or = parenthesisContent.split("||");
  22513. for (var i in or) {
  22514. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22515. var and = ori.split("&&");
  22516. if (and.length > 1) {
  22517. for (var j = 0; j < and.length; ++j) {
  22518. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22519. if (andj !== "true" && andj !== "false") {
  22520. if (andj[0] === "!") {
  22521. result = !evaluateCallback(andj.substring(1));
  22522. }
  22523. else {
  22524. result = evaluateCallback(andj);
  22525. }
  22526. }
  22527. else {
  22528. result = andj === "true" ? true : false;
  22529. }
  22530. if (!result) {
  22531. ori = "false";
  22532. break;
  22533. }
  22534. }
  22535. }
  22536. if (result || ori === "true") {
  22537. result = true;
  22538. break;
  22539. }
  22540. // result equals false (or undefined)
  22541. if (ori !== "true" && ori !== "false") {
  22542. if (ori[0] === "!") {
  22543. result = !evaluateCallback(ori.substring(1));
  22544. }
  22545. else {
  22546. result = evaluateCallback(ori);
  22547. }
  22548. }
  22549. else {
  22550. result = ori === "true" ? true : false;
  22551. }
  22552. }
  22553. // the whole parenthesis scope is replaced by 'true' or 'false'
  22554. return result ? "true" : "false";
  22555. };
  22556. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22557. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22558. // remove whitespaces
  22559. r = r.replace(/[\s]/g, function () { return ""; });
  22560. return r.length % 2 ? "!" : "";
  22561. });
  22562. booleanString = booleanString.trim();
  22563. if (booleanString === "!true") {
  22564. booleanString = "false";
  22565. }
  22566. else if (booleanString === "!false") {
  22567. booleanString = "true";
  22568. }
  22569. return booleanString;
  22570. };
  22571. return AndOrNotEvaluator;
  22572. })();
  22573. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22574. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22575. })(BABYLON || (BABYLON = {}));
  22576. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22577. (function (BABYLON) {
  22578. var PostProcessRenderPass = (function () {
  22579. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22580. this._enabled = true;
  22581. this._refCount = 0;
  22582. this._name = name;
  22583. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22584. this.setRenderList(renderList);
  22585. this._renderTexture.onBeforeRender = beforeRender;
  22586. this._renderTexture.onAfterRender = afterRender;
  22587. this._scene = scene;
  22588. this._renderList = renderList;
  22589. }
  22590. // private
  22591. PostProcessRenderPass.prototype._incRefCount = function () {
  22592. if (this._refCount === 0) {
  22593. this._scene.customRenderTargets.push(this._renderTexture);
  22594. }
  22595. return ++this._refCount;
  22596. };
  22597. PostProcessRenderPass.prototype._decRefCount = function () {
  22598. this._refCount--;
  22599. if (this._refCount <= 0) {
  22600. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22601. }
  22602. return this._refCount;
  22603. };
  22604. PostProcessRenderPass.prototype._update = function () {
  22605. this.setRenderList(this._renderList);
  22606. };
  22607. // public
  22608. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22609. this._renderTexture.renderList = renderList;
  22610. };
  22611. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22612. return this._renderTexture;
  22613. };
  22614. return PostProcessRenderPass;
  22615. })();
  22616. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22617. })(BABYLON || (BABYLON = {}));
  22618. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22619. (function (BABYLON) {
  22620. var PostProcessRenderEffect = (function () {
  22621. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22622. this._engine = engine;
  22623. this._name = name;
  22624. this._singleInstance = singleInstance || true;
  22625. this._getPostProcess = getPostProcess;
  22626. this._cameras = [];
  22627. this._indicesForCamera = [];
  22628. this._postProcesses = {};
  22629. this._renderPasses = {};
  22630. this._renderEffectAsPasses = {};
  22631. }
  22632. PostProcessRenderEffect.prototype._update = function () {
  22633. for (var renderPassName in this._renderPasses) {
  22634. this._renderPasses[renderPassName]._update();
  22635. }
  22636. };
  22637. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22638. this._renderPasses[renderPass._name] = renderPass;
  22639. this._linkParameters();
  22640. };
  22641. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22642. delete this._renderPasses[renderPass._name];
  22643. this._linkParameters();
  22644. };
  22645. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22646. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22647. this._linkParameters();
  22648. };
  22649. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22650. for (var renderPassName in this._renderPasses) {
  22651. if (renderPassName === passName) {
  22652. return this._renderPasses[passName];
  22653. }
  22654. }
  22655. };
  22656. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22657. this._renderPasses = {};
  22658. this._linkParameters();
  22659. };
  22660. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22661. var cameraKey;
  22662. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22663. for (var i = 0; i < _cam.length; i++) {
  22664. var camera = _cam[i];
  22665. var cameraName = camera.name;
  22666. if (this._singleInstance) {
  22667. cameraKey = 0;
  22668. }
  22669. else {
  22670. cameraKey = cameraName;
  22671. }
  22672. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22673. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22674. if (!this._indicesForCamera[cameraName]) {
  22675. this._indicesForCamera[cameraName] = [];
  22676. }
  22677. this._indicesForCamera[cameraName].push(index);
  22678. if (this._cameras.indexOf(camera) === -1) {
  22679. this._cameras[cameraName] = camera;
  22680. }
  22681. for (var passName in this._renderPasses) {
  22682. this._renderPasses[passName]._incRefCount();
  22683. }
  22684. }
  22685. this._linkParameters();
  22686. };
  22687. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22688. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22689. for (var i = 0; i < _cam.length; i++) {
  22690. var camera = _cam[i];
  22691. var cameraName = camera.name;
  22692. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22693. var index = this._cameras.indexOf(cameraName);
  22694. this._indicesForCamera.splice(index, 1);
  22695. this._cameras.splice(index, 1);
  22696. for (var passName in this._renderPasses) {
  22697. this._renderPasses[passName]._decRefCount();
  22698. }
  22699. }
  22700. };
  22701. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22702. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22703. for (var i = 0; i < _cam.length; i++) {
  22704. var camera = _cam[i];
  22705. var cameraName = camera.name;
  22706. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22707. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22708. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22709. }
  22710. }
  22711. for (var passName in this._renderPasses) {
  22712. this._renderPasses[passName]._incRefCount();
  22713. }
  22714. }
  22715. };
  22716. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22717. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22718. for (var i = 0; i < _cam.length; i++) {
  22719. var camera = _cam[i];
  22720. var cameraName = camera.Name;
  22721. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22722. for (var passName in this._renderPasses) {
  22723. this._renderPasses[passName]._decRefCount();
  22724. }
  22725. }
  22726. };
  22727. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22728. if (this._singleInstance) {
  22729. return this._postProcesses[0];
  22730. }
  22731. else {
  22732. return this._postProcesses[camera.name];
  22733. }
  22734. };
  22735. PostProcessRenderEffect.prototype._linkParameters = function () {
  22736. var _this = this;
  22737. for (var index in this._postProcesses) {
  22738. if (this.applyParameters) {
  22739. this.applyParameters(this._postProcesses[index]);
  22740. }
  22741. this._postProcesses[index].onBeforeRender = function (effect) {
  22742. _this._linkTextures(effect);
  22743. };
  22744. }
  22745. };
  22746. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22747. for (var renderPassName in this._renderPasses) {
  22748. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22749. }
  22750. for (var renderEffectName in this._renderEffectAsPasses) {
  22751. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22752. }
  22753. };
  22754. return PostProcessRenderEffect;
  22755. })();
  22756. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22757. })(BABYLON || (BABYLON = {}));
  22758. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22759. (function (BABYLON) {
  22760. var PostProcessRenderPipeline = (function () {
  22761. function PostProcessRenderPipeline(engine, name) {
  22762. this._engine = engine;
  22763. this._name = name;
  22764. this._renderEffects = {};
  22765. this._renderEffectsForIsolatedPass = {};
  22766. this._cameras = [];
  22767. }
  22768. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22769. this._renderEffects[renderEffect._name] = renderEffect;
  22770. };
  22771. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22772. var renderEffects = this._renderEffects[renderEffectName];
  22773. if (!renderEffects) {
  22774. return;
  22775. }
  22776. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22777. };
  22778. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22779. var renderEffects = this._renderEffects[renderEffectName];
  22780. if (!renderEffects) {
  22781. return;
  22782. }
  22783. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22784. };
  22785. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22786. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22787. var indicesToDelete = [];
  22788. for (var i = 0; i < _cam.length; i++) {
  22789. var camera = _cam[i];
  22790. var cameraName = camera.name;
  22791. if (this._cameras.indexOf(camera) === -1) {
  22792. this._cameras[cameraName] = camera;
  22793. }
  22794. else if (unique) {
  22795. indicesToDelete.push(i);
  22796. }
  22797. }
  22798. for (var i = 0; i < indicesToDelete.length; i++) {
  22799. cameras.splice(indicesToDelete[i], 1);
  22800. }
  22801. for (var renderEffectName in this._renderEffects) {
  22802. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22803. }
  22804. };
  22805. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22806. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22807. for (var renderEffectName in this._renderEffects) {
  22808. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22809. }
  22810. for (var i = 0; i < _cam.length; i++) {
  22811. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22812. }
  22813. };
  22814. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22815. var _this = this;
  22816. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22817. var pass = null;
  22818. for (var renderEffectName in this._renderEffects) {
  22819. pass = this._renderEffects[renderEffectName].getPass(passName);
  22820. if (pass != null) {
  22821. break;
  22822. }
  22823. }
  22824. if (pass === null) {
  22825. return;
  22826. }
  22827. for (var renderEffectName in this._renderEffects) {
  22828. this._renderEffects[renderEffectName]._disable(_cam);
  22829. }
  22830. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22831. for (var i = 0; i < _cam.length; i++) {
  22832. var camera = _cam[i];
  22833. var cameraName = camera.name;
  22834. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22835. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22836. });
  22837. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22838. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22839. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22840. }
  22841. };
  22842. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22843. var _this = this;
  22844. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22845. for (var i = 0; i < _cam.length; i++) {
  22846. var camera = _cam[i];
  22847. var cameraName = camera.name;
  22848. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22849. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22850. });
  22851. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22852. }
  22853. for (var renderEffectName in this._renderEffects) {
  22854. this._renderEffects[renderEffectName]._enable(_cam);
  22855. }
  22856. };
  22857. PostProcessRenderPipeline.prototype._update = function () {
  22858. for (var renderEffectName in this._renderEffects) {
  22859. this._renderEffects[renderEffectName]._update();
  22860. }
  22861. for (var i = 0; i < this._cameras.length; i++) {
  22862. var cameraName = this._cameras[i].name;
  22863. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22864. this._renderEffectsForIsolatedPass[cameraName]._update();
  22865. }
  22866. }
  22867. };
  22868. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22869. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22870. return PostProcessRenderPipeline;
  22871. })();
  22872. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22873. })(BABYLON || (BABYLON = {}));
  22874. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22875. (function (BABYLON) {
  22876. var PostProcessRenderPipelineManager = (function () {
  22877. function PostProcessRenderPipelineManager() {
  22878. this._renderPipelines = {};
  22879. }
  22880. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22881. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22882. };
  22883. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22884. var renderPipeline = this._renderPipelines[renderPipelineName];
  22885. if (!renderPipeline) {
  22886. return;
  22887. }
  22888. renderPipeline._attachCameras(cameras, unique);
  22889. };
  22890. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22891. var renderPipeline = this._renderPipelines[renderPipelineName];
  22892. if (!renderPipeline) {
  22893. return;
  22894. }
  22895. renderPipeline._detachCameras(cameras);
  22896. };
  22897. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22898. var renderPipeline = this._renderPipelines[renderPipelineName];
  22899. if (!renderPipeline) {
  22900. return;
  22901. }
  22902. renderPipeline._enableEffect(renderEffectName, cameras);
  22903. };
  22904. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22905. var renderPipeline = this._renderPipelines[renderPipelineName];
  22906. if (!renderPipeline) {
  22907. return;
  22908. }
  22909. renderPipeline._disableEffect(renderEffectName, cameras);
  22910. };
  22911. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22912. var renderPipeline = this._renderPipelines[renderPipelineName];
  22913. if (!renderPipeline) {
  22914. return;
  22915. }
  22916. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22917. };
  22918. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22919. var renderPipeline = this._renderPipelines[renderPipelineName];
  22920. if (!renderPipeline) {
  22921. return;
  22922. }
  22923. renderPipeline._disableDisplayOnlyPass(cameras);
  22924. };
  22925. PostProcessRenderPipelineManager.prototype.update = function () {
  22926. for (var renderPipelineName in this._renderPipelines) {
  22927. this._renderPipelines[renderPipelineName]._update();
  22928. }
  22929. };
  22930. return PostProcessRenderPipelineManager;
  22931. })();
  22932. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22933. })(BABYLON || (BABYLON = {}));
  22934. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22935. var BABYLON;
  22936. (function (BABYLON) {
  22937. var DisplayPassPostProcess = (function (_super) {
  22938. __extends(DisplayPassPostProcess, _super);
  22939. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22940. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22941. }
  22942. return DisplayPassPostProcess;
  22943. })(BABYLON.PostProcess);
  22944. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22945. })(BABYLON || (BABYLON = {}));
  22946. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22947. (function (BABYLON) {
  22948. var BoundingBoxRenderer = (function () {
  22949. function BoundingBoxRenderer(scene) {
  22950. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22951. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22952. this.showBackLines = true;
  22953. this.renderList = new BABYLON.SmartArray(32);
  22954. this._scene = scene;
  22955. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22956. attributes: ["position"],
  22957. uniforms: ["worldViewProjection", "color"]
  22958. });
  22959. var engine = this._scene.getEngine();
  22960. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22961. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22962. 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]);
  22963. }
  22964. BoundingBoxRenderer.prototype.reset = function () {
  22965. this.renderList.reset();
  22966. };
  22967. BoundingBoxRenderer.prototype.render = function () {
  22968. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22969. return;
  22970. }
  22971. var engine = this._scene.getEngine();
  22972. engine.setDepthWrite(false);
  22973. this._colorShader._preBind();
  22974. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22975. var boundingBox = this.renderList.data[boundingBoxIndex];
  22976. var min = boundingBox.minimum;
  22977. var max = boundingBox.maximum;
  22978. var diff = max.subtract(min);
  22979. var median = min.add(diff.scale(0.5));
  22980. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22981. // VBOs
  22982. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22983. if (this.showBackLines) {
  22984. // Back
  22985. engine.setDepthFunctionToGreaterOrEqual();
  22986. this._scene.resetCachedMaterial();
  22987. this._colorShader.setColor4("color", this.backColor.toColor4());
  22988. this._colorShader.bind(worldMatrix);
  22989. // Draw order
  22990. engine.draw(false, 0, 24);
  22991. }
  22992. // Front
  22993. engine.setDepthFunctionToLess();
  22994. this._scene.resetCachedMaterial();
  22995. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22996. this._colorShader.bind(worldMatrix);
  22997. // Draw order
  22998. engine.draw(false, 0, 24);
  22999. }
  23000. this._colorShader.unbind();
  23001. engine.setDepthFunctionToLessOrEqual();
  23002. engine.setDepthWrite(true);
  23003. };
  23004. BoundingBoxRenderer.prototype.dispose = function () {
  23005. this._colorShader.dispose();
  23006. this._vb.dispose();
  23007. this._scene.getEngine()._releaseBuffer(this._ib);
  23008. };
  23009. return BoundingBoxRenderer;
  23010. })();
  23011. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  23012. })(BABYLON || (BABYLON = {}));
  23013. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  23014. (function (BABYLON) {
  23015. var Internals;
  23016. (function (Internals) {
  23017. /*
  23018. * Based on jsTGALoader - Javascript loader for TGA file
  23019. * By Vincent Thibault
  23020. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  23021. */
  23022. var TGATools = (function () {
  23023. function TGATools() {
  23024. }
  23025. TGATools.GetTGAHeader = function (data) {
  23026. var offset = 0;
  23027. var header = {
  23028. id_length: data[offset++],
  23029. colormap_type: data[offset++],
  23030. image_type: data[offset++],
  23031. colormap_index: data[offset++] | data[offset++] << 8,
  23032. colormap_length: data[offset++] | data[offset++] << 8,
  23033. colormap_size: data[offset++],
  23034. origin: [
  23035. data[offset++] | data[offset++] << 8,
  23036. data[offset++] | data[offset++] << 8
  23037. ],
  23038. width: data[offset++] | data[offset++] << 8,
  23039. height: data[offset++] | data[offset++] << 8,
  23040. pixel_size: data[offset++],
  23041. flags: data[offset++]
  23042. };
  23043. return header;
  23044. };
  23045. TGATools.UploadContent = function (gl, data) {
  23046. // Not enough data to contain header ?
  23047. if (data.length < 19) {
  23048. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  23049. return;
  23050. }
  23051. // Read Header
  23052. var offset = 18;
  23053. var header = TGATools.GetTGAHeader(data);
  23054. // Assume it's a valid Targa file.
  23055. if (header.id_length + offset > data.length) {
  23056. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  23057. return;
  23058. }
  23059. // Skip not needed data
  23060. offset += header.id_length;
  23061. var use_rle = false;
  23062. var use_pal = false;
  23063. var use_rgb = false;
  23064. var use_grey = false;
  23065. switch (header.image_type) {
  23066. case TGATools._TYPE_RLE_INDEXED:
  23067. use_rle = true;
  23068. case TGATools._TYPE_INDEXED:
  23069. use_pal = true;
  23070. break;
  23071. case TGATools._TYPE_RLE_RGB:
  23072. use_rle = true;
  23073. case TGATools._TYPE_RGB:
  23074. use_rgb = true;
  23075. break;
  23076. case TGATools._TYPE_RLE_GREY:
  23077. use_rle = true;
  23078. case TGATools._TYPE_GREY:
  23079. use_grey = true;
  23080. break;
  23081. }
  23082. var pixel_data;
  23083. var numAlphaBits = header.flags & 0xf;
  23084. var pixel_size = header.pixel_size >> 3;
  23085. var pixel_total = header.width * header.height * pixel_size;
  23086. // Read palettes
  23087. var palettes;
  23088. if (use_pal) {
  23089. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  23090. }
  23091. // Read LRE
  23092. if (use_rle) {
  23093. pixel_data = new Uint8Array(pixel_total);
  23094. var c, count, i;
  23095. var localOffset = 0;
  23096. var pixels = new Uint8Array(pixel_size);
  23097. while (offset < pixel_total && localOffset < pixel_total) {
  23098. c = data[offset++];
  23099. count = (c & 0x7f) + 1;
  23100. // RLE pixels
  23101. if (c & 0x80) {
  23102. for (i = 0; i < pixel_size; ++i) {
  23103. pixels[i] = data[offset++];
  23104. }
  23105. for (i = 0; i < count; ++i) {
  23106. pixel_data.set(pixels, localOffset + i * pixel_size);
  23107. }
  23108. localOffset += pixel_size * count;
  23109. }
  23110. else {
  23111. count *= pixel_size;
  23112. for (i = 0; i < count; ++i) {
  23113. pixel_data[localOffset + i] = data[offset++];
  23114. }
  23115. localOffset += count;
  23116. }
  23117. }
  23118. }
  23119. else {
  23120. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  23121. }
  23122. // Load to texture
  23123. var x_start, y_start, x_step, y_step, y_end, x_end;
  23124. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  23125. default:
  23126. case TGATools._ORIGIN_UL:
  23127. x_start = 0;
  23128. x_step = 1;
  23129. x_end = header.width;
  23130. y_start = 0;
  23131. y_step = 1;
  23132. y_end = header.height;
  23133. break;
  23134. case TGATools._ORIGIN_BL:
  23135. x_start = 0;
  23136. x_step = 1;
  23137. x_end = header.width;
  23138. y_start = header.height - 1;
  23139. y_step = -1;
  23140. y_end = -1;
  23141. break;
  23142. case TGATools._ORIGIN_UR:
  23143. x_start = header.width - 1;
  23144. x_step = -1;
  23145. x_end = -1;
  23146. y_start = 0;
  23147. y_step = 1;
  23148. y_end = header.height;
  23149. break;
  23150. case TGATools._ORIGIN_BR:
  23151. x_start = header.width - 1;
  23152. x_step = -1;
  23153. x_end = -1;
  23154. y_start = header.height - 1;
  23155. y_step = -1;
  23156. y_end = -1;
  23157. break;
  23158. }
  23159. // Load the specify method
  23160. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  23161. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  23162. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  23163. };
  23164. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23165. var image = pixel_data, colormap = palettes;
  23166. var width = header.width, height = header.height;
  23167. var color, i = 0, x, y;
  23168. var imageData = new Uint8Array(width * height * 4);
  23169. for (y = y_start; y !== y_end; y += y_step) {
  23170. for (x = x_start; x !== x_end; x += x_step, i++) {
  23171. color = image[i];
  23172. imageData[(x + width * y) * 4 + 3] = 255;
  23173. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  23174. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  23175. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  23176. }
  23177. }
  23178. return imageData;
  23179. };
  23180. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23181. var image = pixel_data;
  23182. var width = header.width, height = header.height;
  23183. var color, i = 0, x, y;
  23184. var imageData = new Uint8Array(width * height * 4);
  23185. for (y = y_start; y !== y_end; y += y_step) {
  23186. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23187. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  23188. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  23189. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  23190. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  23191. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  23192. }
  23193. }
  23194. return imageData;
  23195. };
  23196. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23197. var image = pixel_data;
  23198. var width = header.width, height = header.height;
  23199. var i = 0, x, y;
  23200. var imageData = new Uint8Array(width * height * 4);
  23201. for (y = y_start; y !== y_end; y += y_step) {
  23202. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  23203. imageData[(x + width * y) * 4 + 3] = 255;
  23204. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23205. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23206. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23207. }
  23208. }
  23209. return imageData;
  23210. };
  23211. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23212. var image = pixel_data;
  23213. var width = header.width, height = header.height;
  23214. var i = 0, x, y;
  23215. var imageData = new Uint8Array(width * height * 4);
  23216. for (y = y_start; y !== y_end; y += y_step) {
  23217. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  23218. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23219. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  23220. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  23221. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  23222. }
  23223. }
  23224. return imageData;
  23225. };
  23226. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23227. var image = pixel_data;
  23228. var width = header.width, height = header.height;
  23229. var color, i = 0, x, y;
  23230. var imageData = new Uint8Array(width * height * 4);
  23231. for (y = y_start; y !== y_end; y += y_step) {
  23232. for (x = x_start; x !== x_end; x += x_step, i++) {
  23233. color = image[i];
  23234. imageData[(x + width * y) * 4 + 0] = color;
  23235. imageData[(x + width * y) * 4 + 1] = color;
  23236. imageData[(x + width * y) * 4 + 2] = color;
  23237. imageData[(x + width * y) * 4 + 3] = 255;
  23238. }
  23239. }
  23240. return imageData;
  23241. };
  23242. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  23243. var image = pixel_data;
  23244. var width = header.width, height = header.height;
  23245. var i = 0, x, y;
  23246. var imageData = new Uint8Array(width * height * 4);
  23247. for (y = y_start; y !== y_end; y += y_step) {
  23248. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  23249. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  23250. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  23251. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  23252. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  23253. }
  23254. }
  23255. return imageData;
  23256. };
  23257. TGATools._TYPE_NO_DATA = 0;
  23258. TGATools._TYPE_INDEXED = 1;
  23259. TGATools._TYPE_RGB = 2;
  23260. TGATools._TYPE_GREY = 3;
  23261. TGATools._TYPE_RLE_INDEXED = 9;
  23262. TGATools._TYPE_RLE_RGB = 10;
  23263. TGATools._TYPE_RLE_GREY = 11;
  23264. TGATools._ORIGIN_MASK = 0x30;
  23265. TGATools._ORIGIN_SHIFT = 0x04;
  23266. TGATools._ORIGIN_BL = 0x00;
  23267. TGATools._ORIGIN_BR = 0x01;
  23268. TGATools._ORIGIN_UL = 0x02;
  23269. TGATools._ORIGIN_UR = 0x03;
  23270. return TGATools;
  23271. })();
  23272. Internals.TGATools = TGATools;
  23273. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23274. })(BABYLON || (BABYLON = {}));
  23275. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23276. (function (BABYLON) {
  23277. var Internals;
  23278. (function (Internals) {
  23279. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23280. // All values and structures referenced from:
  23281. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23282. var DDS_MAGIC = 0x20534444;
  23283. 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;
  23284. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23285. 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;
  23286. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23287. function FourCCToInt32(value) {
  23288. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23289. }
  23290. function Int32ToFourCC(value) {
  23291. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23292. }
  23293. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23294. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23295. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23296. var headerLengthInt = 31; // The header length in 32 bit ints
  23297. // Offsets into the header array
  23298. var off_magic = 0;
  23299. var off_size = 1;
  23300. var off_flags = 2;
  23301. var off_height = 3;
  23302. var off_width = 4;
  23303. var off_mipmapCount = 7;
  23304. var off_pfFlags = 20;
  23305. var off_pfFourCC = 21;
  23306. var off_RGBbpp = 22;
  23307. var off_RMask = 23;
  23308. var off_GMask = 24;
  23309. var off_BMask = 25;
  23310. var off_AMask = 26;
  23311. var off_caps1 = 27;
  23312. var off_caps2 = 28;
  23313. ;
  23314. var DDSTools = (function () {
  23315. function DDSTools() {
  23316. }
  23317. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23318. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23319. var mipmapCount = 1;
  23320. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23321. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23322. }
  23323. return {
  23324. width: header[off_width],
  23325. height: header[off_height],
  23326. mipmapCount: mipmapCount,
  23327. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23328. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23329. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23330. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23331. };
  23332. };
  23333. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23334. var byteArray = new Uint8Array(dataLength);
  23335. var srcData = new Uint8Array(arrayBuffer);
  23336. var index = 0;
  23337. for (var y = height - 1; y >= 0; y--) {
  23338. for (var x = 0; x < width; x++) {
  23339. var srcPos = dataOffset + (x + y * width) * 4;
  23340. byteArray[index + 2] = srcData[srcPos];
  23341. byteArray[index + 1] = srcData[srcPos + 1];
  23342. byteArray[index] = srcData[srcPos + 2];
  23343. byteArray[index + 3] = srcData[srcPos + 3];
  23344. index += 4;
  23345. }
  23346. }
  23347. return byteArray;
  23348. };
  23349. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23350. var byteArray = new Uint8Array(dataLength);
  23351. var srcData = new Uint8Array(arrayBuffer);
  23352. var index = 0;
  23353. for (var y = height - 1; y >= 0; y--) {
  23354. for (var x = 0; x < width; x++) {
  23355. var srcPos = dataOffset + (x + y * width) * 3;
  23356. byteArray[index + 2] = srcData[srcPos];
  23357. byteArray[index + 1] = srcData[srcPos + 1];
  23358. byteArray[index] = srcData[srcPos + 2];
  23359. index += 3;
  23360. }
  23361. }
  23362. return byteArray;
  23363. };
  23364. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23365. var byteArray = new Uint8Array(dataLength);
  23366. var srcData = new Uint8Array(arrayBuffer);
  23367. var index = 0;
  23368. for (var y = height - 1; y >= 0; y--) {
  23369. for (var x = 0; x < width; x++) {
  23370. var srcPos = dataOffset + (x + y * width);
  23371. byteArray[index] = srcData[srcPos];
  23372. index++;
  23373. }
  23374. }
  23375. return byteArray;
  23376. };
  23377. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23378. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23379. if (header[off_magic] != DDS_MAGIC) {
  23380. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23381. return;
  23382. }
  23383. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23384. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23385. return;
  23386. }
  23387. if (info.isFourCC) {
  23388. fourCC = header[off_pfFourCC];
  23389. switch (fourCC) {
  23390. case FOURCC_DXT1:
  23391. blockBytes = 8;
  23392. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23393. break;
  23394. case FOURCC_DXT3:
  23395. blockBytes = 16;
  23396. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23397. break;
  23398. case FOURCC_DXT5:
  23399. blockBytes = 16;
  23400. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23401. break;
  23402. default:
  23403. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23404. return;
  23405. }
  23406. }
  23407. mipmapCount = 1;
  23408. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23409. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23410. }
  23411. var bpp = header[off_RGBbpp];
  23412. for (var face = 0; face < faces; face++) {
  23413. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23414. width = header[off_width];
  23415. height = header[off_height];
  23416. dataOffset = header[off_size] + 4;
  23417. for (i = 0; i < mipmapCount; ++i) {
  23418. if (info.isRGB) {
  23419. if (bpp == 24) {
  23420. dataLength = width * height * 3;
  23421. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23422. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23423. }
  23424. else {
  23425. dataLength = width * height * 4;
  23426. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23427. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23428. }
  23429. }
  23430. else if (info.isLuminance) {
  23431. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23432. var unpaddedRowSize = width;
  23433. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23434. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23435. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23436. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23437. }
  23438. else {
  23439. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23440. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23441. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23442. }
  23443. dataOffset += dataLength;
  23444. width *= 0.5;
  23445. height *= 0.5;
  23446. width = Math.max(1.0, width);
  23447. height = Math.max(1.0, height);
  23448. }
  23449. }
  23450. };
  23451. return DDSTools;
  23452. })();
  23453. Internals.DDSTools = DDSTools;
  23454. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23455. })(BABYLON || (BABYLON = {}));
  23456. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23457. (function (BABYLON) {
  23458. var SmartArray = (function () {
  23459. function SmartArray(capacity) {
  23460. this.length = 0;
  23461. this._duplicateId = 0;
  23462. this.data = new Array(capacity);
  23463. this._id = SmartArray._GlobalId++;
  23464. }
  23465. SmartArray.prototype.push = function (value) {
  23466. this.data[this.length++] = value;
  23467. if (this.length > this.data.length) {
  23468. this.data.length *= 2;
  23469. }
  23470. if (!value.__smartArrayFlags) {
  23471. value.__smartArrayFlags = {};
  23472. }
  23473. value.__smartArrayFlags[this._id] = this._duplicateId;
  23474. };
  23475. SmartArray.prototype.pushNoDuplicate = function (value) {
  23476. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23477. return;
  23478. }
  23479. this.push(value);
  23480. };
  23481. SmartArray.prototype.sort = function (compareFn) {
  23482. this.data.sort(compareFn);
  23483. };
  23484. SmartArray.prototype.reset = function () {
  23485. this.length = 0;
  23486. this._duplicateId++;
  23487. };
  23488. SmartArray.prototype.concat = function (array) {
  23489. if (array.length === 0) {
  23490. return;
  23491. }
  23492. if (this.length + array.length > this.data.length) {
  23493. this.data.length = (this.length + array.length) * 2;
  23494. }
  23495. for (var index = 0; index < array.length; index++) {
  23496. this.data[this.length++] = (array.data || array)[index];
  23497. }
  23498. };
  23499. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23500. if (array.length === 0) {
  23501. return;
  23502. }
  23503. if (this.length + array.length > this.data.length) {
  23504. this.data.length = (this.length + array.length) * 2;
  23505. }
  23506. for (var index = 0; index < array.length; index++) {
  23507. var item = (array.data || array)[index];
  23508. this.pushNoDuplicate(item);
  23509. }
  23510. };
  23511. SmartArray.prototype.indexOf = function (value) {
  23512. var position = this.data.indexOf(value);
  23513. if (position >= this.length) {
  23514. return -1;
  23515. }
  23516. return position;
  23517. };
  23518. // Statics
  23519. SmartArray._GlobalId = 0;
  23520. return SmartArray;
  23521. })();
  23522. BABYLON.SmartArray = SmartArray;
  23523. })(BABYLON || (BABYLON = {}));
  23524. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23525. (function (BABYLON) {
  23526. var CannonJSPlugin = (function () {
  23527. function CannonJSPlugin() {
  23528. this._registeredMeshes = [];
  23529. this._physicsMaterials = [];
  23530. this.updateBodyPosition = function (mesh) {
  23531. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23532. var registeredMesh = this._registeredMeshes[index];
  23533. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23534. var body = registeredMesh.body;
  23535. var center = mesh.getBoundingInfo().boundingBox.center;
  23536. body.position.set(center.x, center.z, center.y);
  23537. body.quaternion.x = mesh.rotationQuaternion.x;
  23538. body.quaternion.z = mesh.rotationQuaternion.y;
  23539. body.quaternion.y = mesh.rotationQuaternion.z;
  23540. body.quaternion.w = -mesh.rotationQuaternion.w;
  23541. return;
  23542. }
  23543. }
  23544. };
  23545. }
  23546. CannonJSPlugin.prototype.initialize = function (iterations) {
  23547. if (iterations === void 0) { iterations = 10; }
  23548. this._world = new CANNON.World();
  23549. this._world.broadphase = new CANNON.NaiveBroadphase();
  23550. this._world.solver.iterations = iterations;
  23551. };
  23552. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23553. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23554. };
  23555. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23556. this._world.step(delta);
  23557. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23558. var registeredMesh = this._registeredMeshes[index];
  23559. if (registeredMesh.isChild) {
  23560. continue;
  23561. }
  23562. // Body position
  23563. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23564. var deltaPos = registeredMesh.delta;
  23565. if (deltaPos) {
  23566. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23567. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23568. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23569. }
  23570. else {
  23571. registeredMesh.mesh.position.x = bodyX;
  23572. registeredMesh.mesh.position.y = bodyZ;
  23573. registeredMesh.mesh.position.z = bodyY;
  23574. }
  23575. if (!registeredMesh.mesh.rotationQuaternion) {
  23576. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23577. }
  23578. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23579. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23580. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23581. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23582. }
  23583. };
  23584. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23585. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23586. };
  23587. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23588. this.unregisterMesh(mesh);
  23589. mesh.computeWorldMatrix(true);
  23590. switch (impostor) {
  23591. case BABYLON.PhysicsEngine.SphereImpostor:
  23592. var bbox = mesh.getBoundingInfo().boundingBox;
  23593. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23594. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23595. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23596. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23597. case BABYLON.PhysicsEngine.BoxImpostor:
  23598. bbox = mesh.getBoundingInfo().boundingBox;
  23599. var min = bbox.minimumWorld;
  23600. var max = bbox.maximumWorld;
  23601. var box = max.subtract(min).scale(0.5);
  23602. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23603. case BABYLON.PhysicsEngine.PlaneImpostor:
  23604. return this._createPlane(mesh, options);
  23605. case BABYLON.PhysicsEngine.MeshImpostor:
  23606. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23607. var rawFaces = mesh.getIndices();
  23608. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23609. }
  23610. return null;
  23611. };
  23612. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23613. var shape = new CANNON.Sphere(radius);
  23614. if (!options) {
  23615. return shape;
  23616. }
  23617. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23618. };
  23619. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23620. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23621. if (!options) {
  23622. return shape;
  23623. }
  23624. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23625. };
  23626. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23627. var shape = new CANNON.Plane();
  23628. if (!options) {
  23629. return shape;
  23630. }
  23631. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23632. };
  23633. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23634. var verts = [], faces = [];
  23635. mesh.computeWorldMatrix(true);
  23636. for (var i = 0; i < rawVerts.length; i += 3) {
  23637. var transformed = BABYLON.Vector3.Zero();
  23638. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23639. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23640. }
  23641. for (var j = 0; j < rawFaces.length; j += 3) {
  23642. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23643. }
  23644. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23645. if (!options) {
  23646. return shape;
  23647. }
  23648. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23649. };
  23650. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23651. var index;
  23652. var mat;
  23653. for (index = 0; index < this._physicsMaterials.length; index++) {
  23654. mat = this._physicsMaterials[index];
  23655. if (mat.friction === friction && mat.restitution === restitution) {
  23656. return mat;
  23657. }
  23658. }
  23659. var currentMat = new CANNON.Material();
  23660. currentMat.friction = friction;
  23661. currentMat.restitution = restitution;
  23662. this._physicsMaterials.push(currentMat);
  23663. for (index = 0; index < this._physicsMaterials.length; index++) {
  23664. mat = this._physicsMaterials[index];
  23665. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23666. contactMaterial.contactEquationStiffness = 1e10;
  23667. contactMaterial.contactEquationRegularizationTime = 10;
  23668. this._world.addContactMaterial(contactMaterial);
  23669. }
  23670. return currentMat;
  23671. };
  23672. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23673. var initialRotation = null;
  23674. if (mesh.rotationQuaternion) {
  23675. initialRotation = mesh.rotationQuaternion.clone();
  23676. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23677. }
  23678. // The delta between the mesh position and the mesh bounding box center
  23679. var bbox = mesh.getBoundingInfo().boundingBox;
  23680. var deltaPosition = mesh.position.subtract(bbox.center);
  23681. var material = this._addMaterial(friction, restitution);
  23682. var body = new CANNON.RigidBody(mass, shape, material);
  23683. if (initialRotation) {
  23684. body.quaternion.x = initialRotation.x;
  23685. body.quaternion.z = initialRotation.y;
  23686. body.quaternion.y = initialRotation.z;
  23687. body.quaternion.w = -initialRotation.w;
  23688. }
  23689. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23690. this._world.add(body);
  23691. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23692. return body;
  23693. };
  23694. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23695. var compoundShape = new CANNON.Compound();
  23696. for (var index = 0; index < parts.length; index++) {
  23697. var mesh = parts[index].mesh;
  23698. var shape = this.registerMesh(mesh, parts[index].impostor);
  23699. if (index == 0) {
  23700. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23701. }
  23702. else {
  23703. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23704. }
  23705. }
  23706. var initialMesh = parts[0].mesh;
  23707. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23708. body.parts = parts;
  23709. return body;
  23710. };
  23711. CannonJSPlugin.prototype._unbindBody = function (body) {
  23712. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23713. var registeredMesh = this._registeredMeshes[index];
  23714. if (registeredMesh.body === body) {
  23715. registeredMesh.body = null;
  23716. registeredMesh.delta = 0;
  23717. }
  23718. }
  23719. };
  23720. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23721. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23722. var registeredMesh = this._registeredMeshes[index];
  23723. if (registeredMesh.mesh === mesh) {
  23724. // Remove body
  23725. if (registeredMesh.body) {
  23726. this._world.remove(registeredMesh.body);
  23727. this._unbindBody(registeredMesh.body);
  23728. }
  23729. this._registeredMeshes.splice(index, 1);
  23730. return;
  23731. }
  23732. }
  23733. };
  23734. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23735. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23736. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23737. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23738. var registeredMesh = this._registeredMeshes[index];
  23739. if (registeredMesh.mesh === mesh) {
  23740. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23741. return;
  23742. }
  23743. }
  23744. };
  23745. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23746. var body1 = null, body2 = null;
  23747. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23748. var registeredMesh = this._registeredMeshes[index];
  23749. if (registeredMesh.mesh === mesh1) {
  23750. body1 = registeredMesh.body;
  23751. }
  23752. else if (registeredMesh.mesh === mesh2) {
  23753. body2 = registeredMesh.body;
  23754. }
  23755. }
  23756. if (!body1 || !body2) {
  23757. return false;
  23758. }
  23759. 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));
  23760. this._world.addConstraint(constraint);
  23761. return true;
  23762. };
  23763. CannonJSPlugin.prototype.dispose = function () {
  23764. while (this._registeredMeshes.length) {
  23765. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23766. }
  23767. };
  23768. CannonJSPlugin.prototype.isSupported = function () {
  23769. return window.CANNON !== undefined;
  23770. };
  23771. return CannonJSPlugin;
  23772. })();
  23773. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23774. })(BABYLON || (BABYLON = {}));
  23775. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23776. var BABYLON;
  23777. (function (BABYLON) {
  23778. var Condition = (function () {
  23779. function Condition(actionManager) {
  23780. this._actionManager = actionManager;
  23781. }
  23782. Condition.prototype.isValid = function () {
  23783. return true;
  23784. };
  23785. Condition.prototype._getProperty = function (propertyPath) {
  23786. return this._actionManager._getProperty(propertyPath);
  23787. };
  23788. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23789. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23790. };
  23791. return Condition;
  23792. })();
  23793. BABYLON.Condition = Condition;
  23794. var ValueCondition = (function (_super) {
  23795. __extends(ValueCondition, _super);
  23796. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23797. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23798. _super.call(this, actionManager);
  23799. this.propertyPath = propertyPath;
  23800. this.value = value;
  23801. this.operator = operator;
  23802. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23803. this._property = this._getProperty(this.propertyPath);
  23804. }
  23805. Object.defineProperty(ValueCondition, "IsEqual", {
  23806. get: function () {
  23807. return ValueCondition._IsEqual;
  23808. },
  23809. enumerable: true,
  23810. configurable: true
  23811. });
  23812. Object.defineProperty(ValueCondition, "IsDifferent", {
  23813. get: function () {
  23814. return ValueCondition._IsDifferent;
  23815. },
  23816. enumerable: true,
  23817. configurable: true
  23818. });
  23819. Object.defineProperty(ValueCondition, "IsGreater", {
  23820. get: function () {
  23821. return ValueCondition._IsGreater;
  23822. },
  23823. enumerable: true,
  23824. configurable: true
  23825. });
  23826. Object.defineProperty(ValueCondition, "IsLesser", {
  23827. get: function () {
  23828. return ValueCondition._IsLesser;
  23829. },
  23830. enumerable: true,
  23831. configurable: true
  23832. });
  23833. // Methods
  23834. ValueCondition.prototype.isValid = function () {
  23835. switch (this.operator) {
  23836. case ValueCondition.IsGreater:
  23837. return this._target[this._property] > this.value;
  23838. case ValueCondition.IsLesser:
  23839. return this._target[this._property] < this.value;
  23840. case ValueCondition.IsEqual:
  23841. case ValueCondition.IsDifferent:
  23842. var check;
  23843. if (this.value.equals) {
  23844. check = this.value.equals(this._target[this._property]);
  23845. }
  23846. else {
  23847. check = this.value === this._target[this._property];
  23848. }
  23849. return this.operator === ValueCondition.IsEqual ? check : !check;
  23850. }
  23851. return false;
  23852. };
  23853. // Statics
  23854. ValueCondition._IsEqual = 0;
  23855. ValueCondition._IsDifferent = 1;
  23856. ValueCondition._IsGreater = 2;
  23857. ValueCondition._IsLesser = 3;
  23858. return ValueCondition;
  23859. })(Condition);
  23860. BABYLON.ValueCondition = ValueCondition;
  23861. var PredicateCondition = (function (_super) {
  23862. __extends(PredicateCondition, _super);
  23863. function PredicateCondition(actionManager, predicate) {
  23864. _super.call(this, actionManager);
  23865. this.predicate = predicate;
  23866. }
  23867. PredicateCondition.prototype.isValid = function () {
  23868. return this.predicate();
  23869. };
  23870. return PredicateCondition;
  23871. })(Condition);
  23872. BABYLON.PredicateCondition = PredicateCondition;
  23873. var StateCondition = (function (_super) {
  23874. __extends(StateCondition, _super);
  23875. function StateCondition(actionManager, target, value) {
  23876. _super.call(this, actionManager);
  23877. this.value = value;
  23878. this._target = target;
  23879. }
  23880. // Methods
  23881. StateCondition.prototype.isValid = function () {
  23882. return this._target.state === this.value;
  23883. };
  23884. return StateCondition;
  23885. })(Condition);
  23886. BABYLON.StateCondition = StateCondition;
  23887. })(BABYLON || (BABYLON = {}));
  23888. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23889. (function (BABYLON) {
  23890. var Action = (function () {
  23891. function Action(triggerOptions, condition) {
  23892. this.triggerOptions = triggerOptions;
  23893. if (triggerOptions.parameter) {
  23894. this.trigger = triggerOptions.trigger;
  23895. this._triggerParameter = triggerOptions.parameter;
  23896. }
  23897. else {
  23898. this.trigger = triggerOptions;
  23899. }
  23900. this._nextActiveAction = this;
  23901. this._condition = condition;
  23902. }
  23903. // Methods
  23904. Action.prototype._prepare = function () {
  23905. };
  23906. Action.prototype.getTriggerParameter = function () {
  23907. return this._triggerParameter;
  23908. };
  23909. Action.prototype._executeCurrent = function (evt) {
  23910. if (this._nextActiveAction._condition) {
  23911. var condition = this._nextActiveAction._condition;
  23912. var currentRenderId = this._actionManager.getScene().getRenderId();
  23913. // We cache the current evaluation for the current frame
  23914. if (condition._evaluationId === currentRenderId) {
  23915. if (!condition._currentResult) {
  23916. return;
  23917. }
  23918. }
  23919. else {
  23920. condition._evaluationId = currentRenderId;
  23921. if (!condition.isValid()) {
  23922. condition._currentResult = false;
  23923. return;
  23924. }
  23925. condition._currentResult = true;
  23926. }
  23927. }
  23928. this._nextActiveAction.execute(evt);
  23929. if (this._nextActiveAction._child) {
  23930. if (!this._nextActiveAction._child._actionManager) {
  23931. this._nextActiveAction._child._actionManager = this._actionManager;
  23932. }
  23933. this._nextActiveAction = this._nextActiveAction._child;
  23934. }
  23935. else {
  23936. this._nextActiveAction = this;
  23937. }
  23938. };
  23939. Action.prototype.execute = function (evt) {
  23940. };
  23941. Action.prototype.then = function (action) {
  23942. this._child = action;
  23943. action._actionManager = this._actionManager;
  23944. action._prepare();
  23945. return action;
  23946. };
  23947. Action.prototype._getProperty = function (propertyPath) {
  23948. return this._actionManager._getProperty(propertyPath);
  23949. };
  23950. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23951. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23952. };
  23953. return Action;
  23954. })();
  23955. BABYLON.Action = Action;
  23956. })(BABYLON || (BABYLON = {}));
  23957. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23958. (function (BABYLON) {
  23959. /**
  23960. * ActionEvent is the event beint sent when an action is triggered.
  23961. */
  23962. var ActionEvent = (function () {
  23963. /**
  23964. * @constructor
  23965. * @param source The mesh that triggered the action.
  23966. * @param pointerX the X mouse cursor position at the time of the event
  23967. * @param pointerY the Y mouse cursor position at the time of the event
  23968. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23969. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23970. */
  23971. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23972. this.source = source;
  23973. this.pointerX = pointerX;
  23974. this.pointerY = pointerY;
  23975. this.meshUnderPointer = meshUnderPointer;
  23976. this.sourceEvent = sourceEvent;
  23977. }
  23978. /**
  23979. * Helper function to auto-create an ActionEvent from a source mesh.
  23980. * @param source the source mesh that triggered the event
  23981. * @param evt {Event} The original (browser) event
  23982. */
  23983. ActionEvent.CreateNew = function (source, evt) {
  23984. var scene = source.getScene();
  23985. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23986. };
  23987. /**
  23988. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23989. * @param scene the scene where the event occurred
  23990. * @param evt {Event} The original (browser) event
  23991. */
  23992. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23993. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23994. };
  23995. return ActionEvent;
  23996. })();
  23997. BABYLON.ActionEvent = ActionEvent;
  23998. /**
  23999. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  24000. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  24001. */
  24002. var ActionManager = (function () {
  24003. function ActionManager(scene) {
  24004. // Members
  24005. this.actions = new Array();
  24006. this._scene = scene;
  24007. scene._actionManagers.push(this);
  24008. }
  24009. Object.defineProperty(ActionManager, "NothingTrigger", {
  24010. get: function () {
  24011. return ActionManager._NothingTrigger;
  24012. },
  24013. enumerable: true,
  24014. configurable: true
  24015. });
  24016. Object.defineProperty(ActionManager, "OnPickTrigger", {
  24017. get: function () {
  24018. return ActionManager._OnPickTrigger;
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  24024. get: function () {
  24025. return ActionManager._OnLeftPickTrigger;
  24026. },
  24027. enumerable: true,
  24028. configurable: true
  24029. });
  24030. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  24031. get: function () {
  24032. return ActionManager._OnRightPickTrigger;
  24033. },
  24034. enumerable: true,
  24035. configurable: true
  24036. });
  24037. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  24038. get: function () {
  24039. return ActionManager._OnCenterPickTrigger;
  24040. },
  24041. enumerable: true,
  24042. configurable: true
  24043. });
  24044. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  24045. get: function () {
  24046. return ActionManager._OnPointerOverTrigger;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  24052. get: function () {
  24053. return ActionManager._OnPointerOutTrigger;
  24054. },
  24055. enumerable: true,
  24056. configurable: true
  24057. });
  24058. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  24059. get: function () {
  24060. return ActionManager._OnEveryFrameTrigger;
  24061. },
  24062. enumerable: true,
  24063. configurable: true
  24064. });
  24065. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  24066. get: function () {
  24067. return ActionManager._OnIntersectionEnterTrigger;
  24068. },
  24069. enumerable: true,
  24070. configurable: true
  24071. });
  24072. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  24073. get: function () {
  24074. return ActionManager._OnIntersectionExitTrigger;
  24075. },
  24076. enumerable: true,
  24077. configurable: true
  24078. });
  24079. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  24080. get: function () {
  24081. return ActionManager._OnKeyDownTrigger;
  24082. },
  24083. enumerable: true,
  24084. configurable: true
  24085. });
  24086. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  24087. get: function () {
  24088. return ActionManager._OnKeyUpTrigger;
  24089. },
  24090. enumerable: true,
  24091. configurable: true
  24092. });
  24093. // Methods
  24094. ActionManager.prototype.dispose = function () {
  24095. var index = this._scene._actionManagers.indexOf(this);
  24096. if (index > -1) {
  24097. this._scene._actionManagers.splice(index, 1);
  24098. }
  24099. };
  24100. ActionManager.prototype.getScene = function () {
  24101. return this._scene;
  24102. };
  24103. /**
  24104. * Does this action manager handles actions of any of the given triggers
  24105. * @param {number[]} triggers - the triggers to be tested
  24106. * @return {boolean} whether one (or more) of the triggers is handeled
  24107. */
  24108. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  24109. for (var index = 0; index < this.actions.length; index++) {
  24110. var action = this.actions[index];
  24111. if (triggers.indexOf(action.trigger) > -1) {
  24112. return true;
  24113. }
  24114. }
  24115. return false;
  24116. };
  24117. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  24118. /**
  24119. * Does this action manager has pointer triggers
  24120. * @return {boolean} whether or not it has pointer triggers
  24121. */
  24122. get: function () {
  24123. for (var index = 0; index < this.actions.length; index++) {
  24124. var action = this.actions[index];
  24125. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  24126. return true;
  24127. }
  24128. }
  24129. return false;
  24130. },
  24131. enumerable: true,
  24132. configurable: true
  24133. });
  24134. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  24135. /**
  24136. * Does this action manager has pick triggers
  24137. * @return {boolean} whether or not it has pick triggers
  24138. */
  24139. get: function () {
  24140. for (var index = 0; index < this.actions.length; index++) {
  24141. var action = this.actions[index];
  24142. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  24143. return true;
  24144. }
  24145. }
  24146. return false;
  24147. },
  24148. enumerable: true,
  24149. configurable: true
  24150. });
  24151. /**
  24152. * Registers an action to this action manager
  24153. * @param {BABYLON.Action} action - the action to be registered
  24154. * @return {BABYLON.Action} the action amended (prepared) after registration
  24155. */
  24156. ActionManager.prototype.registerAction = function (action) {
  24157. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  24158. if (this.getScene().actionManager !== this) {
  24159. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  24160. return null;
  24161. }
  24162. }
  24163. this.actions.push(action);
  24164. action._actionManager = this;
  24165. action._prepare();
  24166. return action;
  24167. };
  24168. /**
  24169. * Process a specific trigger
  24170. * @param {number} trigger - the trigger to process
  24171. * @param evt {BABYLON.ActionEvent} the event details to be processed
  24172. */
  24173. ActionManager.prototype.processTrigger = function (trigger, evt) {
  24174. for (var index = 0; index < this.actions.length; index++) {
  24175. var action = this.actions[index];
  24176. if (action.trigger === trigger) {
  24177. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  24178. var parameter = action.getTriggerParameter();
  24179. if (parameter) {
  24180. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  24181. var actualkey = String.fromCharCode(unicode).toLowerCase();
  24182. if (actualkey !== parameter.toLowerCase()) {
  24183. continue;
  24184. }
  24185. }
  24186. }
  24187. action._executeCurrent(evt);
  24188. }
  24189. }
  24190. };
  24191. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  24192. var properties = propertyPath.split(".");
  24193. for (var index = 0; index < properties.length - 1; index++) {
  24194. target = target[properties[index]];
  24195. }
  24196. return target;
  24197. };
  24198. ActionManager.prototype._getProperty = function (propertyPath) {
  24199. var properties = propertyPath.split(".");
  24200. return properties[properties.length - 1];
  24201. };
  24202. // Statics
  24203. ActionManager._NothingTrigger = 0;
  24204. ActionManager._OnPickTrigger = 1;
  24205. ActionManager._OnLeftPickTrigger = 2;
  24206. ActionManager._OnRightPickTrigger = 3;
  24207. ActionManager._OnCenterPickTrigger = 4;
  24208. ActionManager._OnPointerOverTrigger = 5;
  24209. ActionManager._OnPointerOutTrigger = 6;
  24210. ActionManager._OnEveryFrameTrigger = 7;
  24211. ActionManager._OnIntersectionEnterTrigger = 8;
  24212. ActionManager._OnIntersectionExitTrigger = 9;
  24213. ActionManager._OnKeyDownTrigger = 10;
  24214. ActionManager._OnKeyUpTrigger = 11;
  24215. return ActionManager;
  24216. })();
  24217. BABYLON.ActionManager = ActionManager;
  24218. })(BABYLON || (BABYLON = {}));
  24219. //# sourceMappingURL=babylon.actionManager.js.map
  24220. var BABYLON;
  24221. (function (BABYLON) {
  24222. var InterpolateValueAction = (function (_super) {
  24223. __extends(InterpolateValueAction, _super);
  24224. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  24225. if (duration === void 0) { duration = 1000; }
  24226. _super.call(this, triggerOptions, condition);
  24227. this.propertyPath = propertyPath;
  24228. this.value = value;
  24229. this.duration = duration;
  24230. this.stopOtherAnimations = stopOtherAnimations;
  24231. this._target = target;
  24232. }
  24233. InterpolateValueAction.prototype._prepare = function () {
  24234. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24235. this._property = this._getProperty(this.propertyPath);
  24236. };
  24237. InterpolateValueAction.prototype.execute = function () {
  24238. var scene = this._actionManager.getScene();
  24239. var keys = [
  24240. {
  24241. frame: 0,
  24242. value: this._target[this._property]
  24243. },
  24244. {
  24245. frame: 100,
  24246. value: this.value
  24247. }
  24248. ];
  24249. var dataType;
  24250. if (typeof this.value === "number") {
  24251. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  24252. }
  24253. else if (this.value instanceof BABYLON.Color3) {
  24254. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  24255. }
  24256. else if (this.value instanceof BABYLON.Vector3) {
  24257. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  24258. }
  24259. else if (this.value instanceof BABYLON.Matrix) {
  24260. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  24261. }
  24262. else if (this.value instanceof BABYLON.Quaternion) {
  24263. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  24264. }
  24265. else {
  24266. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  24267. return;
  24268. }
  24269. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  24270. animation.setKeys(keys);
  24271. if (this.stopOtherAnimations) {
  24272. scene.stopAnimation(this._target);
  24273. }
  24274. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24275. };
  24276. return InterpolateValueAction;
  24277. })(BABYLON.Action);
  24278. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24279. })(BABYLON || (BABYLON = {}));
  24280. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24281. var BABYLON;
  24282. (function (BABYLON) {
  24283. var SwitchBooleanAction = (function (_super) {
  24284. __extends(SwitchBooleanAction, _super);
  24285. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24286. _super.call(this, triggerOptions, condition);
  24287. this.propertyPath = propertyPath;
  24288. this._target = target;
  24289. }
  24290. SwitchBooleanAction.prototype._prepare = function () {
  24291. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24292. this._property = this._getProperty(this.propertyPath);
  24293. };
  24294. SwitchBooleanAction.prototype.execute = function () {
  24295. this._target[this._property] = !this._target[this._property];
  24296. };
  24297. return SwitchBooleanAction;
  24298. })(BABYLON.Action);
  24299. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24300. var SetStateAction = (function (_super) {
  24301. __extends(SetStateAction, _super);
  24302. function SetStateAction(triggerOptions, target, value, condition) {
  24303. _super.call(this, triggerOptions, condition);
  24304. this.value = value;
  24305. this._target = target;
  24306. }
  24307. SetStateAction.prototype.execute = function () {
  24308. this._target.state = this.value;
  24309. };
  24310. return SetStateAction;
  24311. })(BABYLON.Action);
  24312. BABYLON.SetStateAction = SetStateAction;
  24313. var SetValueAction = (function (_super) {
  24314. __extends(SetValueAction, _super);
  24315. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24316. _super.call(this, triggerOptions, condition);
  24317. this.propertyPath = propertyPath;
  24318. this.value = value;
  24319. this._target = target;
  24320. }
  24321. SetValueAction.prototype._prepare = function () {
  24322. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24323. this._property = this._getProperty(this.propertyPath);
  24324. };
  24325. SetValueAction.prototype.execute = function () {
  24326. this._target[this._property] = this.value;
  24327. };
  24328. return SetValueAction;
  24329. })(BABYLON.Action);
  24330. BABYLON.SetValueAction = SetValueAction;
  24331. var IncrementValueAction = (function (_super) {
  24332. __extends(IncrementValueAction, _super);
  24333. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24334. _super.call(this, triggerOptions, condition);
  24335. this.propertyPath = propertyPath;
  24336. this.value = value;
  24337. this._target = target;
  24338. }
  24339. IncrementValueAction.prototype._prepare = function () {
  24340. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24341. this._property = this._getProperty(this.propertyPath);
  24342. if (typeof this._target[this._property] !== "number") {
  24343. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24344. }
  24345. };
  24346. IncrementValueAction.prototype.execute = function () {
  24347. this._target[this._property] += this.value;
  24348. };
  24349. return IncrementValueAction;
  24350. })(BABYLON.Action);
  24351. BABYLON.IncrementValueAction = IncrementValueAction;
  24352. var PlayAnimationAction = (function (_super) {
  24353. __extends(PlayAnimationAction, _super);
  24354. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24355. _super.call(this, triggerOptions, condition);
  24356. this.from = from;
  24357. this.to = to;
  24358. this.loop = loop;
  24359. this._target = target;
  24360. }
  24361. PlayAnimationAction.prototype._prepare = function () {
  24362. };
  24363. PlayAnimationAction.prototype.execute = function () {
  24364. var scene = this._actionManager.getScene();
  24365. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24366. };
  24367. return PlayAnimationAction;
  24368. })(BABYLON.Action);
  24369. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24370. var StopAnimationAction = (function (_super) {
  24371. __extends(StopAnimationAction, _super);
  24372. function StopAnimationAction(triggerOptions, target, condition) {
  24373. _super.call(this, triggerOptions, condition);
  24374. this._target = target;
  24375. }
  24376. StopAnimationAction.prototype._prepare = function () {
  24377. };
  24378. StopAnimationAction.prototype.execute = function () {
  24379. var scene = this._actionManager.getScene();
  24380. scene.stopAnimation(this._target);
  24381. };
  24382. return StopAnimationAction;
  24383. })(BABYLON.Action);
  24384. BABYLON.StopAnimationAction = StopAnimationAction;
  24385. var DoNothingAction = (function (_super) {
  24386. __extends(DoNothingAction, _super);
  24387. function DoNothingAction(triggerOptions, condition) {
  24388. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24389. _super.call(this, triggerOptions, condition);
  24390. }
  24391. DoNothingAction.prototype.execute = function () {
  24392. };
  24393. return DoNothingAction;
  24394. })(BABYLON.Action);
  24395. BABYLON.DoNothingAction = DoNothingAction;
  24396. var CombineAction = (function (_super) {
  24397. __extends(CombineAction, _super);
  24398. function CombineAction(triggerOptions, children, condition) {
  24399. _super.call(this, triggerOptions, condition);
  24400. this.children = children;
  24401. }
  24402. CombineAction.prototype._prepare = function () {
  24403. for (var index = 0; index < this.children.length; index++) {
  24404. this.children[index]._actionManager = this._actionManager;
  24405. this.children[index]._prepare();
  24406. }
  24407. };
  24408. CombineAction.prototype.execute = function (evt) {
  24409. for (var index = 0; index < this.children.length; index++) {
  24410. this.children[index].execute(evt);
  24411. }
  24412. };
  24413. return CombineAction;
  24414. })(BABYLON.Action);
  24415. BABYLON.CombineAction = CombineAction;
  24416. var ExecuteCodeAction = (function (_super) {
  24417. __extends(ExecuteCodeAction, _super);
  24418. function ExecuteCodeAction(triggerOptions, func, condition) {
  24419. _super.call(this, triggerOptions, condition);
  24420. this.func = func;
  24421. }
  24422. ExecuteCodeAction.prototype.execute = function (evt) {
  24423. this.func(evt);
  24424. };
  24425. return ExecuteCodeAction;
  24426. })(BABYLON.Action);
  24427. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24428. var SetParentAction = (function (_super) {
  24429. __extends(SetParentAction, _super);
  24430. function SetParentAction(triggerOptions, target, parent, condition) {
  24431. _super.call(this, triggerOptions, condition);
  24432. this._target = target;
  24433. this._parent = parent;
  24434. }
  24435. SetParentAction.prototype._prepare = function () {
  24436. };
  24437. SetParentAction.prototype.execute = function () {
  24438. if (this._target.parent === this._parent) {
  24439. return;
  24440. }
  24441. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24442. invertParentWorldMatrix.invert();
  24443. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24444. this._target.parent = this._parent;
  24445. };
  24446. return SetParentAction;
  24447. })(BABYLON.Action);
  24448. BABYLON.SetParentAction = SetParentAction;
  24449. var PlaySoundAction = (function (_super) {
  24450. __extends(PlaySoundAction, _super);
  24451. function PlaySoundAction(triggerOptions, sound, condition) {
  24452. _super.call(this, triggerOptions, condition);
  24453. this._sound = sound;
  24454. }
  24455. PlaySoundAction.prototype._prepare = function () {
  24456. };
  24457. PlaySoundAction.prototype.execute = function () {
  24458. if (this._sound !== undefined)
  24459. this._sound.play();
  24460. };
  24461. return PlaySoundAction;
  24462. })(BABYLON.Action);
  24463. BABYLON.PlaySoundAction = PlaySoundAction;
  24464. var StopSoundAction = (function (_super) {
  24465. __extends(StopSoundAction, _super);
  24466. function StopSoundAction(triggerOptions, sound, condition) {
  24467. _super.call(this, triggerOptions, condition);
  24468. this._sound = sound;
  24469. }
  24470. StopSoundAction.prototype._prepare = function () {
  24471. };
  24472. StopSoundAction.prototype.execute = function () {
  24473. if (this._sound !== undefined)
  24474. this._sound.stop();
  24475. };
  24476. return StopSoundAction;
  24477. })(BABYLON.Action);
  24478. BABYLON.StopSoundAction = StopSoundAction;
  24479. })(BABYLON || (BABYLON = {}));
  24480. //# sourceMappingURL=babylon.directActions.js.map
  24481. var BABYLON;
  24482. (function (BABYLON) {
  24483. var Geometry = (function () {
  24484. function Geometry(id, scene, vertexData, updatable, mesh) {
  24485. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24486. this._totalVertices = 0;
  24487. this._indices = [];
  24488. this.id = id;
  24489. this._engine = scene.getEngine();
  24490. this._meshes = [];
  24491. this._scene = scene;
  24492. // vertexData
  24493. if (vertexData) {
  24494. this.setAllVerticesData(vertexData, updatable);
  24495. }
  24496. else {
  24497. this._totalVertices = 0;
  24498. this._indices = [];
  24499. }
  24500. // applyToMesh
  24501. if (mesh) {
  24502. this.applyToMesh(mesh);
  24503. mesh.computeWorldMatrix(true);
  24504. }
  24505. }
  24506. Geometry.prototype.getScene = function () {
  24507. return this._scene;
  24508. };
  24509. Geometry.prototype.getEngine = function () {
  24510. return this._engine;
  24511. };
  24512. Geometry.prototype.isReady = function () {
  24513. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24514. };
  24515. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24516. vertexData.applyToGeometry(this, updatable);
  24517. };
  24518. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24519. this._vertexBuffers = this._vertexBuffers || {};
  24520. if (this._vertexBuffers[kind]) {
  24521. this._vertexBuffers[kind].dispose();
  24522. }
  24523. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24524. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24525. stride = this._vertexBuffers[kind].getStrideSize();
  24526. this._totalVertices = data.length / stride;
  24527. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24528. var meshes = this._meshes;
  24529. var numOfMeshes = meshes.length;
  24530. for (var index = 0; index < numOfMeshes; index++) {
  24531. var mesh = meshes[index];
  24532. mesh._resetPointsArrayCache();
  24533. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24534. mesh._createGlobalSubMesh();
  24535. mesh.computeWorldMatrix(true);
  24536. }
  24537. }
  24538. };
  24539. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24540. var vertexBuffer = this.getVertexBuffer(kind);
  24541. if (!vertexBuffer) {
  24542. return;
  24543. }
  24544. vertexBuffer.updateDirectly(data, offset);
  24545. };
  24546. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24547. var vertexBuffer = this.getVertexBuffer(kind);
  24548. if (!vertexBuffer) {
  24549. return;
  24550. }
  24551. vertexBuffer.update(data);
  24552. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24553. var extend;
  24554. var stride = vertexBuffer.getStrideSize();
  24555. this._totalVertices = data.length / stride;
  24556. if (updateExtends) {
  24557. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24558. }
  24559. var meshes = this._meshes;
  24560. var numOfMeshes = meshes.length;
  24561. for (var index = 0; index < numOfMeshes; index++) {
  24562. var mesh = meshes[index];
  24563. mesh._resetPointsArrayCache();
  24564. if (updateExtends) {
  24565. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24566. }
  24567. }
  24568. }
  24569. };
  24570. Geometry.prototype.getTotalVertices = function () {
  24571. if (!this.isReady()) {
  24572. return 0;
  24573. }
  24574. return this._totalVertices;
  24575. };
  24576. Geometry.prototype.getVerticesData = function (kind) {
  24577. var vertexBuffer = this.getVertexBuffer(kind);
  24578. if (!vertexBuffer) {
  24579. return null;
  24580. }
  24581. return vertexBuffer.getData();
  24582. };
  24583. Geometry.prototype.getVertexBuffer = function (kind) {
  24584. if (!this.isReady()) {
  24585. return null;
  24586. }
  24587. return this._vertexBuffers[kind];
  24588. };
  24589. Geometry.prototype.getVertexBuffers = function () {
  24590. if (!this.isReady()) {
  24591. return null;
  24592. }
  24593. return this._vertexBuffers;
  24594. };
  24595. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24596. if (!this._vertexBuffers) {
  24597. if (this._delayInfo) {
  24598. return this._delayInfo.indexOf(kind) !== -1;
  24599. }
  24600. return false;
  24601. }
  24602. return this._vertexBuffers[kind] !== undefined;
  24603. };
  24604. Geometry.prototype.getVerticesDataKinds = function () {
  24605. var result = [];
  24606. if (!this._vertexBuffers && this._delayInfo) {
  24607. for (var kind in this._delayInfo) {
  24608. result.push(kind);
  24609. }
  24610. }
  24611. else {
  24612. for (kind in this._vertexBuffers) {
  24613. result.push(kind);
  24614. }
  24615. }
  24616. return result;
  24617. };
  24618. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24619. if (this._indexBuffer) {
  24620. this._engine._releaseBuffer(this._indexBuffer);
  24621. }
  24622. this._indices = indices;
  24623. if (this._meshes.length !== 0 && this._indices) {
  24624. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24625. }
  24626. if (totalVertices !== undefined) {
  24627. this._totalVertices = totalVertices;
  24628. }
  24629. var meshes = this._meshes;
  24630. var numOfMeshes = meshes.length;
  24631. for (var index = 0; index < numOfMeshes; index++) {
  24632. meshes[index]._createGlobalSubMesh();
  24633. }
  24634. };
  24635. Geometry.prototype.getTotalIndices = function () {
  24636. if (!this.isReady()) {
  24637. return 0;
  24638. }
  24639. return this._indices.length;
  24640. };
  24641. Geometry.prototype.getIndices = function () {
  24642. if (!this.isReady()) {
  24643. return null;
  24644. }
  24645. return this._indices;
  24646. };
  24647. Geometry.prototype.getIndexBuffer = function () {
  24648. if (!this.isReady()) {
  24649. return null;
  24650. }
  24651. return this._indexBuffer;
  24652. };
  24653. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24654. var meshes = this._meshes;
  24655. var index = meshes.indexOf(mesh);
  24656. if (index === -1) {
  24657. return;
  24658. }
  24659. for (var kind in this._vertexBuffers) {
  24660. this._vertexBuffers[kind].dispose();
  24661. }
  24662. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24663. this._indexBuffer = null;
  24664. }
  24665. meshes.splice(index, 1);
  24666. mesh._geometry = null;
  24667. if (meshes.length === 0 && shouldDispose) {
  24668. this.dispose();
  24669. }
  24670. };
  24671. Geometry.prototype.applyToMesh = function (mesh) {
  24672. if (mesh._geometry === this) {
  24673. return;
  24674. }
  24675. var previousGeometry = mesh._geometry;
  24676. if (previousGeometry) {
  24677. previousGeometry.releaseForMesh(mesh);
  24678. }
  24679. var meshes = this._meshes;
  24680. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24681. mesh._geometry = this;
  24682. this._scene.pushGeometry(this);
  24683. meshes.push(mesh);
  24684. if (this.isReady()) {
  24685. this._applyToMesh(mesh);
  24686. }
  24687. else {
  24688. mesh._boundingInfo = this._boundingInfo;
  24689. }
  24690. };
  24691. Geometry.prototype._applyToMesh = function (mesh) {
  24692. var numOfMeshes = this._meshes.length;
  24693. for (var kind in this._vertexBuffers) {
  24694. if (numOfMeshes === 1) {
  24695. this._vertexBuffers[kind].create();
  24696. }
  24697. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24698. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24699. mesh._resetPointsArrayCache();
  24700. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24701. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24702. mesh._createGlobalSubMesh();
  24703. //bounding info was just created again, world matrix should be applied again.
  24704. mesh._updateBoundingInfo();
  24705. }
  24706. }
  24707. // indexBuffer
  24708. if (numOfMeshes === 1 && this._indices) {
  24709. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24710. }
  24711. if (this._indexBuffer) {
  24712. this._indexBuffer.references = numOfMeshes;
  24713. }
  24714. };
  24715. Geometry.prototype.load = function (scene, onLoaded) {
  24716. var _this = this;
  24717. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24718. return;
  24719. }
  24720. if (this.isReady()) {
  24721. if (onLoaded) {
  24722. onLoaded();
  24723. }
  24724. return;
  24725. }
  24726. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24727. scene._addPendingData(this);
  24728. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24729. _this._delayLoadingFunction(JSON.parse(data), _this);
  24730. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24731. _this._delayInfo = [];
  24732. scene._removePendingData(_this);
  24733. var meshes = _this._meshes;
  24734. var numOfMeshes = meshes.length;
  24735. for (var index = 0; index < numOfMeshes; index++) {
  24736. _this._applyToMesh(meshes[index]);
  24737. }
  24738. if (onLoaded) {
  24739. onLoaded();
  24740. }
  24741. }, function () {
  24742. }, scene.database);
  24743. };
  24744. Geometry.prototype.dispose = function () {
  24745. var meshes = this._meshes;
  24746. var numOfMeshes = meshes.length;
  24747. var index;
  24748. for (index = 0; index < numOfMeshes; index++) {
  24749. this.releaseForMesh(meshes[index]);
  24750. }
  24751. this._meshes = [];
  24752. for (var kind in this._vertexBuffers) {
  24753. this._vertexBuffers[kind].dispose();
  24754. }
  24755. this._vertexBuffers = [];
  24756. this._totalVertices = 0;
  24757. if (this._indexBuffer) {
  24758. this._engine._releaseBuffer(this._indexBuffer);
  24759. }
  24760. this._indexBuffer = null;
  24761. this._indices = [];
  24762. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24763. this.delayLoadingFile = null;
  24764. this._delayLoadingFunction = null;
  24765. this._delayInfo = [];
  24766. this._boundingInfo = null; // todo: .dispose()
  24767. var geometries = this._scene.getGeometries();
  24768. index = geometries.indexOf(this);
  24769. if (index > -1) {
  24770. geometries.splice(index, 1);
  24771. }
  24772. };
  24773. Geometry.prototype.copy = function (id) {
  24774. var vertexData = new BABYLON.VertexData();
  24775. vertexData.indices = [];
  24776. var indices = this.getIndices();
  24777. for (var index = 0; index < indices.length; index++) {
  24778. vertexData.indices.push(indices[index]);
  24779. }
  24780. var updatable = false;
  24781. var stopChecking = false;
  24782. for (var kind in this._vertexBuffers) {
  24783. // using slice() to make a copy of the array and not just reference it
  24784. vertexData.set(this.getVerticesData(kind).slice(0), kind);
  24785. if (!stopChecking) {
  24786. updatable = this.getVertexBuffer(kind).isUpdatable();
  24787. stopChecking = !updatable;
  24788. }
  24789. }
  24790. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24791. geometry.delayLoadState = this.delayLoadState;
  24792. geometry.delayLoadingFile = this.delayLoadingFile;
  24793. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24794. for (kind in this._delayInfo) {
  24795. geometry._delayInfo = geometry._delayInfo || [];
  24796. geometry._delayInfo.push(kind);
  24797. }
  24798. // Bounding info
  24799. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24800. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24801. return geometry;
  24802. };
  24803. // Statics
  24804. Geometry.ExtractFromMesh = function (mesh, id) {
  24805. var geometry = mesh._geometry;
  24806. if (!geometry) {
  24807. return null;
  24808. }
  24809. return geometry.copy(id);
  24810. };
  24811. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24812. // be aware Math.random() could cause collisions
  24813. Geometry.RandomId = function () {
  24814. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24815. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24816. return v.toString(16);
  24817. });
  24818. };
  24819. return Geometry;
  24820. })();
  24821. BABYLON.Geometry = Geometry;
  24822. /////// Primitives //////////////////////////////////////////////
  24823. var Geometry;
  24824. (function (Geometry) {
  24825. var Primitives;
  24826. (function (Primitives) {
  24827. /// Abstract class
  24828. var _Primitive = (function (_super) {
  24829. __extends(_Primitive, _super);
  24830. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24831. this._beingRegenerated = true;
  24832. this._canBeRegenerated = canBeRegenerated;
  24833. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24834. this._beingRegenerated = false;
  24835. }
  24836. _Primitive.prototype.canBeRegenerated = function () {
  24837. return this._canBeRegenerated;
  24838. };
  24839. _Primitive.prototype.regenerate = function () {
  24840. if (!this._canBeRegenerated) {
  24841. return;
  24842. }
  24843. this._beingRegenerated = true;
  24844. this.setAllVerticesData(this._regenerateVertexData(), false);
  24845. this._beingRegenerated = false;
  24846. };
  24847. _Primitive.prototype.asNewGeometry = function (id) {
  24848. return _super.prototype.copy.call(this, id);
  24849. };
  24850. // overrides
  24851. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24852. if (!this._beingRegenerated) {
  24853. return;
  24854. }
  24855. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24856. };
  24857. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24858. if (!this._beingRegenerated) {
  24859. return;
  24860. }
  24861. _super.prototype.setVerticesData.call(this, kind, data, false);
  24862. };
  24863. // to override
  24864. // protected
  24865. _Primitive.prototype._regenerateVertexData = function () {
  24866. throw new Error("Abstract method");
  24867. };
  24868. _Primitive.prototype.copy = function (id) {
  24869. throw new Error("Must be overriden in sub-classes.");
  24870. };
  24871. return _Primitive;
  24872. })(Geometry);
  24873. Primitives._Primitive = _Primitive;
  24874. var Ribbon = (function (_super) {
  24875. __extends(Ribbon, _super);
  24876. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24877. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24878. this.pathArray = pathArray;
  24879. this.closeArray = closeArray;
  24880. this.closePath = closePath;
  24881. this.offset = offset;
  24882. this.side = side;
  24883. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24884. }
  24885. Ribbon.prototype._regenerateVertexData = function () {
  24886. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24887. };
  24888. Ribbon.prototype.copy = function (id) {
  24889. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24890. };
  24891. return Ribbon;
  24892. })(_Primitive);
  24893. Primitives.Ribbon = Ribbon;
  24894. var Box = (function (_super) {
  24895. __extends(Box, _super);
  24896. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24897. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24898. this.size = size;
  24899. this.side = side;
  24900. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24901. }
  24902. Box.prototype._regenerateVertexData = function () {
  24903. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24904. };
  24905. Box.prototype.copy = function (id) {
  24906. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24907. };
  24908. return Box;
  24909. })(_Primitive);
  24910. Primitives.Box = Box;
  24911. var Sphere = (function (_super) {
  24912. __extends(Sphere, _super);
  24913. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24914. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24915. this.segments = segments;
  24916. this.diameter = diameter;
  24917. this.side = side;
  24918. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24919. }
  24920. Sphere.prototype._regenerateVertexData = function () {
  24921. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24922. };
  24923. Sphere.prototype.copy = function (id) {
  24924. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24925. };
  24926. return Sphere;
  24927. })(_Primitive);
  24928. Primitives.Sphere = Sphere;
  24929. var Cylinder = (function (_super) {
  24930. __extends(Cylinder, _super);
  24931. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24932. if (subdivisions === void 0) { subdivisions = 1; }
  24933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24934. this.height = height;
  24935. this.diameterTop = diameterTop;
  24936. this.diameterBottom = diameterBottom;
  24937. this.tessellation = tessellation;
  24938. this.subdivisions = subdivisions;
  24939. this.side = side;
  24940. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24941. }
  24942. Cylinder.prototype._regenerateVertexData = function () {
  24943. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24944. };
  24945. Cylinder.prototype.copy = function (id) {
  24946. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24947. };
  24948. return Cylinder;
  24949. })(_Primitive);
  24950. Primitives.Cylinder = Cylinder;
  24951. var Torus = (function (_super) {
  24952. __extends(Torus, _super);
  24953. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24954. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24955. this.diameter = diameter;
  24956. this.thickness = thickness;
  24957. this.tessellation = tessellation;
  24958. this.side = side;
  24959. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24960. }
  24961. Torus.prototype._regenerateVertexData = function () {
  24962. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24963. };
  24964. Torus.prototype.copy = function (id) {
  24965. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24966. };
  24967. return Torus;
  24968. })(_Primitive);
  24969. Primitives.Torus = Torus;
  24970. var Ground = (function (_super) {
  24971. __extends(Ground, _super);
  24972. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24973. this.width = width;
  24974. this.height = height;
  24975. this.subdivisions = subdivisions;
  24976. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24977. }
  24978. Ground.prototype._regenerateVertexData = function () {
  24979. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24980. };
  24981. Ground.prototype.copy = function (id) {
  24982. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24983. };
  24984. return Ground;
  24985. })(_Primitive);
  24986. Primitives.Ground = Ground;
  24987. var TiledGround = (function (_super) {
  24988. __extends(TiledGround, _super);
  24989. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24990. this.xmin = xmin;
  24991. this.zmin = zmin;
  24992. this.xmax = xmax;
  24993. this.zmax = zmax;
  24994. this.subdivisions = subdivisions;
  24995. this.precision = precision;
  24996. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24997. }
  24998. TiledGround.prototype._regenerateVertexData = function () {
  24999. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  25000. };
  25001. TiledGround.prototype.copy = function (id) {
  25002. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  25003. };
  25004. return TiledGround;
  25005. })(_Primitive);
  25006. Primitives.TiledGround = TiledGround;
  25007. var Plane = (function (_super) {
  25008. __extends(Plane, _super);
  25009. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  25010. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25011. this.size = size;
  25012. this.side = side;
  25013. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25014. }
  25015. Plane.prototype._regenerateVertexData = function () {
  25016. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  25017. };
  25018. Plane.prototype.copy = function (id) {
  25019. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  25020. };
  25021. return Plane;
  25022. })(_Primitive);
  25023. Primitives.Plane = Plane;
  25024. var TorusKnot = (function (_super) {
  25025. __extends(TorusKnot, _super);
  25026. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  25027. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  25028. this.radius = radius;
  25029. this.tube = tube;
  25030. this.radialSegments = radialSegments;
  25031. this.tubularSegments = tubularSegments;
  25032. this.p = p;
  25033. this.q = q;
  25034. this.side = side;
  25035. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  25036. }
  25037. TorusKnot.prototype._regenerateVertexData = function () {
  25038. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  25039. };
  25040. TorusKnot.prototype.copy = function (id) {
  25041. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  25042. };
  25043. return TorusKnot;
  25044. })(_Primitive);
  25045. Primitives.TorusKnot = TorusKnot;
  25046. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  25047. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  25048. })(BABYLON || (BABYLON = {}));
  25049. //# sourceMappingURL=babylon.geometry.js.map
  25050. var BABYLON;
  25051. (function (BABYLON) {
  25052. var Gamepads = (function () {
  25053. function Gamepads(ongamedpadconnected) {
  25054. var _this = this;
  25055. this.babylonGamepads = [];
  25056. this.oneGamepadConnected = false;
  25057. this.isMonitoring = false;
  25058. this.gamepadEventSupported = 'GamepadEvent' in window;
  25059. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  25060. 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=";
  25061. this._callbackGamepadConnected = ongamedpadconnected;
  25062. if (this.gamepadSupportAvailable) {
  25063. // Checking if the gamepad connected event is supported (like in Firefox)
  25064. if (this.gamepadEventSupported) {
  25065. window.addEventListener('gamepadconnected', function (evt) {
  25066. _this._onGamepadConnected(evt);
  25067. }, false);
  25068. window.addEventListener('gamepaddisconnected', function (evt) {
  25069. _this._onGamepadDisconnected(evt);
  25070. }, false);
  25071. }
  25072. else {
  25073. this._startMonitoringGamepads();
  25074. }
  25075. if (!this.oneGamepadConnected) {
  25076. this._insertGamepadDOMInstructions();
  25077. }
  25078. }
  25079. else {
  25080. this._insertGamepadDOMNotSupported();
  25081. }
  25082. }
  25083. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  25084. Gamepads.gamepadDOMInfo = document.createElement("div");
  25085. var buttonAImage = document.createElement("img");
  25086. buttonAImage.src = this.buttonADataURL;
  25087. var spanMessage = document.createElement("span");
  25088. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  25089. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  25090. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25091. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25092. Gamepads.gamepadDOMInfo.style.width = "100%";
  25093. Gamepads.gamepadDOMInfo.style.height = "48px";
  25094. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25095. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25096. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25097. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25098. buttonAImage.style.position = "relative";
  25099. buttonAImage.style.bottom = "8px";
  25100. spanMessage.style.position = "relative";
  25101. spanMessage.style.fontSize = "32px";
  25102. spanMessage.style.bottom = "32px";
  25103. spanMessage.style.color = "green";
  25104. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25105. };
  25106. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  25107. Gamepads.gamepadDOMInfo = document.createElement("div");
  25108. var spanMessage = document.createElement("span");
  25109. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  25110. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  25111. Gamepads.gamepadDOMInfo.style.position = "absolute";
  25112. Gamepads.gamepadDOMInfo.style.width = "100%";
  25113. Gamepads.gamepadDOMInfo.style.height = "40px";
  25114. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  25115. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  25116. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  25117. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  25118. spanMessage.style.position = "relative";
  25119. spanMessage.style.fontSize = "32px";
  25120. spanMessage.style.color = "red";
  25121. document.body.appendChild(Gamepads.gamepadDOMInfo);
  25122. };
  25123. Gamepads.prototype.dispose = function () {
  25124. if (Gamepads.gamepadDOMInfo) {
  25125. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25126. }
  25127. };
  25128. Gamepads.prototype._onGamepadConnected = function (evt) {
  25129. var newGamepad = this._addNewGamepad(evt.gamepad);
  25130. if (this._callbackGamepadConnected)
  25131. this._callbackGamepadConnected(newGamepad);
  25132. this._startMonitoringGamepads();
  25133. };
  25134. Gamepads.prototype._addNewGamepad = function (gamepad) {
  25135. if (!this.oneGamepadConnected) {
  25136. this.oneGamepadConnected = true;
  25137. if (Gamepads.gamepadDOMInfo) {
  25138. document.body.removeChild(Gamepads.gamepadDOMInfo);
  25139. Gamepads.gamepadDOMInfo = null;
  25140. }
  25141. }
  25142. var newGamepad;
  25143. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  25144. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  25145. }
  25146. else {
  25147. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  25148. }
  25149. this.babylonGamepads.push(newGamepad);
  25150. return newGamepad;
  25151. };
  25152. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  25153. for (var i in this.babylonGamepads) {
  25154. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  25155. this.babylonGamepads.splice(i, 1);
  25156. break;
  25157. }
  25158. }
  25159. // If no gamepads are left, stop the polling loop.
  25160. if (this.babylonGamepads.length == 0) {
  25161. this._stopMonitoringGamepads();
  25162. }
  25163. };
  25164. Gamepads.prototype._startMonitoringGamepads = function () {
  25165. if (!this.isMonitoring) {
  25166. this.isMonitoring = true;
  25167. this._checkGamepadsStatus();
  25168. }
  25169. };
  25170. Gamepads.prototype._stopMonitoringGamepads = function () {
  25171. this.isMonitoring = false;
  25172. };
  25173. Gamepads.prototype._checkGamepadsStatus = function () {
  25174. var _this = this;
  25175. // updating gamepad objects
  25176. this._updateGamepadObjects();
  25177. for (var i in this.babylonGamepads) {
  25178. this.babylonGamepads[i].update();
  25179. }
  25180. if (this.isMonitoring) {
  25181. if (window.requestAnimationFrame) {
  25182. window.requestAnimationFrame(function () {
  25183. _this._checkGamepadsStatus();
  25184. });
  25185. }
  25186. else if (window.mozRequestAnimationFrame) {
  25187. window.mozRequestAnimationFrame(function () {
  25188. _this._checkGamepadsStatus();
  25189. });
  25190. }
  25191. else if (window.webkitRequestAnimationFrame) {
  25192. window.webkitRequestAnimationFrame(function () {
  25193. _this._checkGamepadsStatus();
  25194. });
  25195. }
  25196. }
  25197. };
  25198. // This function is called only on Chrome, which does not yet support
  25199. // connection/disconnection events, but requires you to monitor
  25200. // an array for changes.
  25201. Gamepads.prototype._updateGamepadObjects = function () {
  25202. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  25203. for (var i = 0; i < gamepads.length; i++) {
  25204. if (gamepads[i]) {
  25205. if (!(gamepads[i].index in this.babylonGamepads)) {
  25206. var newGamepad = this._addNewGamepad(gamepads[i]);
  25207. if (this._callbackGamepadConnected) {
  25208. this._callbackGamepadConnected(newGamepad);
  25209. }
  25210. }
  25211. else {
  25212. this.babylonGamepads[i].browserGamepad = gamepads[i];
  25213. }
  25214. }
  25215. }
  25216. };
  25217. return Gamepads;
  25218. })();
  25219. BABYLON.Gamepads = Gamepads;
  25220. var StickValues = (function () {
  25221. function StickValues(x, y) {
  25222. this.x = x;
  25223. this.y = y;
  25224. }
  25225. return StickValues;
  25226. })();
  25227. BABYLON.StickValues = StickValues;
  25228. var Gamepad = (function () {
  25229. function Gamepad(id, index, browserGamepad) {
  25230. this.id = id;
  25231. this.index = index;
  25232. this.browserGamepad = browserGamepad;
  25233. if (this.browserGamepad.axes.length >= 2) {
  25234. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25235. }
  25236. if (this.browserGamepad.axes.length >= 4) {
  25237. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25238. }
  25239. }
  25240. Gamepad.prototype.onleftstickchanged = function (callback) {
  25241. this._onleftstickchanged = callback;
  25242. };
  25243. Gamepad.prototype.onrightstickchanged = function (callback) {
  25244. this._onrightstickchanged = callback;
  25245. };
  25246. Object.defineProperty(Gamepad.prototype, "leftStick", {
  25247. get: function () {
  25248. return this._leftStick;
  25249. },
  25250. set: function (newValues) {
  25251. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  25252. this._onleftstickchanged(newValues);
  25253. }
  25254. this._leftStick = newValues;
  25255. },
  25256. enumerable: true,
  25257. configurable: true
  25258. });
  25259. Object.defineProperty(Gamepad.prototype, "rightStick", {
  25260. get: function () {
  25261. return this._rightStick;
  25262. },
  25263. set: function (newValues) {
  25264. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  25265. this._onrightstickchanged(newValues);
  25266. }
  25267. this._rightStick = newValues;
  25268. },
  25269. enumerable: true,
  25270. configurable: true
  25271. });
  25272. Gamepad.prototype.update = function () {
  25273. if (this._leftStick) {
  25274. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25275. }
  25276. if (this._rightStick) {
  25277. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25278. }
  25279. };
  25280. return Gamepad;
  25281. })();
  25282. BABYLON.Gamepad = Gamepad;
  25283. var GenericPad = (function (_super) {
  25284. __extends(GenericPad, _super);
  25285. function GenericPad(id, index, gamepad) {
  25286. _super.call(this, id, index, gamepad);
  25287. this.id = id;
  25288. this.index = index;
  25289. this.gamepad = gamepad;
  25290. this._buttons = new Array(gamepad.buttons.length);
  25291. }
  25292. GenericPad.prototype.onbuttondown = function (callback) {
  25293. this._onbuttondown = callback;
  25294. };
  25295. GenericPad.prototype.onbuttonup = function (callback) {
  25296. this._onbuttonup = callback;
  25297. };
  25298. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25299. if (newValue !== currentValue) {
  25300. if (this._onbuttondown && newValue === 1) {
  25301. this._onbuttondown(buttonIndex);
  25302. }
  25303. if (this._onbuttonup && newValue === 0) {
  25304. this._onbuttonup(buttonIndex);
  25305. }
  25306. }
  25307. return newValue;
  25308. };
  25309. GenericPad.prototype.update = function () {
  25310. _super.prototype.update.call(this);
  25311. for (var index = 0; index < this._buttons.length; index++) {
  25312. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25313. }
  25314. };
  25315. return GenericPad;
  25316. })(Gamepad);
  25317. BABYLON.GenericPad = GenericPad;
  25318. (function (Xbox360Button) {
  25319. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25320. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25321. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25322. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25323. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25324. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25325. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25326. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25327. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25328. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25329. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25330. var Xbox360Button = BABYLON.Xbox360Button;
  25331. (function (Xbox360Dpad) {
  25332. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25333. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25334. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25335. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25336. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25337. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25338. var Xbox360Pad = (function (_super) {
  25339. __extends(Xbox360Pad, _super);
  25340. function Xbox360Pad() {
  25341. _super.apply(this, arguments);
  25342. this._leftTrigger = 0;
  25343. this._rightTrigger = 0;
  25344. this._buttonA = 0;
  25345. this._buttonB = 0;
  25346. this._buttonX = 0;
  25347. this._buttonY = 0;
  25348. this._buttonBack = 0;
  25349. this._buttonStart = 0;
  25350. this._buttonLB = 0;
  25351. this._buttonRB = 0;
  25352. this._buttonLeftStick = 0;
  25353. this._buttonRightStick = 0;
  25354. this._dPadUp = 0;
  25355. this._dPadDown = 0;
  25356. this._dPadLeft = 0;
  25357. this._dPadRight = 0;
  25358. }
  25359. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25360. this._onlefttriggerchanged = callback;
  25361. };
  25362. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25363. this._onrighttriggerchanged = callback;
  25364. };
  25365. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25366. get: function () {
  25367. return this._leftTrigger;
  25368. },
  25369. set: function (newValue) {
  25370. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25371. this._onlefttriggerchanged(newValue);
  25372. }
  25373. this._leftTrigger = newValue;
  25374. },
  25375. enumerable: true,
  25376. configurable: true
  25377. });
  25378. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25379. get: function () {
  25380. return this._rightTrigger;
  25381. },
  25382. set: function (newValue) {
  25383. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25384. this._onrighttriggerchanged(newValue);
  25385. }
  25386. this._rightTrigger = newValue;
  25387. },
  25388. enumerable: true,
  25389. configurable: true
  25390. });
  25391. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25392. this._onbuttondown = callback;
  25393. };
  25394. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25395. this._onbuttonup = callback;
  25396. };
  25397. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25398. this._ondpaddown = callback;
  25399. };
  25400. Xbox360Pad.prototype.ondpadup = function (callback) {
  25401. this._ondpadup = callback;
  25402. };
  25403. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25404. if (newValue !== currentValue) {
  25405. if (this._onbuttondown && newValue === 1) {
  25406. this._onbuttondown(buttonType);
  25407. }
  25408. if (this._onbuttonup && newValue === 0) {
  25409. this._onbuttonup(buttonType);
  25410. }
  25411. }
  25412. return newValue;
  25413. };
  25414. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25415. if (newValue !== currentValue) {
  25416. if (this._ondpaddown && newValue === 1) {
  25417. this._ondpaddown(buttonType);
  25418. }
  25419. if (this._ondpadup && newValue === 0) {
  25420. this._ondpadup(buttonType);
  25421. }
  25422. }
  25423. return newValue;
  25424. };
  25425. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25426. get: function () {
  25427. return this._buttonA;
  25428. },
  25429. set: function (value) {
  25430. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25431. },
  25432. enumerable: true,
  25433. configurable: true
  25434. });
  25435. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25436. get: function () {
  25437. return this._buttonB;
  25438. },
  25439. set: function (value) {
  25440. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25441. },
  25442. enumerable: true,
  25443. configurable: true
  25444. });
  25445. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25446. get: function () {
  25447. return this._buttonX;
  25448. },
  25449. set: function (value) {
  25450. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25451. },
  25452. enumerable: true,
  25453. configurable: true
  25454. });
  25455. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25456. get: function () {
  25457. return this._buttonY;
  25458. },
  25459. set: function (value) {
  25460. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25461. },
  25462. enumerable: true,
  25463. configurable: true
  25464. });
  25465. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25466. get: function () {
  25467. return this._buttonStart;
  25468. },
  25469. set: function (value) {
  25470. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25471. },
  25472. enumerable: true,
  25473. configurable: true
  25474. });
  25475. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25476. get: function () {
  25477. return this._buttonBack;
  25478. },
  25479. set: function (value) {
  25480. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25481. },
  25482. enumerable: true,
  25483. configurable: true
  25484. });
  25485. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25486. get: function () {
  25487. return this._buttonLB;
  25488. },
  25489. set: function (value) {
  25490. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25491. },
  25492. enumerable: true,
  25493. configurable: true
  25494. });
  25495. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25496. get: function () {
  25497. return this._buttonRB;
  25498. },
  25499. set: function (value) {
  25500. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25501. },
  25502. enumerable: true,
  25503. configurable: true
  25504. });
  25505. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25506. get: function () {
  25507. return this._buttonLeftStick;
  25508. },
  25509. set: function (value) {
  25510. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25511. },
  25512. enumerable: true,
  25513. configurable: true
  25514. });
  25515. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25516. get: function () {
  25517. return this._buttonRightStick;
  25518. },
  25519. set: function (value) {
  25520. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25521. },
  25522. enumerable: true,
  25523. configurable: true
  25524. });
  25525. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25526. get: function () {
  25527. return this._dPadUp;
  25528. },
  25529. set: function (value) {
  25530. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25531. },
  25532. enumerable: true,
  25533. configurable: true
  25534. });
  25535. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25536. get: function () {
  25537. return this._dPadDown;
  25538. },
  25539. set: function (value) {
  25540. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25541. },
  25542. enumerable: true,
  25543. configurable: true
  25544. });
  25545. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25546. get: function () {
  25547. return this._dPadLeft;
  25548. },
  25549. set: function (value) {
  25550. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25551. },
  25552. enumerable: true,
  25553. configurable: true
  25554. });
  25555. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25556. get: function () {
  25557. return this._dPadRight;
  25558. },
  25559. set: function (value) {
  25560. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25561. },
  25562. enumerable: true,
  25563. configurable: true
  25564. });
  25565. Xbox360Pad.prototype.update = function () {
  25566. _super.prototype.update.call(this);
  25567. this.buttonA = this.browserGamepad.buttons[0].value;
  25568. this.buttonB = this.browserGamepad.buttons[1].value;
  25569. this.buttonX = this.browserGamepad.buttons[2].value;
  25570. this.buttonY = this.browserGamepad.buttons[3].value;
  25571. this.buttonLB = this.browserGamepad.buttons[4].value;
  25572. this.buttonRB = this.browserGamepad.buttons[5].value;
  25573. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25574. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25575. this.buttonBack = this.browserGamepad.buttons[8].value;
  25576. this.buttonStart = this.browserGamepad.buttons[9].value;
  25577. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25578. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25579. this.dPadUp = this.browserGamepad.buttons[12].value;
  25580. this.dPadDown = this.browserGamepad.buttons[13].value;
  25581. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25582. this.dPadRight = this.browserGamepad.buttons[15].value;
  25583. };
  25584. return Xbox360Pad;
  25585. })(Gamepad);
  25586. BABYLON.Xbox360Pad = Xbox360Pad;
  25587. })(BABYLON || (BABYLON = {}));
  25588. //# sourceMappingURL=babylon.gamepads.js.map
  25589. var BABYLON;
  25590. (function (BABYLON) {
  25591. // We're mainly based on the logic defined into the FreeCamera code
  25592. var GamepadCamera = (function (_super) {
  25593. __extends(GamepadCamera, _super);
  25594. function GamepadCamera(name, position, scene) {
  25595. var _this = this;
  25596. _super.call(this, name, position, scene);
  25597. this.angularSensibility = 200;
  25598. this.moveSensibility = 75;
  25599. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25600. _this._onNewGameConnected(gamepad);
  25601. });
  25602. }
  25603. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25604. // Only the first gamepad can control the camera
  25605. if (gamepad.index === 0) {
  25606. this._gamepad = gamepad;
  25607. }
  25608. };
  25609. GamepadCamera.prototype._checkInputs = function () {
  25610. if (!this._gamepad) {
  25611. return;
  25612. }
  25613. var LSValues = this._gamepad.leftStick;
  25614. var normalizedLX = LSValues.x / this.moveSensibility;
  25615. var normalizedLY = LSValues.y / this.moveSensibility;
  25616. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25617. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25618. var RSValues = this._gamepad.rightStick;
  25619. var normalizedRX = RSValues.x / this.angularSensibility;
  25620. var normalizedRY = RSValues.y / this.angularSensibility;
  25621. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25622. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25623. ;
  25624. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25625. var speed = this._computeLocalCameraSpeed() * 50.0;
  25626. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25627. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25628. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25629. };
  25630. GamepadCamera.prototype.dispose = function () {
  25631. this._gamepads.dispose();
  25632. _super.prototype.dispose.call(this);
  25633. };
  25634. return GamepadCamera;
  25635. })(BABYLON.FreeCamera);
  25636. BABYLON.GamepadCamera = GamepadCamera;
  25637. })(BABYLON || (BABYLON = {}));
  25638. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25639. var BABYLON;
  25640. (function (BABYLON) {
  25641. var LinesMesh = (function (_super) {
  25642. __extends(LinesMesh, _super);
  25643. function LinesMesh(name, scene, updatable) {
  25644. if (updatable === void 0) { updatable = false; }
  25645. _super.call(this, name, scene);
  25646. this.color = new BABYLON.Color3(1, 1, 1);
  25647. this.alpha = 1;
  25648. this._indices = new Array();
  25649. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25650. attributes: ["position"],
  25651. uniforms: ["worldViewProjection", "color"],
  25652. needAlphaBlending: true
  25653. });
  25654. }
  25655. Object.defineProperty(LinesMesh.prototype, "material", {
  25656. get: function () {
  25657. return this._colorShader;
  25658. },
  25659. enumerable: true,
  25660. configurable: true
  25661. });
  25662. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25663. get: function () {
  25664. return false;
  25665. },
  25666. enumerable: true,
  25667. configurable: true
  25668. });
  25669. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25670. get: function () {
  25671. return false;
  25672. },
  25673. enumerable: true,
  25674. configurable: true
  25675. });
  25676. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25677. var engine = this.getScene().getEngine();
  25678. var indexToBind = this._geometry.getIndexBuffer();
  25679. // VBOs
  25680. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25681. // Color
  25682. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25683. };
  25684. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25685. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25686. return;
  25687. }
  25688. var engine = this.getScene().getEngine();
  25689. // Draw order
  25690. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25691. };
  25692. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25693. return null;
  25694. };
  25695. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25696. this._colorShader.dispose();
  25697. _super.prototype.dispose.call(this, doNotRecurse);
  25698. };
  25699. return LinesMesh;
  25700. })(BABYLON.Mesh);
  25701. BABYLON.LinesMesh = LinesMesh;
  25702. })(BABYLON || (BABYLON = {}));
  25703. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25704. (function (BABYLON) {
  25705. var OutlineRenderer = (function () {
  25706. function OutlineRenderer(scene) {
  25707. this._scene = scene;
  25708. }
  25709. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25710. var _this = this;
  25711. if (useOverlay === void 0) { useOverlay = false; }
  25712. var scene = this._scene;
  25713. var engine = this._scene.getEngine();
  25714. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25715. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25716. return;
  25717. }
  25718. var mesh = subMesh.getRenderingMesh();
  25719. var material = subMesh.getMaterial();
  25720. engine.enableEffect(this._effect);
  25721. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25722. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25723. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25724. // Bones
  25725. if (mesh.useBones) {
  25726. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25727. }
  25728. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25729. // Alpha test
  25730. if (material && material.needAlphaTesting()) {
  25731. var alphaTexture = material.getAlphaTestTexture();
  25732. this._effect.setTexture("diffuseSampler", alphaTexture);
  25733. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25734. }
  25735. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25736. _this._effect.setMatrix("world", world);
  25737. });
  25738. };
  25739. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25740. var defines = [];
  25741. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25742. var mesh = subMesh.getMesh();
  25743. var material = subMesh.getMaterial();
  25744. // Alpha test
  25745. if (material && material.needAlphaTesting()) {
  25746. defines.push("#define ALPHATEST");
  25747. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25748. attribs.push(BABYLON.VertexBuffer.UVKind);
  25749. defines.push("#define UV1");
  25750. }
  25751. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25752. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25753. defines.push("#define UV2");
  25754. }
  25755. }
  25756. // Bones
  25757. if (mesh.useBones) {
  25758. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25759. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25760. defines.push("#define BONES");
  25761. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25762. }
  25763. // Instances
  25764. if (useInstances) {
  25765. defines.push("#define INSTANCES");
  25766. attribs.push("world0");
  25767. attribs.push("world1");
  25768. attribs.push("world2");
  25769. attribs.push("world3");
  25770. }
  25771. // Get correct effect
  25772. var join = defines.join("\n");
  25773. if (this._cachedDefines !== join) {
  25774. this._cachedDefines = join;
  25775. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25776. }
  25777. return this._effect.isReady();
  25778. };
  25779. return OutlineRenderer;
  25780. })();
  25781. BABYLON.OutlineRenderer = OutlineRenderer;
  25782. })(BABYLON || (BABYLON = {}));
  25783. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25784. (function (BABYLON) {
  25785. var MeshAssetTask = (function () {
  25786. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25787. this.name = name;
  25788. this.meshesNames = meshesNames;
  25789. this.rootUrl = rootUrl;
  25790. this.sceneFilename = sceneFilename;
  25791. this.isCompleted = false;
  25792. }
  25793. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25794. var _this = this;
  25795. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25796. _this.loadedMeshes = meshes;
  25797. _this.loadedParticleSystems = particleSystems;
  25798. _this.loadedSkeletons = skeletons;
  25799. _this.isCompleted = true;
  25800. if (_this.onSuccess) {
  25801. _this.onSuccess(_this);
  25802. }
  25803. onSuccess();
  25804. }, null, function () {
  25805. if (_this.onError) {
  25806. _this.onError(_this);
  25807. }
  25808. onError();
  25809. });
  25810. };
  25811. return MeshAssetTask;
  25812. })();
  25813. BABYLON.MeshAssetTask = MeshAssetTask;
  25814. var TextFileAssetTask = (function () {
  25815. function TextFileAssetTask(name, url) {
  25816. this.name = name;
  25817. this.url = url;
  25818. this.isCompleted = false;
  25819. }
  25820. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25821. var _this = this;
  25822. BABYLON.Tools.LoadFile(this.url, function (data) {
  25823. _this.text = data;
  25824. _this.isCompleted = true;
  25825. if (_this.onSuccess) {
  25826. _this.onSuccess(_this);
  25827. }
  25828. onSuccess();
  25829. }, null, scene.database, false, function () {
  25830. if (_this.onError) {
  25831. _this.onError(_this);
  25832. }
  25833. onError();
  25834. });
  25835. };
  25836. return TextFileAssetTask;
  25837. })();
  25838. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25839. var BinaryFileAssetTask = (function () {
  25840. function BinaryFileAssetTask(name, url) {
  25841. this.name = name;
  25842. this.url = url;
  25843. this.isCompleted = false;
  25844. }
  25845. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25846. var _this = this;
  25847. BABYLON.Tools.LoadFile(this.url, function (data) {
  25848. _this.data = data;
  25849. _this.isCompleted = true;
  25850. if (_this.onSuccess) {
  25851. _this.onSuccess(_this);
  25852. }
  25853. onSuccess();
  25854. }, null, scene.database, true, function () {
  25855. if (_this.onError) {
  25856. _this.onError(_this);
  25857. }
  25858. onError();
  25859. });
  25860. };
  25861. return BinaryFileAssetTask;
  25862. })();
  25863. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25864. var ImageAssetTask = (function () {
  25865. function ImageAssetTask(name, url) {
  25866. this.name = name;
  25867. this.url = url;
  25868. this.isCompleted = false;
  25869. }
  25870. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25871. var _this = this;
  25872. var img = new Image();
  25873. img.onload = function () {
  25874. _this.image = img;
  25875. _this.isCompleted = true;
  25876. if (_this.onSuccess) {
  25877. _this.onSuccess(_this);
  25878. }
  25879. onSuccess();
  25880. };
  25881. img.onerror = function () {
  25882. if (_this.onError) {
  25883. _this.onError(_this);
  25884. }
  25885. onError();
  25886. };
  25887. img.src = this.url;
  25888. };
  25889. return ImageAssetTask;
  25890. })();
  25891. BABYLON.ImageAssetTask = ImageAssetTask;
  25892. var TextureAssetTask = (function () {
  25893. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25894. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25895. this.name = name;
  25896. this.url = url;
  25897. this.noMipmap = noMipmap;
  25898. this.invertY = invertY;
  25899. this.samplingMode = samplingMode;
  25900. this.isCompleted = false;
  25901. }
  25902. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25903. var _this = this;
  25904. var onload = function () {
  25905. _this.isCompleted = true;
  25906. if (_this.onSuccess) {
  25907. _this.onSuccess(_this);
  25908. }
  25909. onSuccess();
  25910. };
  25911. var onerror = function () {
  25912. if (_this.onError) {
  25913. _this.onError(_this);
  25914. }
  25915. onError();
  25916. };
  25917. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25918. };
  25919. return TextureAssetTask;
  25920. })();
  25921. BABYLON.TextureAssetTask = TextureAssetTask;
  25922. var AssetsManager = (function () {
  25923. function AssetsManager(scene) {
  25924. this._tasks = new Array();
  25925. this._waitingTasksCount = 0;
  25926. this.useDefaultLoadingScreen = true;
  25927. this._scene = scene;
  25928. }
  25929. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25930. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25931. this._tasks.push(task);
  25932. return task;
  25933. };
  25934. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25935. var task = new TextFileAssetTask(taskName, url);
  25936. this._tasks.push(task);
  25937. return task;
  25938. };
  25939. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25940. var task = new BinaryFileAssetTask(taskName, url);
  25941. this._tasks.push(task);
  25942. return task;
  25943. };
  25944. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25945. var task = new ImageAssetTask(taskName, url);
  25946. this._tasks.push(task);
  25947. return task;
  25948. };
  25949. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25950. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25951. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25952. this._tasks.push(task);
  25953. return task;
  25954. };
  25955. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25956. this._waitingTasksCount--;
  25957. if (this._waitingTasksCount === 0) {
  25958. if (this.onFinish) {
  25959. this.onFinish(this._tasks);
  25960. }
  25961. this._scene.getEngine().hideLoadingUI();
  25962. }
  25963. };
  25964. AssetsManager.prototype._runTask = function (task) {
  25965. var _this = this;
  25966. task.run(this._scene, function () {
  25967. if (_this.onTaskSuccess) {
  25968. _this.onTaskSuccess(task);
  25969. }
  25970. _this._decreaseWaitingTasksCount();
  25971. }, function () {
  25972. if (_this.onTaskError) {
  25973. _this.onTaskError(task);
  25974. }
  25975. _this._decreaseWaitingTasksCount();
  25976. });
  25977. };
  25978. AssetsManager.prototype.reset = function () {
  25979. this._tasks = new Array();
  25980. return this;
  25981. };
  25982. AssetsManager.prototype.load = function () {
  25983. this._waitingTasksCount = this._tasks.length;
  25984. if (this._waitingTasksCount === 0) {
  25985. if (this.onFinish) {
  25986. this.onFinish(this._tasks);
  25987. }
  25988. return this;
  25989. }
  25990. if (this.useDefaultLoadingScreen) {
  25991. this._scene.getEngine().displayLoadingUI();
  25992. }
  25993. for (var index = 0; index < this._tasks.length; index++) {
  25994. var task = this._tasks[index];
  25995. this._runTask(task);
  25996. }
  25997. return this;
  25998. };
  25999. return AssetsManager;
  26000. })();
  26001. BABYLON.AssetsManager = AssetsManager;
  26002. })(BABYLON || (BABYLON = {}));
  26003. //# sourceMappingURL=babylon.assetsManager.js.map
  26004. var BABYLON;
  26005. (function (BABYLON) {
  26006. var VRDeviceOrientationCamera = (function (_super) {
  26007. __extends(VRDeviceOrientationCamera, _super);
  26008. function VRDeviceOrientationCamera(name, position, scene) {
  26009. _super.call(this, name, position, scene);
  26010. this._alpha = 0;
  26011. this._beta = 0;
  26012. this._gamma = 0;
  26013. }
  26014. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  26015. this._alpha = +evt.alpha | 0;
  26016. this._beta = +evt.beta | 0;
  26017. this._gamma = +evt.gamma | 0;
  26018. if (this._gamma < 0) {
  26019. this._gamma = 90 + this._gamma;
  26020. }
  26021. else {
  26022. // Incline it in the correct angle.
  26023. this._gamma = 270 - this._gamma;
  26024. }
  26025. this.rotation.x = this._gamma / 180.0 * Math.PI;
  26026. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  26027. this.rotation.z = this._beta / 180.0 * Math.PI;
  26028. };
  26029. return VRDeviceOrientationCamera;
  26030. })(BABYLON.OculusCamera);
  26031. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  26032. })(BABYLON || (BABYLON = {}));
  26033. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  26034. var BABYLON;
  26035. (function (BABYLON) {
  26036. var WebVRCamera = (function (_super) {
  26037. __extends(WebVRCamera, _super);
  26038. function WebVRCamera(name, position, scene) {
  26039. _super.call(this, name, position, scene);
  26040. this._hmdDevice = null;
  26041. this._sensorDevice = null;
  26042. this._cacheState = null;
  26043. this._cacheQuaternion = new BABYLON.Quaternion();
  26044. this._cacheRotation = BABYLON.Vector3.Zero();
  26045. this._vrEnabled = false;
  26046. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  26047. }
  26048. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  26049. var size = devices.length;
  26050. var i = 0;
  26051. // Reset devices.
  26052. this._sensorDevice = null;
  26053. this._hmdDevice = null;
  26054. while (i < size && this._hmdDevice === null) {
  26055. if (devices[i] instanceof HMDVRDevice) {
  26056. this._hmdDevice = devices[i];
  26057. }
  26058. i++;
  26059. }
  26060. i = 0;
  26061. while (i < size && this._sensorDevice === null) {
  26062. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  26063. this._sensorDevice = devices[i];
  26064. }
  26065. i++;
  26066. }
  26067. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  26068. };
  26069. WebVRCamera.prototype._update = function () {
  26070. if (this._vrEnabled) {
  26071. this._cacheState = this._sensorDevice.getState();
  26072. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  26073. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  26074. this.rotation.x = -this._cacheRotation.z;
  26075. this.rotation.y = -this._cacheRotation.y;
  26076. this.rotation.z = this._cacheRotation.x;
  26077. }
  26078. _super.prototype._update.call(this);
  26079. };
  26080. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  26081. _super.prototype.attachControl.call(this, element, noPreventDefault);
  26082. if (navigator.getVRDevices) {
  26083. navigator.getVRDevices().then(this._getWebVRDevices);
  26084. }
  26085. else if (navigator.mozGetVRDevices) {
  26086. navigator.mozGetVRDevices(this._getWebVRDevices);
  26087. }
  26088. };
  26089. WebVRCamera.prototype.detachControl = function (element) {
  26090. _super.prototype.detachControl.call(this, element);
  26091. this._vrEnabled = false;
  26092. };
  26093. return WebVRCamera;
  26094. })(BABYLON.OculusCamera);
  26095. BABYLON.WebVRCamera = WebVRCamera;
  26096. })(BABYLON || (BABYLON = {}));
  26097. //# sourceMappingURL=babylon.webVRCamera.js.map
  26098. var BABYLON;
  26099. (function (BABYLON) {
  26100. // Standard optimizations
  26101. var SceneOptimization = (function () {
  26102. function SceneOptimization(priority) {
  26103. if (priority === void 0) { priority = 0; }
  26104. this.priority = priority;
  26105. this.apply = function (scene) {
  26106. return true; // Return true if everything that can be done was applied
  26107. };
  26108. }
  26109. return SceneOptimization;
  26110. })();
  26111. BABYLON.SceneOptimization = SceneOptimization;
  26112. var TextureOptimization = (function (_super) {
  26113. __extends(TextureOptimization, _super);
  26114. function TextureOptimization(priority, maximumSize) {
  26115. var _this = this;
  26116. if (priority === void 0) { priority = 0; }
  26117. if (maximumSize === void 0) { maximumSize = 1024; }
  26118. _super.call(this, priority);
  26119. this.priority = priority;
  26120. this.maximumSize = maximumSize;
  26121. this.apply = function (scene) {
  26122. var allDone = true;
  26123. for (var index = 0; index < scene.textures.length; index++) {
  26124. var texture = scene.textures[index];
  26125. if (!texture.canRescale) {
  26126. continue;
  26127. }
  26128. var currentSize = texture.getSize();
  26129. var maxDimension = Math.max(currentSize.width, currentSize.height);
  26130. if (maxDimension > _this.maximumSize) {
  26131. texture.scale(0.5);
  26132. allDone = false;
  26133. }
  26134. }
  26135. return allDone;
  26136. };
  26137. }
  26138. return TextureOptimization;
  26139. })(SceneOptimization);
  26140. BABYLON.TextureOptimization = TextureOptimization;
  26141. var HardwareScalingOptimization = (function (_super) {
  26142. __extends(HardwareScalingOptimization, _super);
  26143. function HardwareScalingOptimization(priority, maximumScale) {
  26144. var _this = this;
  26145. if (priority === void 0) { priority = 0; }
  26146. if (maximumScale === void 0) { maximumScale = 2; }
  26147. _super.call(this, priority);
  26148. this.priority = priority;
  26149. this.maximumScale = maximumScale;
  26150. this._currentScale = 1;
  26151. this.apply = function (scene) {
  26152. _this._currentScale++;
  26153. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  26154. return _this._currentScale >= _this.maximumScale;
  26155. };
  26156. }
  26157. return HardwareScalingOptimization;
  26158. })(SceneOptimization);
  26159. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  26160. var ShadowsOptimization = (function (_super) {
  26161. __extends(ShadowsOptimization, _super);
  26162. function ShadowsOptimization() {
  26163. _super.apply(this, arguments);
  26164. this.apply = function (scene) {
  26165. scene.shadowsEnabled = false;
  26166. return true;
  26167. };
  26168. }
  26169. return ShadowsOptimization;
  26170. })(SceneOptimization);
  26171. BABYLON.ShadowsOptimization = ShadowsOptimization;
  26172. var PostProcessesOptimization = (function (_super) {
  26173. __extends(PostProcessesOptimization, _super);
  26174. function PostProcessesOptimization() {
  26175. _super.apply(this, arguments);
  26176. this.apply = function (scene) {
  26177. scene.postProcessesEnabled = false;
  26178. return true;
  26179. };
  26180. }
  26181. return PostProcessesOptimization;
  26182. })(SceneOptimization);
  26183. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  26184. var LensFlaresOptimization = (function (_super) {
  26185. __extends(LensFlaresOptimization, _super);
  26186. function LensFlaresOptimization() {
  26187. _super.apply(this, arguments);
  26188. this.apply = function (scene) {
  26189. scene.lensFlaresEnabled = false;
  26190. return true;
  26191. };
  26192. }
  26193. return LensFlaresOptimization;
  26194. })(SceneOptimization);
  26195. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  26196. var ParticlesOptimization = (function (_super) {
  26197. __extends(ParticlesOptimization, _super);
  26198. function ParticlesOptimization() {
  26199. _super.apply(this, arguments);
  26200. this.apply = function (scene) {
  26201. scene.particlesEnabled = false;
  26202. return true;
  26203. };
  26204. }
  26205. return ParticlesOptimization;
  26206. })(SceneOptimization);
  26207. BABYLON.ParticlesOptimization = ParticlesOptimization;
  26208. var RenderTargetsOptimization = (function (_super) {
  26209. __extends(RenderTargetsOptimization, _super);
  26210. function RenderTargetsOptimization() {
  26211. _super.apply(this, arguments);
  26212. this.apply = function (scene) {
  26213. scene.renderTargetsEnabled = false;
  26214. return true;
  26215. };
  26216. }
  26217. return RenderTargetsOptimization;
  26218. })(SceneOptimization);
  26219. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  26220. var MergeMeshesOptimization = (function (_super) {
  26221. __extends(MergeMeshesOptimization, _super);
  26222. function MergeMeshesOptimization() {
  26223. var _this = this;
  26224. _super.apply(this, arguments);
  26225. this._canBeMerged = function (abstractMesh) {
  26226. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  26227. return false;
  26228. }
  26229. var mesh = abstractMesh;
  26230. if (!mesh.isVisible || !mesh.isEnabled()) {
  26231. return false;
  26232. }
  26233. if (mesh.instances.length > 0) {
  26234. return false;
  26235. }
  26236. if (mesh.skeleton || mesh.hasLODLevels) {
  26237. return false;
  26238. }
  26239. return true;
  26240. };
  26241. this.apply = function (scene) {
  26242. var globalPool = scene.meshes.slice(0);
  26243. var globalLength = globalPool.length;
  26244. for (var index = 0; index < globalLength; index++) {
  26245. var currentPool = new Array();
  26246. var current = globalPool[index];
  26247. // Checks
  26248. if (!_this._canBeMerged(current)) {
  26249. continue;
  26250. }
  26251. currentPool.push(current);
  26252. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  26253. var otherMesh = globalPool[subIndex];
  26254. if (!_this._canBeMerged(otherMesh)) {
  26255. continue;
  26256. }
  26257. if (otherMesh.material !== current.material) {
  26258. continue;
  26259. }
  26260. if (otherMesh.checkCollisions !== current.checkCollisions) {
  26261. continue;
  26262. }
  26263. currentPool.push(otherMesh);
  26264. globalLength--;
  26265. globalPool.splice(subIndex, 1);
  26266. subIndex--;
  26267. }
  26268. if (currentPool.length < 2) {
  26269. continue;
  26270. }
  26271. // Merge meshes
  26272. BABYLON.Mesh.MergeMeshes(currentPool);
  26273. }
  26274. return true;
  26275. };
  26276. }
  26277. return MergeMeshesOptimization;
  26278. })(SceneOptimization);
  26279. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26280. // Options
  26281. var SceneOptimizerOptions = (function () {
  26282. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26283. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26284. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26285. this.targetFrameRate = targetFrameRate;
  26286. this.trackerDuration = trackerDuration;
  26287. this.optimizations = new Array();
  26288. }
  26289. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26290. var result = new SceneOptimizerOptions(targetFrameRate);
  26291. var priority = 0;
  26292. result.optimizations.push(new MergeMeshesOptimization(priority));
  26293. result.optimizations.push(new ShadowsOptimization(priority));
  26294. result.optimizations.push(new LensFlaresOptimization(priority));
  26295. // Next priority
  26296. priority++;
  26297. result.optimizations.push(new PostProcessesOptimization(priority));
  26298. result.optimizations.push(new ParticlesOptimization(priority));
  26299. // Next priority
  26300. priority++;
  26301. result.optimizations.push(new TextureOptimization(priority, 1024));
  26302. return result;
  26303. };
  26304. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26305. var result = new SceneOptimizerOptions(targetFrameRate);
  26306. var priority = 0;
  26307. result.optimizations.push(new MergeMeshesOptimization(priority));
  26308. result.optimizations.push(new ShadowsOptimization(priority));
  26309. result.optimizations.push(new LensFlaresOptimization(priority));
  26310. // Next priority
  26311. priority++;
  26312. result.optimizations.push(new PostProcessesOptimization(priority));
  26313. result.optimizations.push(new ParticlesOptimization(priority));
  26314. // Next priority
  26315. priority++;
  26316. result.optimizations.push(new TextureOptimization(priority, 512));
  26317. // Next priority
  26318. priority++;
  26319. result.optimizations.push(new RenderTargetsOptimization(priority));
  26320. // Next priority
  26321. priority++;
  26322. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26323. return result;
  26324. };
  26325. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26326. var result = new SceneOptimizerOptions(targetFrameRate);
  26327. var priority = 0;
  26328. result.optimizations.push(new MergeMeshesOptimization(priority));
  26329. result.optimizations.push(new ShadowsOptimization(priority));
  26330. result.optimizations.push(new LensFlaresOptimization(priority));
  26331. // Next priority
  26332. priority++;
  26333. result.optimizations.push(new PostProcessesOptimization(priority));
  26334. result.optimizations.push(new ParticlesOptimization(priority));
  26335. // Next priority
  26336. priority++;
  26337. result.optimizations.push(new TextureOptimization(priority, 256));
  26338. // Next priority
  26339. priority++;
  26340. result.optimizations.push(new RenderTargetsOptimization(priority));
  26341. // Next priority
  26342. priority++;
  26343. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26344. return result;
  26345. };
  26346. return SceneOptimizerOptions;
  26347. })();
  26348. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26349. // Scene optimizer tool
  26350. var SceneOptimizer = (function () {
  26351. function SceneOptimizer() {
  26352. }
  26353. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26354. // TODO: add an epsilon
  26355. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26356. if (onSuccess) {
  26357. onSuccess();
  26358. }
  26359. return;
  26360. }
  26361. // Apply current level of optimizations
  26362. var allDone = true;
  26363. var noOptimizationApplied = true;
  26364. for (var index = 0; index < options.optimizations.length; index++) {
  26365. var optimization = options.optimizations[index];
  26366. if (optimization.priority === currentPriorityLevel) {
  26367. noOptimizationApplied = false;
  26368. allDone = allDone && optimization.apply(scene);
  26369. }
  26370. }
  26371. // If no optimization was applied, this is a failure :(
  26372. if (noOptimizationApplied) {
  26373. if (onFailure) {
  26374. onFailure();
  26375. }
  26376. return;
  26377. }
  26378. // If all optimizations were done, move to next level
  26379. if (allDone) {
  26380. currentPriorityLevel++;
  26381. }
  26382. // Let's the system running for a specific amount of time before checking FPS
  26383. scene.executeWhenReady(function () {
  26384. setTimeout(function () {
  26385. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26386. }, options.trackerDuration);
  26387. });
  26388. };
  26389. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26390. if (!options) {
  26391. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26392. }
  26393. // Let's the system running for a specific amount of time before checking FPS
  26394. scene.executeWhenReady(function () {
  26395. setTimeout(function () {
  26396. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26397. }, options.trackerDuration);
  26398. });
  26399. };
  26400. return SceneOptimizer;
  26401. })();
  26402. BABYLON.SceneOptimizer = SceneOptimizer;
  26403. })(BABYLON || (BABYLON = {}));
  26404. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26405. (function (BABYLON) {
  26406. var Internals;
  26407. (function (Internals) {
  26408. var MeshLODLevel = (function () {
  26409. function MeshLODLevel(distance, mesh) {
  26410. this.distance = distance;
  26411. this.mesh = mesh;
  26412. }
  26413. return MeshLODLevel;
  26414. })();
  26415. Internals.MeshLODLevel = MeshLODLevel;
  26416. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26417. })(BABYLON || (BABYLON = {}));
  26418. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26419. (function (BABYLON) {
  26420. var AudioEngine = (function () {
  26421. function AudioEngine() {
  26422. this.audioContext = null;
  26423. this.canUseWebAudio = false;
  26424. this.WarnedWebAudioUnsupported = false;
  26425. try {
  26426. if (typeof AudioContext !== 'undefined') {
  26427. this.audioContext = new AudioContext();
  26428. this.canUseWebAudio = true;
  26429. }
  26430. else if (typeof webkitAudioContext !== 'undefined') {
  26431. this.audioContext = new webkitAudioContext();
  26432. this.canUseWebAudio = true;
  26433. }
  26434. }
  26435. catch (e) {
  26436. this.canUseWebAudio = false;
  26437. BABYLON.Tools.Error("Web Audio: " + e.message);
  26438. }
  26439. // create a global volume gain node
  26440. if (this.canUseWebAudio) {
  26441. this.masterGain = this.audioContext.createGain();
  26442. this.masterGain.gain.value = 1;
  26443. this.masterGain.connect(this.audioContext.destination);
  26444. }
  26445. }
  26446. AudioEngine.prototype.dispose = function () {
  26447. if (this.canUseWebAudio) {
  26448. if (this._connectedAnalyser) {
  26449. this._connectedAnalyser.stopDebugCanvas();
  26450. this._connectedAnalyser.dispose();
  26451. this.masterGain.disconnect();
  26452. this.masterGain.connect(this.audioContext.destination);
  26453. this._connectedAnalyser = null;
  26454. }
  26455. this.masterGain.gain.value = 1;
  26456. }
  26457. this.WarnedWebAudioUnsupported = false;
  26458. };
  26459. AudioEngine.prototype.getGlobalVolume = function () {
  26460. if (this.canUseWebAudio) {
  26461. return this.masterGain.gain.value;
  26462. }
  26463. else {
  26464. return -1;
  26465. }
  26466. };
  26467. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26468. if (this.canUseWebAudio) {
  26469. this.masterGain.gain.value = newVolume;
  26470. }
  26471. };
  26472. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26473. if (this._connectedAnalyser) {
  26474. this._connectedAnalyser.stopDebugCanvas();
  26475. }
  26476. this._connectedAnalyser = analyser;
  26477. if (this.canUseWebAudio) {
  26478. this.masterGain.disconnect();
  26479. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26480. }
  26481. };
  26482. return AudioEngine;
  26483. })();
  26484. BABYLON.AudioEngine = AudioEngine;
  26485. })(BABYLON || (BABYLON = {}));
  26486. //# sourceMappingURL=babylon.audioEngine.js.mapvar BABYLON;
  26487. (function (BABYLON) {
  26488. var Sound = (function () {
  26489. /**
  26490. * Create a sound and attach it to a scene
  26491. * @param name Name of your sound
  26492. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26493. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26494. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26495. */
  26496. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26497. var _this = this;
  26498. this.autoplay = false;
  26499. this.loop = false;
  26500. this.useCustomAttenuation = false;
  26501. this.spatialSound = false;
  26502. this.refDistance = 1;
  26503. this.rolloffFactor = 1;
  26504. this.maxDistance = 100;
  26505. this.distanceModel = "linear";
  26506. this._panningModel = "equalpower";
  26507. this._playbackRate = 1;
  26508. this._startTime = 0;
  26509. this._startOffset = 0;
  26510. this._position = BABYLON.Vector3.Zero();
  26511. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26512. this._volume = 1;
  26513. this._isLoaded = false;
  26514. this._isReadyToPlay = false;
  26515. this.isPlaying = false;
  26516. this.isPaused = false;
  26517. this._isDirectional = false;
  26518. // Used if you'd like to create a directional sound.
  26519. // If not set, the sound will be omnidirectional
  26520. this._coneInnerAngle = 360;
  26521. this._coneOuterAngle = 360;
  26522. this._coneOuterGain = 0;
  26523. this.name = name;
  26524. this._scene = scene;
  26525. this._readyToPlayCallback = readyToPlayCallback;
  26526. // Default custom attenuation function is a linear attenuation
  26527. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26528. if (currentDistance < maxDistance) {
  26529. return currentVolume * (1 - currentDistance / maxDistance);
  26530. }
  26531. else {
  26532. return 0;
  26533. }
  26534. };
  26535. if (options) {
  26536. this.autoplay = options.autoplay || false;
  26537. this.loop = options.loop || false;
  26538. // if volume === 0, we need another way to check this option
  26539. if (options.volume !== undefined) {
  26540. this._volume = options.volume;
  26541. }
  26542. this.spatialSound = options.spatialSound || false;
  26543. this.maxDistance = options.maxDistance || 100;
  26544. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26545. this.rolloffFactor = options.rolloffFactor || 1;
  26546. this.refDistance = options.refDistance || 1;
  26547. this.distanceModel = options.distanceModel || "linear";
  26548. this._playbackRate = options.playbackRate || 1;
  26549. }
  26550. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26551. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26552. this._soundGain.gain.value = this._volume;
  26553. this._inputAudioNode = this._soundGain;
  26554. this._ouputAudioNode = this._soundGain;
  26555. if (this.spatialSound) {
  26556. this._createSpatialParameters();
  26557. }
  26558. this._scene.mainSoundTrack.AddSound(this);
  26559. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26560. if (urlOrArrayBuffer) {
  26561. // If it's an URL
  26562. if (typeof (urlOrArrayBuffer) === "string") {
  26563. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26564. _this._soundLoaded(data);
  26565. }, null, null, true);
  26566. }
  26567. else {
  26568. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26569. this._soundLoaded(urlOrArrayBuffer);
  26570. }
  26571. else {
  26572. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26573. }
  26574. }
  26575. }
  26576. }
  26577. else {
  26578. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26579. this._scene.mainSoundTrack.AddSound(this);
  26580. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26581. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26582. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26583. }
  26584. }
  26585. }
  26586. Sound.prototype.dispose = function () {
  26587. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26588. if (this.isPlaying) {
  26589. this.stop();
  26590. }
  26591. this._isReadyToPlay = false;
  26592. if (this.soundTrackId === -1) {
  26593. this._scene.mainSoundTrack.RemoveSound(this);
  26594. }
  26595. else {
  26596. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26597. }
  26598. if (this._soundGain) {
  26599. this._soundGain.disconnect();
  26600. this._soundGain = null;
  26601. }
  26602. if (this._soundPanner) {
  26603. this._soundPanner.disconnect();
  26604. this._soundPanner = null;
  26605. }
  26606. if (this._soundSource) {
  26607. this._soundSource.disconnect();
  26608. this._soundSource = null;
  26609. }
  26610. this._audioBuffer = null;
  26611. if (this._connectedMesh) {
  26612. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26613. this._connectedMesh = null;
  26614. }
  26615. }
  26616. };
  26617. Sound.prototype._soundLoaded = function (audioData) {
  26618. var _this = this;
  26619. this._isLoaded = true;
  26620. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26621. _this._audioBuffer = buffer;
  26622. _this._isReadyToPlay = true;
  26623. if (_this.autoplay) {
  26624. _this.play();
  26625. }
  26626. if (_this._readyToPlayCallback) {
  26627. _this._readyToPlayCallback();
  26628. }
  26629. }, function (error) {
  26630. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26631. });
  26632. };
  26633. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26635. this._audioBuffer = audioBuffer;
  26636. this._isReadyToPlay = true;
  26637. }
  26638. };
  26639. Sound.prototype.updateOptions = function (options) {
  26640. if (options) {
  26641. this.loop = options.loop || this.loop;
  26642. this.maxDistance = options.maxDistance || this.maxDistance;
  26643. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26644. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26645. this.refDistance = options.refDistance || this.refDistance;
  26646. this.distanceModel = options.distanceModel || this.distanceModel;
  26647. this._playbackRate = options.playbackRate || this._playbackRate;
  26648. }
  26649. };
  26650. Sound.prototype._createSpatialParameters = function () {
  26651. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26652. if (this._scene.headphone) {
  26653. this._panningModel = "HRTF";
  26654. }
  26655. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26656. if (this.useCustomAttenuation) {
  26657. // Tricks to disable in a way embedded Web Audio attenuation
  26658. this._soundPanner.distanceModel = "linear";
  26659. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26660. this._soundPanner.refDistance = 1;
  26661. this._soundPanner.rolloffFactor = 1;
  26662. this._soundPanner.panningModel = this._panningModel;
  26663. }
  26664. else {
  26665. this._soundPanner.distanceModel = this.distanceModel;
  26666. this._soundPanner.maxDistance = this.maxDistance;
  26667. this._soundPanner.refDistance = this.refDistance;
  26668. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26669. this._soundPanner.panningModel = this._panningModel;
  26670. }
  26671. this._soundPanner.connect(this._ouputAudioNode);
  26672. this._inputAudioNode = this._soundPanner;
  26673. }
  26674. };
  26675. Sound.prototype.switchPanningModelToHRTF = function () {
  26676. this._panningModel = "HRTF";
  26677. this._switchPanningModel();
  26678. };
  26679. Sound.prototype.switchPanningModelToEqualPower = function () {
  26680. this._panningModel = "equalpower";
  26681. this._switchPanningModel();
  26682. };
  26683. Sound.prototype._switchPanningModel = function () {
  26684. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26685. this._soundPanner.panningModel = this._panningModel;
  26686. }
  26687. };
  26688. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26689. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26690. this._ouputAudioNode.disconnect();
  26691. this._ouputAudioNode.connect(soundTrackAudioNode);
  26692. }
  26693. };
  26694. /**
  26695. * Transform this sound into a directional source
  26696. * @param coneInnerAngle Size of the inner cone in degree
  26697. * @param coneOuterAngle Size of the outer cone in degree
  26698. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26699. */
  26700. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26701. if (coneOuterAngle < coneInnerAngle) {
  26702. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26703. return;
  26704. }
  26705. this._coneInnerAngle = coneInnerAngle;
  26706. this._coneOuterAngle = coneOuterAngle;
  26707. this._coneOuterGain = coneOuterGain;
  26708. this._isDirectional = true;
  26709. if (this.isPlaying && this.loop) {
  26710. this.stop();
  26711. this.play();
  26712. }
  26713. };
  26714. Sound.prototype.setPosition = function (newPosition) {
  26715. this._position = newPosition;
  26716. if (this.isPlaying && this.spatialSound) {
  26717. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26718. }
  26719. };
  26720. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26721. this._localDirection = newLocalDirection;
  26722. if (this._connectedMesh && this.isPlaying) {
  26723. this._updateDirection();
  26724. }
  26725. };
  26726. Sound.prototype._updateDirection = function () {
  26727. var mat = this._connectedMesh.getWorldMatrix();
  26728. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26729. direction.normalize();
  26730. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26731. };
  26732. Sound.prototype.updateDistanceFromListener = function () {
  26733. if (this._connectedMesh && this.useCustomAttenuation) {
  26734. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26735. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26736. }
  26737. };
  26738. Sound.prototype.setAttenuationFunction = function (callback) {
  26739. this._customAttenuationFunction = callback;
  26740. };
  26741. /**
  26742. * Play the sound
  26743. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26744. */
  26745. Sound.prototype.play = function (time) {
  26746. var _this = this;
  26747. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26748. try {
  26749. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26750. if (!this._soundSource) {
  26751. if (this.spatialSound) {
  26752. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26753. if (this._isDirectional) {
  26754. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26755. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26756. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26757. if (this._connectedMesh) {
  26758. this._updateDirection();
  26759. }
  26760. else {
  26761. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26762. }
  26763. }
  26764. }
  26765. }
  26766. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26767. this._soundSource.buffer = this._audioBuffer;
  26768. this._soundSource.connect(this._inputAudioNode);
  26769. this._soundSource.loop = this.loop;
  26770. this._soundSource.playbackRate.value = this._playbackRate;
  26771. this._startTime = startTime;
  26772. this._soundSource.onended = function () {
  26773. _this._onended();
  26774. };
  26775. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26776. this.isPlaying = true;
  26777. this.isPaused = false;
  26778. }
  26779. catch (ex) {
  26780. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26781. }
  26782. }
  26783. };
  26784. Sound.prototype._onended = function () {
  26785. this.isPlaying = false;
  26786. if (this.onended) {
  26787. this.onended();
  26788. }
  26789. };
  26790. /**
  26791. * Stop the sound
  26792. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26793. */
  26794. Sound.prototype.stop = function (time) {
  26795. if (this.isPlaying) {
  26796. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26797. this._soundSource.stop(stopTime);
  26798. this.isPlaying = false;
  26799. }
  26800. };
  26801. Sound.prototype.pause = function () {
  26802. if (this.isPlaying) {
  26803. this.stop(0);
  26804. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26805. this.isPaused = true;
  26806. }
  26807. };
  26808. Sound.prototype.setVolume = function (newVolume, time) {
  26809. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26810. if (time) {
  26811. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26812. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26813. }
  26814. else {
  26815. this._soundGain.gain.value = newVolume;
  26816. }
  26817. }
  26818. this._volume = newVolume;
  26819. };
  26820. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26821. this._playbackRate = newPlaybackRate;
  26822. if (this.isPlaying) {
  26823. this._soundSource.playbackRate.value = this._playbackRate;
  26824. }
  26825. };
  26826. Sound.prototype.getVolume = function () {
  26827. return this._volume;
  26828. };
  26829. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26830. var _this = this;
  26831. this._connectedMesh = meshToConnectTo;
  26832. if (!this.spatialSound) {
  26833. this._createSpatialParameters();
  26834. this.spatialSound = true;
  26835. if (this.isPlaying && this.loop) {
  26836. this.stop();
  26837. this.play();
  26838. }
  26839. }
  26840. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26841. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26842. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26843. };
  26844. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26845. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26846. if (this._isDirectional && this.isPlaying) {
  26847. this._updateDirection();
  26848. }
  26849. };
  26850. return Sound;
  26851. })();
  26852. BABYLON.Sound = Sound;
  26853. })(BABYLON || (BABYLON = {}));
  26854. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26855. (function (BABYLON) {
  26856. var SoundTrack = (function () {
  26857. function SoundTrack(scene, options) {
  26858. this.id = -1;
  26859. this._isMainTrack = false;
  26860. this._scene = scene;
  26861. this._audioEngine = BABYLON.Engine.audioEngine;
  26862. this.soundCollection = new Array();
  26863. if (this._audioEngine.canUseWebAudio) {
  26864. this._trackGain = this._audioEngine.audioContext.createGain();
  26865. this._trackGain.connect(this._audioEngine.masterGain);
  26866. if (options) {
  26867. if (options.volume) {
  26868. this._trackGain.gain.value = options.volume;
  26869. }
  26870. if (options.mainTrack) {
  26871. this._isMainTrack = options.mainTrack;
  26872. }
  26873. }
  26874. }
  26875. if (!this._isMainTrack) {
  26876. this._scene.soundTracks.push(this);
  26877. this.id = this._scene.soundTracks.length - 1;
  26878. }
  26879. }
  26880. SoundTrack.prototype.dispose = function () {
  26881. if (this._audioEngine.canUseWebAudio) {
  26882. if (this._connectedAnalyser) {
  26883. this._connectedAnalyser.stopDebugCanvas();
  26884. }
  26885. while (this.soundCollection.length) {
  26886. this.soundCollection[0].dispose();
  26887. }
  26888. this._trackGain.disconnect();
  26889. this._trackGain = null;
  26890. }
  26891. };
  26892. SoundTrack.prototype.AddSound = function (sound) {
  26893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26894. sound.connectToSoundTrackAudioNode(this._trackGain);
  26895. }
  26896. if (sound.soundTrackId) {
  26897. if (sound.soundTrackId === -1) {
  26898. this._scene.mainSoundTrack.RemoveSound(sound);
  26899. }
  26900. else {
  26901. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26902. }
  26903. }
  26904. this.soundCollection.push(sound);
  26905. sound.soundTrackId = this.id;
  26906. };
  26907. SoundTrack.prototype.RemoveSound = function (sound) {
  26908. var index = this.soundCollection.indexOf(sound);
  26909. if (index !== -1) {
  26910. this.soundCollection.splice(index, 1);
  26911. }
  26912. };
  26913. SoundTrack.prototype.setVolume = function (newVolume) {
  26914. if (this._audioEngine.canUseWebAudio) {
  26915. this._trackGain.gain.value = newVolume;
  26916. }
  26917. };
  26918. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26919. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26920. for (var i = 0; i < this.soundCollection.length; i++) {
  26921. this.soundCollection[i].switchPanningModelToHRTF();
  26922. }
  26923. }
  26924. };
  26925. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26926. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26927. for (var i = 0; i < this.soundCollection.length; i++) {
  26928. this.soundCollection[i].switchPanningModelToEqualPower();
  26929. }
  26930. }
  26931. };
  26932. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26933. if (this._connectedAnalyser) {
  26934. this._connectedAnalyser.stopDebugCanvas();
  26935. }
  26936. this._connectedAnalyser = analyser;
  26937. if (this._audioEngine.canUseWebAudio) {
  26938. this._trackGain.disconnect();
  26939. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26940. }
  26941. };
  26942. return SoundTrack;
  26943. })();
  26944. BABYLON.SoundTrack = SoundTrack;
  26945. })(BABYLON || (BABYLON = {}));
  26946. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26947. (function (BABYLON) {
  26948. var DebugLayer = (function () {
  26949. function DebugLayer(scene) {
  26950. var _this = this;
  26951. this._transformationMatrix = BABYLON.Matrix.Identity();
  26952. this._enabled = false;
  26953. this._labelsEnabled = false;
  26954. this._displayStatistics = true;
  26955. this._displayTree = false;
  26956. this._displayLogs = false;
  26957. this._identityMatrix = BABYLON.Matrix.Identity();
  26958. this.axisRatio = 0.02;
  26959. this.accentColor = "orange";
  26960. this._scene = scene;
  26961. this._syncPositions = function () {
  26962. var engine = _this._scene.getEngine();
  26963. var canvasRect = engine.getRenderingCanvasClientRect();
  26964. if (_this._showUI) {
  26965. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26966. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26967. _this._statsDiv.style.width = "400px";
  26968. _this._statsDiv.style.height = "auto";
  26969. _this._statsSubsetDiv.style.maxHeight = "240px";
  26970. _this._optionsDiv.style.left = "0px";
  26971. _this._optionsDiv.style.top = "10px";
  26972. _this._optionsDiv.style.width = "200px";
  26973. _this._optionsDiv.style.height = "auto";
  26974. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26975. _this._logDiv.style.left = "0px";
  26976. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26977. _this._logDiv.style.width = "600px";
  26978. _this._logDiv.style.height = "160px";
  26979. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26980. _this._treeDiv.style.top = "10px";
  26981. _this._treeDiv.style.width = "300px";
  26982. _this._treeDiv.style.height = "auto";
  26983. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26984. }
  26985. _this._globalDiv.style.left = canvasRect.left + "px";
  26986. _this._globalDiv.style.top = canvasRect.top + "px";
  26987. _this._drawingCanvas.style.left = "0px";
  26988. _this._drawingCanvas.style.top = "0px";
  26989. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26990. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26991. var devicePixelRatio = window.devicePixelRatio || 1;
  26992. var context = _this._drawingContext;
  26993. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26994. _this._ratio = devicePixelRatio / backingStoreRatio;
  26995. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26996. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26997. };
  26998. this._onCanvasClick = function (evt) {
  26999. _this._clickPosition = {
  27000. x: evt.clientX * _this._ratio,
  27001. y: evt.clientY * _this._ratio
  27002. };
  27003. };
  27004. this._syncUI = function () {
  27005. if (_this._showUI) {
  27006. if (_this._displayStatistics) {
  27007. _this._displayStats();
  27008. _this._statsDiv.style.display = "";
  27009. }
  27010. else {
  27011. _this._statsDiv.style.display = "none";
  27012. }
  27013. if (_this._displayLogs) {
  27014. _this._logDiv.style.display = "";
  27015. }
  27016. else {
  27017. _this._logDiv.style.display = "none";
  27018. }
  27019. if (_this._displayTree) {
  27020. _this._treeDiv.style.display = "";
  27021. if (_this._needToRefreshMeshesTree) {
  27022. _this._needToRefreshMeshesTree = false;
  27023. _this._refreshMeshesTreeContent();
  27024. }
  27025. }
  27026. else {
  27027. _this._treeDiv.style.display = "none";
  27028. }
  27029. }
  27030. };
  27031. this._syncData = function () {
  27032. if (_this._labelsEnabled || !_this._showUI) {
  27033. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  27034. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  27035. var engine = _this._scene.getEngine();
  27036. var viewport = _this._camera.viewport;
  27037. var globalViewport = viewport.toGlobal(engine);
  27038. // Meshes
  27039. var meshes = _this._camera.getActiveMeshes();
  27040. for (var index = 0; index < meshes.length; index++) {
  27041. var mesh = meshes.data[index];
  27042. var position = mesh.getBoundingInfo().boundingSphere.center;
  27043. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27044. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  27045. _this._renderAxis(projectedPosition, mesh, globalViewport);
  27046. }
  27047. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  27048. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  27049. mesh.renderOverlay = !mesh.renderOverlay;
  27050. }, function () {
  27051. return mesh.renderOverlay ? 'red' : 'black';
  27052. });
  27053. }
  27054. }
  27055. // Cameras
  27056. var cameras = _this._scene.cameras;
  27057. for (index = 0; index < cameras.length; index++) {
  27058. var camera = cameras[index];
  27059. if (camera === _this._camera) {
  27060. continue;
  27061. }
  27062. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  27063. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  27064. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  27065. _this._camera.detachControl(engine.getRenderingCanvas());
  27066. _this._camera = camera;
  27067. _this._camera.attachControl(engine.getRenderingCanvas());
  27068. }, function () {
  27069. return "purple";
  27070. });
  27071. }
  27072. }
  27073. // Lights
  27074. var lights = _this._scene.lights;
  27075. for (index = 0; index < lights.length; index++) {
  27076. var light = lights[index];
  27077. if (light.position) {
  27078. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  27079. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  27080. _this._renderLabel(light.name, projectedPosition, -20, function () {
  27081. light.setEnabled(!light.isEnabled());
  27082. }, function () {
  27083. return light.isEnabled() ? "orange" : "gray";
  27084. });
  27085. }
  27086. }
  27087. }
  27088. }
  27089. _this._clickPosition = undefined;
  27090. };
  27091. }
  27092. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  27093. while (this._treeSubsetDiv.hasChildNodes()) {
  27094. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  27095. }
  27096. // Add meshes
  27097. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  27098. sortedArray.sort(function (a, b) {
  27099. if (a.name === b.name) {
  27100. return 0;
  27101. }
  27102. return (a.name > b.name) ? 1 : -1;
  27103. });
  27104. for (var index = 0; index < sortedArray.length; index++) {
  27105. var mesh = sortedArray[index];
  27106. if (!mesh.isEnabled()) {
  27107. continue;
  27108. }
  27109. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  27110. m.isVisible = element.checked;
  27111. }, mesh);
  27112. }
  27113. };
  27114. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  27115. this._drawingContext.beginPath();
  27116. this._drawingContext.moveTo(zero.x, zero.y);
  27117. this._drawingContext.lineTo(unit.x, unit.y);
  27118. this._drawingContext.strokeStyle = color;
  27119. this._drawingContext.lineWidth = 4;
  27120. this._drawingContext.stroke();
  27121. this._drawingContext.font = "normal 14px Segoe UI";
  27122. this._drawingContext.fillStyle = color;
  27123. this._drawingContext.fillText(label, unitText.x, unitText.y);
  27124. };
  27125. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  27126. var position = mesh.getBoundingInfo().boundingSphere.center;
  27127. var worldMatrix = mesh.getWorldMatrix();
  27128. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  27129. var unit = (unprojectedVector.subtract(position)).length();
  27130. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27131. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27132. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  27133. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27134. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  27135. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  27136. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  27137. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  27138. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  27139. };
  27140. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  27141. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  27142. this._drawingContext.font = "normal 12px Segoe UI";
  27143. var textMetrics = this._drawingContext.measureText(text);
  27144. var centerX = projectedPosition.x - textMetrics.width / 2;
  27145. var centerY = projectedPosition.y;
  27146. var clientRect = this._drawingCanvas.getBoundingClientRect();
  27147. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  27148. onClick();
  27149. }
  27150. this._drawingContext.beginPath();
  27151. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  27152. this._drawingContext.fillStyle = getFillStyle();
  27153. this._drawingContext.globalAlpha = 0.5;
  27154. this._drawingContext.fill();
  27155. this._drawingContext.globalAlpha = 1.0;
  27156. this._drawingContext.strokeStyle = '#FFFFFF';
  27157. this._drawingContext.lineWidth = 1;
  27158. this._drawingContext.stroke();
  27159. this._drawingContext.fillStyle = "#FFFFFF";
  27160. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  27161. this._drawingContext.beginPath();
  27162. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  27163. this._drawingContext.fill();
  27164. }
  27165. };
  27166. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  27167. if (!this._clickPosition) {
  27168. return false;
  27169. }
  27170. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  27171. return false;
  27172. }
  27173. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  27174. return false;
  27175. }
  27176. return true;
  27177. };
  27178. DebugLayer.prototype.isVisible = function () {
  27179. return this._enabled;
  27180. };
  27181. DebugLayer.prototype.hide = function () {
  27182. if (!this._enabled) {
  27183. return;
  27184. }
  27185. this._enabled = false;
  27186. var engine = this._scene.getEngine();
  27187. this._scene.unregisterBeforeRender(this._syncData);
  27188. this._scene.unregisterAfterRender(this._syncUI);
  27189. document.body.removeChild(this._globalDiv);
  27190. window.removeEventListener("resize", this._syncPositions);
  27191. this._scene.forceShowBoundingBoxes = false;
  27192. this._scene.forceWireframe = false;
  27193. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  27194. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  27195. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  27196. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  27197. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  27198. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  27199. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  27200. this._scene.shadowsEnabled = true;
  27201. this._scene.particlesEnabled = true;
  27202. this._scene.postProcessesEnabled = true;
  27203. this._scene.collisionsEnabled = true;
  27204. this._scene.lightsEnabled = true;
  27205. this._scene.texturesEnabled = true;
  27206. this._scene.lensFlaresEnabled = true;
  27207. this._scene.proceduralTexturesEnabled = true;
  27208. this._scene.renderTargetsEnabled = true;
  27209. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  27210. };
  27211. DebugLayer.prototype.show = function (showUI, camera) {
  27212. if (showUI === void 0) { showUI = true; }
  27213. if (camera === void 0) { camera = null; }
  27214. if (this._enabled) {
  27215. return;
  27216. }
  27217. if (camera) {
  27218. this._camera = camera;
  27219. }
  27220. else {
  27221. this._camera = this._scene.activeCamera;
  27222. }
  27223. this._enabled = true;
  27224. this._showUI = showUI;
  27225. var engine = this._scene.getEngine();
  27226. this._globalDiv = document.createElement("div");
  27227. document.body.appendChild(this._globalDiv);
  27228. this._generateDOMelements();
  27229. window.addEventListener("resize", this._syncPositions);
  27230. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  27231. this._syncPositions();
  27232. this._scene.registerBeforeRender(this._syncData);
  27233. this._scene.registerAfterRender(this._syncUI);
  27234. };
  27235. DebugLayer.prototype._clearLabels = function () {
  27236. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  27237. for (var index = 0; index < this._scene.meshes.length; index++) {
  27238. var mesh = this._scene.meshes[index];
  27239. mesh.renderOverlay = false;
  27240. }
  27241. };
  27242. DebugLayer.prototype._generateheader = function (root, text) {
  27243. var header = document.createElement("div");
  27244. header.innerHTML = text + "&nbsp;";
  27245. header.style.textAlign = "right";
  27246. header.style.width = "100%";
  27247. header.style.color = "white";
  27248. header.style.backgroundColor = "Black";
  27249. header.style.padding = "5px 5px 4px 0px";
  27250. header.style.marginLeft = "-5px";
  27251. header.style.fontWeight = "bold";
  27252. root.appendChild(header);
  27253. };
  27254. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  27255. var label = document.createElement("label");
  27256. label.innerHTML = title;
  27257. label.style.color = color;
  27258. root.appendChild(label);
  27259. root.appendChild(document.createElement("br"));
  27260. };
  27261. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  27262. if (tag === void 0) { tag = null; }
  27263. var label = document.createElement("label");
  27264. var boundingBoxesCheckbox = document.createElement("input");
  27265. boundingBoxesCheckbox.type = "checkbox";
  27266. boundingBoxesCheckbox.checked = initialState;
  27267. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  27268. task(evt.target, tag);
  27269. });
  27270. label.appendChild(boundingBoxesCheckbox);
  27271. var container = document.createElement("span");
  27272. var leftPart = document.createElement("span");
  27273. var rightPart = document.createElement("span");
  27274. rightPart.style.cssFloat = "right";
  27275. leftPart.innerHTML = leftTitle;
  27276. rightPart.innerHTML = rightTitle;
  27277. rightPart.style.fontSize = "12px";
  27278. rightPart.style.maxWidth = "200px";
  27279. container.appendChild(leftPart);
  27280. container.appendChild(rightPart);
  27281. label.appendChild(container);
  27282. root.appendChild(label);
  27283. root.appendChild(document.createElement("br"));
  27284. };
  27285. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27286. if (tag === void 0) { tag = null; }
  27287. var label = document.createElement("label");
  27288. var checkBox = document.createElement("input");
  27289. checkBox.type = "checkbox";
  27290. checkBox.checked = initialState;
  27291. checkBox.addEventListener("change", function (evt) {
  27292. task(evt.target, tag);
  27293. });
  27294. label.appendChild(checkBox);
  27295. label.appendChild(document.createTextNode(title));
  27296. root.appendChild(label);
  27297. root.appendChild(document.createElement("br"));
  27298. };
  27299. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27300. if (tag === void 0) { tag = null; }
  27301. var button = document.createElement("button");
  27302. button.innerHTML = title;
  27303. button.style.height = "24px";
  27304. button.style.color = "#444444";
  27305. button.style.border = "1px solid white";
  27306. button.className = "debugLayerButton";
  27307. button.addEventListener("click", function (evt) {
  27308. task(evt.target, tag);
  27309. });
  27310. root.appendChild(button);
  27311. root.appendChild(document.createElement("br"));
  27312. };
  27313. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27314. if (tag === void 0) { tag = null; }
  27315. var label = document.createElement("label");
  27316. var boundingBoxesRadio = document.createElement("input");
  27317. boundingBoxesRadio.type = "radio";
  27318. boundingBoxesRadio.name = name;
  27319. boundingBoxesRadio.checked = initialState;
  27320. boundingBoxesRadio.addEventListener("change", function (evt) {
  27321. task(evt.target, tag);
  27322. });
  27323. label.appendChild(boundingBoxesRadio);
  27324. label.appendChild(document.createTextNode(title));
  27325. root.appendChild(label);
  27326. root.appendChild(document.createElement("br"));
  27327. };
  27328. DebugLayer.prototype._generateDOMelements = function () {
  27329. var _this = this;
  27330. this._globalDiv.id = "DebugLayer";
  27331. this._globalDiv.style.position = "absolute";
  27332. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27333. this._globalDiv.style.fontSize = "14px";
  27334. this._globalDiv.style.color = "white";
  27335. // Drawing canvas
  27336. this._drawingCanvas = document.createElement("canvas");
  27337. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27338. this._drawingCanvas.style.position = "absolute";
  27339. this._drawingCanvas.style.pointerEvents = "none";
  27340. this._drawingContext = this._drawingCanvas.getContext("2d");
  27341. this._globalDiv.appendChild(this._drawingCanvas);
  27342. if (this._showUI) {
  27343. var background = "rgba(128, 128, 128, 0.4)";
  27344. var border = "rgb(180, 180, 180) solid 1px";
  27345. // Stats
  27346. this._statsDiv = document.createElement("div");
  27347. this._statsDiv.id = "DebugLayerStats";
  27348. this._statsDiv.style.border = border;
  27349. this._statsDiv.style.position = "absolute";
  27350. this._statsDiv.style.background = background;
  27351. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27352. this._generateheader(this._statsDiv, "STATISTICS");
  27353. this._statsSubsetDiv = document.createElement("div");
  27354. this._statsSubsetDiv.style.paddingTop = "5px";
  27355. this._statsSubsetDiv.style.paddingBottom = "5px";
  27356. this._statsSubsetDiv.style.overflowY = "auto";
  27357. this._statsDiv.appendChild(this._statsSubsetDiv);
  27358. // Tree
  27359. this._treeDiv = document.createElement("div");
  27360. this._treeDiv.id = "DebugLayerTree";
  27361. this._treeDiv.style.border = border;
  27362. this._treeDiv.style.position = "absolute";
  27363. this._treeDiv.style.background = background;
  27364. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27365. this._treeDiv.style.display = "none";
  27366. this._generateheader(this._treeDiv, "MESHES TREE");
  27367. this._treeSubsetDiv = document.createElement("div");
  27368. this._treeSubsetDiv.style.paddingTop = "5px";
  27369. this._treeSubsetDiv.style.paddingRight = "5px";
  27370. this._treeSubsetDiv.style.overflowY = "auto";
  27371. this._treeSubsetDiv.style.maxHeight = "300px";
  27372. this._treeDiv.appendChild(this._treeSubsetDiv);
  27373. this._needToRefreshMeshesTree = true;
  27374. // Logs
  27375. this._logDiv = document.createElement("div");
  27376. this._logDiv.style.border = border;
  27377. this._logDiv.id = "DebugLayerLogs";
  27378. this._logDiv.style.position = "absolute";
  27379. this._logDiv.style.background = background;
  27380. this._logDiv.style.padding = "0px 0px 0px 5px";
  27381. this._logDiv.style.display = "none";
  27382. this._generateheader(this._logDiv, "LOGS");
  27383. this._logSubsetDiv = document.createElement("div");
  27384. this._logSubsetDiv.style.height = "127px";
  27385. this._logSubsetDiv.style.paddingTop = "5px";
  27386. this._logSubsetDiv.style.overflowY = "auto";
  27387. this._logSubsetDiv.style.fontSize = "12px";
  27388. this._logSubsetDiv.style.fontFamily = "consolas";
  27389. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27390. this._logDiv.appendChild(this._logSubsetDiv);
  27391. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27392. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27393. };
  27394. // Options
  27395. this._optionsDiv = document.createElement("div");
  27396. this._optionsDiv.id = "DebugLayerOptions";
  27397. this._optionsDiv.style.border = border;
  27398. this._optionsDiv.style.position = "absolute";
  27399. this._optionsDiv.style.background = background;
  27400. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27401. this._optionsDiv.style.overflowY = "auto";
  27402. this._generateheader(this._optionsDiv, "OPTIONS");
  27403. this._optionsSubsetDiv = document.createElement("div");
  27404. this._optionsSubsetDiv.style.paddingTop = "5px";
  27405. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27406. this._optionsSubsetDiv.style.overflowY = "auto";
  27407. this._optionsSubsetDiv.style.maxHeight = "200px";
  27408. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27409. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27410. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27411. _this._displayStatistics = element.checked;
  27412. });
  27413. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27414. _this._displayLogs = element.checked;
  27415. });
  27416. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27417. _this._displayTree = element.checked;
  27418. _this._needToRefreshMeshesTree = true;
  27419. });
  27420. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27421. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27422. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27423. _this._scene.forceShowBoundingBoxes = element.checked;
  27424. });
  27425. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27426. _this._labelsEnabled = element.checked;
  27427. if (!_this._labelsEnabled) {
  27428. _this._clearLabels();
  27429. }
  27430. });
  27431. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27432. if (element.checked) {
  27433. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27434. }
  27435. else {
  27436. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27437. }
  27438. });
  27439. ;
  27440. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27441. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27442. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27443. if (element.checked) {
  27444. _this._scene.forceWireframe = false;
  27445. _this._scene.forcePointsCloud = false;
  27446. }
  27447. });
  27448. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27449. if (element.checked) {
  27450. _this._scene.forceWireframe = true;
  27451. _this._scene.forcePointsCloud = false;
  27452. }
  27453. });
  27454. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27455. if (element.checked) {
  27456. _this._scene.forceWireframe = false;
  27457. _this._scene.forcePointsCloud = true;
  27458. }
  27459. });
  27460. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27461. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27462. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27463. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27464. });
  27465. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27466. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27467. });
  27468. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27469. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27470. });
  27471. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27472. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27473. });
  27474. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27475. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27476. });
  27477. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27478. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27479. });
  27480. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27481. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27482. });
  27483. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27484. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27485. });
  27486. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27487. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27488. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27489. _this._scene.animationsEnabled = element.checked;
  27490. });
  27491. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27492. _this._scene.collisionsEnabled = element.checked;
  27493. });
  27494. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27495. _this._scene.fogEnabled = element.checked;
  27496. });
  27497. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27498. _this._scene.lensFlaresEnabled = element.checked;
  27499. });
  27500. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27501. _this._scene.lightsEnabled = element.checked;
  27502. });
  27503. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27504. _this._scene.particlesEnabled = element.checked;
  27505. });
  27506. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27507. _this._scene.postProcessesEnabled = element.checked;
  27508. });
  27509. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27510. _this._scene.proceduralTexturesEnabled = element.checked;
  27511. });
  27512. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27513. _this._scene.renderTargetsEnabled = element.checked;
  27514. });
  27515. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27516. _this._scene.shadowsEnabled = element.checked;
  27517. });
  27518. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27519. _this._scene.skeletonsEnabled = element.checked;
  27520. });
  27521. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27522. _this._scene.spritesEnabled = element.checked;
  27523. });
  27524. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27525. _this._scene.texturesEnabled = element.checked;
  27526. });
  27527. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27528. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27529. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27530. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  27531. if (element.checked) {
  27532. _this._scene.headphone = true;
  27533. }
  27534. });
  27535. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  27536. if (element.checked) {
  27537. _this._scene.headphone = false;
  27538. }
  27539. });
  27540. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27541. _this._scene.audioEnabled = !element.checked;
  27542. });
  27543. }
  27544. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27545. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27546. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27547. _this._scene.dumpNextRenderTargets = true;
  27548. });
  27549. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27550. this._globalDiv.appendChild(this._statsDiv);
  27551. this._globalDiv.appendChild(this._logDiv);
  27552. this._globalDiv.appendChild(this._optionsDiv);
  27553. this._globalDiv.appendChild(this._treeDiv);
  27554. }
  27555. };
  27556. DebugLayer.prototype._displayStats = function () {
  27557. var scene = this._scene;
  27558. var engine = scene.getEngine();
  27559. var glInfo = engine.getGlInfo();
  27560. 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>";
  27561. if (this.customStatsFunction) {
  27562. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27563. }
  27564. };
  27565. return DebugLayer;
  27566. })();
  27567. BABYLON.DebugLayer = DebugLayer;
  27568. })(BABYLON || (BABYLON = {}));
  27569. //# sourceMappingURL=babylon.debugLayer.js.map
  27570. var BABYLON;
  27571. (function (BABYLON) {
  27572. var RawTexture = (function (_super) {
  27573. __extends(RawTexture, _super);
  27574. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27575. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27576. if (invertY === void 0) { invertY = false; }
  27577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27578. _super.call(this, null, scene, !generateMipMaps, invertY);
  27579. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27580. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27581. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27582. }
  27583. // Statics
  27584. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27585. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27586. if (invertY === void 0) { invertY = false; }
  27587. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27588. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27589. };
  27590. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27591. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27592. if (invertY === void 0) { invertY = false; }
  27593. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27594. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27595. };
  27596. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27597. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27598. if (invertY === void 0) { invertY = false; }
  27599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27600. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27601. };
  27602. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27603. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27604. if (invertY === void 0) { invertY = false; }
  27605. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27606. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27607. };
  27608. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27609. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27610. if (invertY === void 0) { invertY = false; }
  27611. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27612. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27613. };
  27614. return RawTexture;
  27615. })(BABYLON.Texture);
  27616. BABYLON.RawTexture = RawTexture;
  27617. })(BABYLON || (BABYLON = {}));
  27618. //# sourceMappingURL=babylon.rawTexture.js.map
  27619. var BABYLON;
  27620. (function (BABYLON) {
  27621. var IndexedVector2 = (function (_super) {
  27622. __extends(IndexedVector2, _super);
  27623. function IndexedVector2(original, index) {
  27624. _super.call(this, original.x, original.y);
  27625. this.index = index;
  27626. }
  27627. return IndexedVector2;
  27628. })(BABYLON.Vector2);
  27629. var PolygonPoints = (function () {
  27630. function PolygonPoints() {
  27631. this.elements = new Array();
  27632. }
  27633. PolygonPoints.prototype.add = function (originalPoints) {
  27634. var _this = this;
  27635. var result = new Array();
  27636. originalPoints.forEach(function (point) {
  27637. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27638. var newPoint = new IndexedVector2(point, _this.elements.length);
  27639. result.push(newPoint);
  27640. _this.elements.push(newPoint);
  27641. }
  27642. });
  27643. return result;
  27644. };
  27645. PolygonPoints.prototype.computeBounds = function () {
  27646. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27647. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27648. this.elements.forEach(function (point) {
  27649. // x
  27650. if (point.x < lmin.x) {
  27651. lmin.x = point.x;
  27652. }
  27653. else if (point.x > lmax.x) {
  27654. lmax.x = point.x;
  27655. }
  27656. // y
  27657. if (point.y < lmin.y) {
  27658. lmin.y = point.y;
  27659. }
  27660. else if (point.y > lmax.y) {
  27661. lmax.y = point.y;
  27662. }
  27663. });
  27664. return {
  27665. min: lmin,
  27666. max: lmax,
  27667. width: lmax.x - lmin.x,
  27668. height: lmax.y - lmin.y
  27669. };
  27670. };
  27671. return PolygonPoints;
  27672. })();
  27673. var Polygon = (function () {
  27674. function Polygon() {
  27675. }
  27676. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27677. return [
  27678. new BABYLON.Vector2(xmin, ymin),
  27679. new BABYLON.Vector2(xmax, ymin),
  27680. new BABYLON.Vector2(xmax, ymax),
  27681. new BABYLON.Vector2(xmin, ymax)
  27682. ];
  27683. };
  27684. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27685. if (cx === void 0) { cx = 0; }
  27686. if (cy === void 0) { cy = 0; }
  27687. if (numberOfSides === void 0) { numberOfSides = 32; }
  27688. var result = new Array();
  27689. var angle = 0;
  27690. var increment = (Math.PI * 2) / numberOfSides;
  27691. for (var i = 0; i < numberOfSides; i++) {
  27692. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27693. angle -= increment;
  27694. }
  27695. return result;
  27696. };
  27697. Polygon.Parse = function (input) {
  27698. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27699. var i, result = [];
  27700. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27701. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27702. }
  27703. return result;
  27704. };
  27705. Polygon.StartingAt = function (x, y) {
  27706. return BABYLON.Path2.StartingAt(x, y);
  27707. };
  27708. return Polygon;
  27709. })();
  27710. BABYLON.Polygon = Polygon;
  27711. var PolygonMeshBuilder = (function () {
  27712. function PolygonMeshBuilder(name, contours, scene) {
  27713. this._points = new PolygonPoints();
  27714. if (!("poly2tri" in window)) {
  27715. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27716. }
  27717. this._name = name;
  27718. this._scene = scene;
  27719. var points;
  27720. if (contours instanceof BABYLON.Path2) {
  27721. points = contours.getPoints();
  27722. }
  27723. else {
  27724. points = contours;
  27725. }
  27726. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27727. }
  27728. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27729. this._swctx.addHole(this._points.add(hole));
  27730. return this;
  27731. };
  27732. PolygonMeshBuilder.prototype.build = function (updatable) {
  27733. if (updatable === void 0) { updatable = false; }
  27734. var result = new BABYLON.Mesh(this._name, this._scene);
  27735. var normals = [];
  27736. var positions = [];
  27737. var uvs = [];
  27738. var bounds = this._points.computeBounds();
  27739. this._points.elements.forEach(function (p) {
  27740. normals.push(0, 1.0, 0);
  27741. positions.push(p.x, 0, p.y);
  27742. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27743. });
  27744. var indices = [];
  27745. this._swctx.triangulate();
  27746. this._swctx.getTriangles().forEach(function (triangle) {
  27747. triangle.getPoints().forEach(function (point) {
  27748. indices.push(point.index);
  27749. });
  27750. });
  27751. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27752. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27753. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27754. result.setIndices(indices);
  27755. return result;
  27756. };
  27757. return PolygonMeshBuilder;
  27758. })();
  27759. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27760. })(BABYLON || (BABYLON = {}));
  27761. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27762. (function (BABYLON) {
  27763. var SimplificationSettings = (function () {
  27764. function SimplificationSettings(quality, distance) {
  27765. this.quality = quality;
  27766. this.distance = distance;
  27767. }
  27768. return SimplificationSettings;
  27769. })();
  27770. BABYLON.SimplificationSettings = SimplificationSettings;
  27771. var SimplificationQueue = (function () {
  27772. function SimplificationQueue() {
  27773. this.running = false;
  27774. this._simplificationArray = [];
  27775. }
  27776. SimplificationQueue.prototype.addTask = function (task) {
  27777. this._simplificationArray.push(task);
  27778. };
  27779. SimplificationQueue.prototype.executeNext = function () {
  27780. var task = this._simplificationArray.pop();
  27781. if (task) {
  27782. this.running = true;
  27783. this.runSimplification(task);
  27784. }
  27785. else {
  27786. this.running = false;
  27787. }
  27788. };
  27789. SimplificationQueue.prototype.runSimplification = function (task) {
  27790. var _this = this;
  27791. function setLODLevel(distance, mesh) {
  27792. }
  27793. if (task.parallelProcessing) {
  27794. //parallel simplifier
  27795. task.settings.forEach(function (setting) {
  27796. var simplifier = _this.getSimplifier(task);
  27797. simplifier.simplify(setting, function (newMesh) {
  27798. task.mesh.addLODLevel(setting.distance, newMesh);
  27799. //check if it is the last
  27800. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  27801. //all done, run the success callback.
  27802. task.successCallback();
  27803. }
  27804. _this.executeNext();
  27805. });
  27806. });
  27807. }
  27808. else {
  27809. //single simplifier.
  27810. var simplifier = this.getSimplifier(task);
  27811. var runDecimation = function (setting, callback) {
  27812. simplifier.simplify(setting, function (newMesh) {
  27813. task.mesh.addLODLevel(setting.distance, newMesh);
  27814. //run the next quality level
  27815. callback();
  27816. });
  27817. };
  27818. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  27819. runDecimation(task.settings[loop.index], function () {
  27820. loop.executeNext();
  27821. });
  27822. }, function () {
  27823. //execution ended, run the success callback.
  27824. if (task.successCallback) {
  27825. task.successCallback();
  27826. }
  27827. _this.executeNext();
  27828. });
  27829. }
  27830. };
  27831. SimplificationQueue.prototype.getSimplifier = function (task) {
  27832. switch (task.simplificationType) {
  27833. case 0 /* QUADRATIC */:
  27834. default:
  27835. return new QuadraticErrorSimplification(task.mesh);
  27836. }
  27837. };
  27838. return SimplificationQueue;
  27839. })();
  27840. BABYLON.SimplificationQueue = SimplificationQueue;
  27841. /**
  27842. * The implemented types of simplification.
  27843. * At the moment only Quadratic Error Decimation is implemented.
  27844. */
  27845. (function (SimplificationType) {
  27846. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27847. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27848. var SimplificationType = BABYLON.SimplificationType;
  27849. var DecimationTriangle = (function () {
  27850. function DecimationTriangle(vertices) {
  27851. this.vertices = vertices;
  27852. this.error = new Array(4);
  27853. this.deleted = false;
  27854. this.isDirty = false;
  27855. this.borderFactor = 0;
  27856. }
  27857. return DecimationTriangle;
  27858. })();
  27859. BABYLON.DecimationTriangle = DecimationTriangle;
  27860. var DecimationVertex = (function () {
  27861. function DecimationVertex(position, normal, uv, id) {
  27862. this.position = position;
  27863. this.normal = normal;
  27864. this.uv = uv;
  27865. this.id = id;
  27866. this.isBorder = true;
  27867. this.q = new QuadraticMatrix();
  27868. this.triangleCount = 0;
  27869. this.triangleStart = 0;
  27870. }
  27871. return DecimationVertex;
  27872. })();
  27873. BABYLON.DecimationVertex = DecimationVertex;
  27874. var QuadraticMatrix = (function () {
  27875. function QuadraticMatrix(data) {
  27876. this.data = new Array(10);
  27877. for (var i = 0; i < 10; ++i) {
  27878. if (data && data[i]) {
  27879. this.data[i] = data[i];
  27880. }
  27881. else {
  27882. this.data[i] = 0;
  27883. }
  27884. }
  27885. }
  27886. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27887. 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];
  27888. return det;
  27889. };
  27890. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27891. for (var i = 0; i < 10; ++i) {
  27892. this.data[i] += matrix.data[i];
  27893. }
  27894. };
  27895. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27896. for (var i = 0; i < 10; ++i) {
  27897. this.data[i] += data[i];
  27898. }
  27899. };
  27900. QuadraticMatrix.prototype.add = function (matrix) {
  27901. var m = new QuadraticMatrix();
  27902. for (var i = 0; i < 10; ++i) {
  27903. m.data[i] = this.data[i] + matrix.data[i];
  27904. }
  27905. return m;
  27906. };
  27907. QuadraticMatrix.FromData = function (a, b, c, d) {
  27908. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27909. };
  27910. //returning an array to avoid garbage collection
  27911. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27912. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27913. };
  27914. return QuadraticMatrix;
  27915. })();
  27916. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27917. var Reference = (function () {
  27918. function Reference(vertexId, triangleId) {
  27919. this.vertexId = vertexId;
  27920. this.triangleId = triangleId;
  27921. }
  27922. return Reference;
  27923. })();
  27924. BABYLON.Reference = Reference;
  27925. /**
  27926. * An implementation of the Quadratic Error simplification algorithm.
  27927. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27928. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27929. * @author RaananW
  27930. */
  27931. var QuadraticErrorSimplification = (function () {
  27932. function QuadraticErrorSimplification(_mesh) {
  27933. this._mesh = _mesh;
  27934. this.initialised = false;
  27935. this.syncIterations = 5000;
  27936. this.aggressiveness = 7;
  27937. this.decimationIterations = 100;
  27938. this.boundingBoxEpsilon = BABYLON.Engine.Epsilon;
  27939. }
  27940. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27941. var _this = this;
  27942. this.initDecimatedMesh();
  27943. //iterating through the submeshes array, one after the other.
  27944. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  27945. _this.initWithMesh(_this._mesh, loop.index, function () {
  27946. _this.runDecimation(settings, loop.index, function () {
  27947. loop.executeNext();
  27948. });
  27949. });
  27950. }, function () {
  27951. setTimeout(function () {
  27952. _this._reconstructedMesh.isVisible = true;
  27953. successCallback(_this._reconstructedMesh);
  27954. }, 0);
  27955. });
  27956. };
  27957. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  27958. var _this = this;
  27959. var gCount = 0;
  27960. triangle.vertices.forEach(function (vId) {
  27961. var count = 0;
  27962. var vPos = _this.vertices[vId].position;
  27963. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  27964. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  27965. ++count;
  27966. if (bbox.maximum.y == vPos.y || vPos.y == bbox.minimum.y)
  27967. ++count;
  27968. if (bbox.maximum.z == vPos.z || vPos.z == bbox.minimum.z)
  27969. ++count;
  27970. if (count > 1) {
  27971. ++gCount;
  27972. }
  27973. ;
  27974. });
  27975. if (gCount > 1) {
  27976. console.log(triangle, gCount);
  27977. }
  27978. return gCount > 1;
  27979. };
  27980. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  27981. var _this = this;
  27982. var targetCount = ~~(this.triangles.length * settings.quality);
  27983. var deletedTriangles = 0;
  27984. var triangleCount = this.triangles.length;
  27985. var iterationFunction = function (iteration, callback) {
  27986. setTimeout(function () {
  27987. if (iteration % 5 === 0) {
  27988. _this.updateMesh(iteration === 0);
  27989. }
  27990. for (var i = 0; i < _this.triangles.length; ++i) {
  27991. _this.triangles[i].isDirty = false;
  27992. }
  27993. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27994. var trianglesIterator = function (i) {
  27995. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27996. var t = _this.triangles[tIdx];
  27997. if (!t)
  27998. return;
  27999. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  28000. return;
  28001. }
  28002. for (var j = 0; j < 3; ++j) {
  28003. if (t.error[j] < threshold) {
  28004. var deleted0 = [];
  28005. var deleted1 = [];
  28006. var i0 = t.vertices[j];
  28007. var i1 = t.vertices[(j + 1) % 3];
  28008. var v0 = _this.vertices[i0];
  28009. var v1 = _this.vertices[i1];
  28010. if (v0.isBorder !== v1.isBorder)
  28011. continue;
  28012. var p = BABYLON.Vector3.Zero();
  28013. var n = BABYLON.Vector3.Zero();
  28014. var uv = BABYLON.Vector2.Zero();
  28015. var color = new BABYLON.Color4(0, 0, 0, 1);
  28016. _this.calculateError(v0, v1, p, n, uv, color);
  28017. var delTr = [];
  28018. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  28019. continue;
  28020. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  28021. continue;
  28022. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  28023. continue;
  28024. }
  28025. v0.normal = n;
  28026. if (v0.uv)
  28027. v0.uv = uv;
  28028. else if (v0.color)
  28029. v0.color = color;
  28030. v0.q = v1.q.add(v0.q);
  28031. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  28032. continue;
  28033. if (p.equals(v0.position))
  28034. continue;
  28035. v0.position = p;
  28036. var tStart = _this.references.length;
  28037. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  28038. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  28039. var tCount = _this.references.length - tStart;
  28040. if (tCount <= v0.triangleCount) {
  28041. if (tCount) {
  28042. for (var c = 0; c < tCount; c++) {
  28043. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  28044. }
  28045. }
  28046. }
  28047. else {
  28048. v0.triangleStart = tStart;
  28049. }
  28050. v0.triangleCount = tCount;
  28051. break;
  28052. }
  28053. }
  28054. };
  28055. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  28056. return (triangleCount - deletedTriangles <= targetCount);
  28057. });
  28058. }, 0);
  28059. };
  28060. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  28061. if (triangleCount - deletedTriangles <= targetCount)
  28062. loop.breakLoop();
  28063. else {
  28064. iterationFunction(loop.index, function () {
  28065. loop.executeNext();
  28066. });
  28067. }
  28068. }, function () {
  28069. setTimeout(function () {
  28070. //reconstruct this part of the mesh
  28071. _this.reconstructMesh(submeshIndex);
  28072. successCallback();
  28073. }, 0);
  28074. });
  28075. };
  28076. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, submeshIndex, callback) {
  28077. var _this = this;
  28078. if (!mesh)
  28079. return;
  28080. this.vertices = [];
  28081. this.triangles = [];
  28082. this._mesh = mesh;
  28083. //It is assumed that a mesh has positions, normals and either uvs or colors.
  28084. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28085. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28086. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  28087. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  28088. var indices = mesh.getIndices();
  28089. var submesh = mesh.subMeshes[submeshIndex];
  28090. var vertexInit = function (i) {
  28091. var offset = i + submesh.verticesStart;
  28092. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, offset * 3), BABYLON.Vector3.FromArray(normalData, offset * 3), null, i);
  28093. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28094. vertex.uv = BABYLON.Vector2.FromArray(uvs, offset * 2);
  28095. }
  28096. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28097. vertex.color = BABYLON.Color4.FromArray(colorsData, offset * 4);
  28098. }
  28099. _this.vertices.push(vertex);
  28100. };
  28101. //var totalVertices = mesh.getTotalVertices();
  28102. var totalVertices = submesh.verticesCount;
  28103. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  28104. var indicesInit = function (i) {
  28105. var offset = (submesh.indexStart / 3) + i;
  28106. var pos = (offset * 3);
  28107. var i0 = indices[pos + 0] - submesh.verticesStart;
  28108. var i1 = indices[pos + 1] - submesh.verticesStart;
  28109. var i2 = indices[pos + 2] - submesh.verticesStart;
  28110. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  28111. _this.triangles.push(triangle);
  28112. };
  28113. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  28114. _this.init(callback);
  28115. });
  28116. });
  28117. };
  28118. QuadraticErrorSimplification.prototype.init = function (callback) {
  28119. var _this = this;
  28120. var triangleInit1 = function (i) {
  28121. var t = _this.triangles[i];
  28122. 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();
  28123. for (var j = 0; j < 3; j++) {
  28124. _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))));
  28125. }
  28126. };
  28127. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  28128. var triangleInit2 = function (i) {
  28129. var t = _this.triangles[i];
  28130. for (var j = 0; j < 3; ++j) {
  28131. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  28132. }
  28133. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28134. };
  28135. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  28136. _this.initialised = true;
  28137. callback();
  28138. });
  28139. });
  28140. };
  28141. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  28142. var newTriangles = [];
  28143. var i;
  28144. for (i = 0; i < this.vertices.length; ++i) {
  28145. this.vertices[i].triangleCount = 0;
  28146. }
  28147. var t;
  28148. var j;
  28149. for (i = 0; i < this.triangles.length; ++i) {
  28150. if (!this.triangles[i].deleted) {
  28151. t = this.triangles[i];
  28152. for (j = 0; j < 3; ++j) {
  28153. this.vertices[t.vertices[j]].triangleCount = 1;
  28154. }
  28155. newTriangles.push(t);
  28156. }
  28157. }
  28158. var newVerticesOrder = [];
  28159. //compact vertices, get the IDs of the vertices used.
  28160. var dst = 0;
  28161. for (i = 0; i < this.vertices.length; ++i) {
  28162. if (this.vertices[i].triangleCount) {
  28163. this.vertices[i].triangleStart = dst;
  28164. this.vertices[dst].position = this.vertices[i].position;
  28165. this.vertices[dst].normal = this.vertices[i].normal;
  28166. this.vertices[dst].uv = this.vertices[i].uv;
  28167. this.vertices[dst].color = this.vertices[i].color;
  28168. newVerticesOrder.push(i);
  28169. dst++;
  28170. }
  28171. }
  28172. for (i = 0; i < newTriangles.length; ++i) {
  28173. t = newTriangles[i];
  28174. for (j = 0; j < 3; ++j) {
  28175. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  28176. }
  28177. }
  28178. this.vertices = this.vertices.slice(0, dst);
  28179. var newPositionData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || [];
  28180. var newNormalData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || [];
  28181. var newUVsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || [];
  28182. var newColorsData = this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || [];
  28183. for (i = 0; i < newVerticesOrder.length; ++i) {
  28184. newPositionData.push(this.vertices[i].position.x);
  28185. newPositionData.push(this.vertices[i].position.y);
  28186. newPositionData.push(this.vertices[i].position.z);
  28187. newNormalData.push(this.vertices[i].normal.x);
  28188. newNormalData.push(this.vertices[i].normal.y);
  28189. newNormalData.push(this.vertices[i].normal.z);
  28190. if (this.vertices[i].uv) {
  28191. newUVsData.push(this.vertices[i].uv.x);
  28192. newUVsData.push(this.vertices[i].uv.y);
  28193. }
  28194. else if (this.vertices[i].color) {
  28195. newColorsData.push(this.vertices[i].color.r);
  28196. newColorsData.push(this.vertices[i].color.g);
  28197. newColorsData.push(this.vertices[i].color.b);
  28198. newColorsData.push(this.vertices[i].color.a);
  28199. }
  28200. }
  28201. var startingIndex = this._reconstructedMesh.getTotalIndices();
  28202. var startingVertex = this._reconstructedMesh.getTotalVertices();
  28203. var submeshesArray = this._reconstructedMesh.subMeshes;
  28204. this._reconstructedMesh.subMeshes = [];
  28205. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  28206. for (i = 0; i < newTriangles.length; ++i) {
  28207. newIndicesArray.push(newTriangles[i].vertices[0] + startingVertex);
  28208. newIndicesArray.push(newTriangles[i].vertices[1] + startingVertex);
  28209. newIndicesArray.push(newTriangles[i].vertices[2] + startingVertex);
  28210. }
  28211. //overwriting the old vertex buffers and indices.
  28212. this._reconstructedMesh.setIndices(newIndicesArray);
  28213. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  28214. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  28215. if (newUVsData.length > 0)
  28216. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  28217. if (newColorsData.length > 0)
  28218. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  28219. //create submesh
  28220. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  28221. if (submeshIndex > 0) {
  28222. this._reconstructedMesh.subMeshes = [];
  28223. submeshesArray.forEach(function (submesh) {
  28224. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, submesh.indexStart, submesh.indexCount, submesh.getMesh());
  28225. });
  28226. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, newVerticesOrder.length, startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  28227. }
  28228. };
  28229. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  28230. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  28231. this._reconstructedMesh.material = this._mesh.material;
  28232. this._reconstructedMesh.parent = this._mesh.parent;
  28233. this._reconstructedMesh.isVisible = false;
  28234. };
  28235. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  28236. for (var i = 0; i < vertex1.triangleCount; ++i) {
  28237. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  28238. if (t.deleted)
  28239. continue;
  28240. var s = this.references[vertex1.triangleStart + i].vertexId;
  28241. var id1 = t.vertices[(s + 1) % 3];
  28242. var id2 = t.vertices[(s + 2) % 3];
  28243. if ((id1 === index2 || id2 === index2)) {
  28244. deletedArray[i] = true;
  28245. delTr.push(t);
  28246. continue;
  28247. }
  28248. var d1 = this.vertices[id1].position.subtract(point);
  28249. d1 = d1.normalize();
  28250. var d2 = this.vertices[id2].position.subtract(point);
  28251. d2 = d2.normalize();
  28252. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  28253. return true;
  28254. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  28255. deletedArray[i] = false;
  28256. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  28257. return true;
  28258. }
  28259. return false;
  28260. };
  28261. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  28262. var newDeleted = deletedTriangles;
  28263. for (var i = 0; i < vertex.triangleCount; ++i) {
  28264. var ref = this.references[vertex.triangleStart + i];
  28265. var t = this.triangles[ref.triangleId];
  28266. if (t.deleted)
  28267. continue;
  28268. if (deletedArray[i]) {
  28269. t.deleted = true;
  28270. newDeleted++;
  28271. continue;
  28272. }
  28273. t.vertices[ref.vertexId] = vertexId;
  28274. t.isDirty = true;
  28275. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  28276. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  28277. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  28278. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  28279. this.references.push(ref);
  28280. }
  28281. return newDeleted;
  28282. };
  28283. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  28284. for (var i = 0; i < this.vertices.length; ++i) {
  28285. var vCount = [];
  28286. var vId = [];
  28287. var v = this.vertices[i];
  28288. var j;
  28289. for (j = 0; j < v.triangleCount; ++j) {
  28290. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  28291. for (var ii = 0; ii < 3; ii++) {
  28292. var ofs = 0;
  28293. var id = triangle.vertices[ii];
  28294. while (ofs < vCount.length) {
  28295. if (vId[ofs] === id)
  28296. break;
  28297. ++ofs;
  28298. }
  28299. if (ofs === vCount.length) {
  28300. vCount.push(1);
  28301. vId.push(id);
  28302. }
  28303. else {
  28304. vCount[ofs]++;
  28305. }
  28306. }
  28307. }
  28308. for (j = 0; j < vCount.length; ++j) {
  28309. if (vCount[j] === 1) {
  28310. this.vertices[vId[j]].isBorder = true;
  28311. }
  28312. else {
  28313. this.vertices[vId[j]].isBorder = false;
  28314. }
  28315. }
  28316. }
  28317. };
  28318. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  28319. if (identifyBorders === void 0) { identifyBorders = false; }
  28320. var i;
  28321. if (!identifyBorders) {
  28322. var newTrianglesVector = [];
  28323. for (i = 0; i < this.triangles.length; ++i) {
  28324. if (!this.triangles[i].deleted) {
  28325. newTrianglesVector.push(this.triangles[i]);
  28326. }
  28327. }
  28328. this.triangles = newTrianglesVector;
  28329. }
  28330. for (i = 0; i < this.vertices.length; ++i) {
  28331. this.vertices[i].triangleCount = 0;
  28332. this.vertices[i].triangleStart = 0;
  28333. }
  28334. var t;
  28335. var j;
  28336. var v;
  28337. for (i = 0; i < this.triangles.length; ++i) {
  28338. t = this.triangles[i];
  28339. for (j = 0; j < 3; ++j) {
  28340. v = this.vertices[t.vertices[j]];
  28341. v.triangleCount++;
  28342. }
  28343. }
  28344. var tStart = 0;
  28345. for (i = 0; i < this.vertices.length; ++i) {
  28346. this.vertices[i].triangleStart = tStart;
  28347. tStart += this.vertices[i].triangleCount;
  28348. this.vertices[i].triangleCount = 0;
  28349. }
  28350. var newReferences = new Array(this.triangles.length * 3);
  28351. for (i = 0; i < this.triangles.length; ++i) {
  28352. t = this.triangles[i];
  28353. for (j = 0; j < 3; ++j) {
  28354. v = this.vertices[t.vertices[j]];
  28355. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  28356. v.triangleCount++;
  28357. }
  28358. }
  28359. this.references = newReferences;
  28360. if (identifyBorders) {
  28361. this.identifyBorder();
  28362. }
  28363. };
  28364. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  28365. var x = point.x;
  28366. var y = point.y;
  28367. var z = point.z;
  28368. 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];
  28369. };
  28370. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  28371. var q = vertex1.q.add(vertex2.q);
  28372. var border = vertex1.isBorder && vertex2.isBorder;
  28373. var error = 0;
  28374. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  28375. if (qDet !== 0 && !border) {
  28376. if (!pointResult) {
  28377. pointResult = BABYLON.Vector3.Zero();
  28378. }
  28379. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  28380. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  28381. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  28382. error = this.vertexError(q, pointResult);
  28383. //TODO this should be correctly calculated
  28384. if (normalResult) {
  28385. normalResult.copyFrom(vertex1.normal);
  28386. if (vertex1.uv)
  28387. uvResult.copyFrom(vertex1.uv);
  28388. else if (vertex1.color)
  28389. colorResult.copyFrom(vertex1.color);
  28390. }
  28391. }
  28392. else {
  28393. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  28394. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  28395. var error1 = this.vertexError(q, vertex1.position);
  28396. var error2 = this.vertexError(q, vertex2.position);
  28397. var error3 = this.vertexError(q, p3);
  28398. error = Math.min(error1, error2, error3);
  28399. if (error === error1) {
  28400. if (pointResult) {
  28401. pointResult.copyFrom(vertex1.position);
  28402. normalResult.copyFrom(vertex1.normal);
  28403. if (vertex1.uv)
  28404. uvResult.copyFrom(vertex1.uv);
  28405. else if (vertex1.color)
  28406. colorResult.copyFrom(vertex1.color);
  28407. }
  28408. }
  28409. else if (error === error2) {
  28410. if (pointResult) {
  28411. pointResult.copyFrom(vertex2.position);
  28412. normalResult.copyFrom(vertex2.normal);
  28413. if (vertex2.uv)
  28414. uvResult.copyFrom(vertex2.uv);
  28415. else if (vertex2.color)
  28416. colorResult.copyFrom(vertex2.color);
  28417. }
  28418. }
  28419. else {
  28420. if (pointResult) {
  28421. pointResult.copyFrom(p3);
  28422. normalResult.copyFrom(vertex1.normal);
  28423. if (vertex1.uv)
  28424. uvResult.copyFrom(vertex1.uv);
  28425. else if (vertex1.color)
  28426. colorResult.copyFrom(vertex1.color);
  28427. }
  28428. }
  28429. }
  28430. return error;
  28431. };
  28432. return QuadraticErrorSimplification;
  28433. })();
  28434. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28435. })(BABYLON || (BABYLON = {}));
  28436. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28437. (function (BABYLON) {
  28438. var Analyser = (function () {
  28439. function Analyser(scene) {
  28440. this.SMOOTHING = 0.75;
  28441. this.FFT_SIZE = 512;
  28442. this.BARGRAPHAMPLITUDE = 256;
  28443. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28444. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28445. this._scene = scene;
  28446. this._audioEngine = BABYLON.Engine.audioEngine;
  28447. if (this._audioEngine.canUseWebAudio) {
  28448. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28449. this._webAudioAnalyser.minDecibels = -140;
  28450. this._webAudioAnalyser.maxDecibels = 0;
  28451. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28452. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28453. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28454. }
  28455. }
  28456. Analyser.prototype.getFrequencyBinCount = function () {
  28457. if (this._audioEngine.canUseWebAudio) {
  28458. return this._webAudioAnalyser.frequencyBinCount;
  28459. }
  28460. else {
  28461. return 0;
  28462. }
  28463. };
  28464. Analyser.prototype.getByteFrequencyData = function () {
  28465. if (this._audioEngine.canUseWebAudio) {
  28466. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28467. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28468. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28469. }
  28470. return this._byteFreqs;
  28471. };
  28472. Analyser.prototype.getByteTimeDomainData = function () {
  28473. if (this._audioEngine.canUseWebAudio) {
  28474. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28475. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28476. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28477. }
  28478. return this._byteTime;
  28479. };
  28480. Analyser.prototype.getFloatFrequencyData = function () {
  28481. if (this._audioEngine.canUseWebAudio) {
  28482. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28483. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28484. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28485. }
  28486. return this._floatFreqs;
  28487. };
  28488. Analyser.prototype.drawDebugCanvas = function () {
  28489. var _this = this;
  28490. if (this._audioEngine.canUseWebAudio) {
  28491. if (!this._debugCanvas) {
  28492. this._debugCanvas = document.createElement("canvas");
  28493. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28494. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28495. this._debugCanvas.style.position = "absolute";
  28496. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28497. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28498. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28499. document.body.appendChild(this._debugCanvas);
  28500. this._registerFunc = function () {
  28501. _this.drawDebugCanvas();
  28502. };
  28503. this._scene.registerBeforeRender(this._registerFunc);
  28504. }
  28505. if (this._registerFunc) {
  28506. var workingArray = this.getByteFrequencyData();
  28507. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28508. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28509. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28510. var value = workingArray[i];
  28511. var percent = value / this.BARGRAPHAMPLITUDE;
  28512. var height = this.DEBUGCANVASSIZE.height * percent;
  28513. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28514. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28515. var hue = i / this.getFrequencyBinCount() * 360;
  28516. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28517. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28518. }
  28519. }
  28520. }
  28521. };
  28522. Analyser.prototype.stopDebugCanvas = function () {
  28523. if (this._debugCanvas) {
  28524. this._scene.unregisterBeforeRender(this._registerFunc);
  28525. this._registerFunc = null;
  28526. document.body.removeChild(this._debugCanvas);
  28527. this._debugCanvas = null;
  28528. this._debugCanvasContext = null;
  28529. }
  28530. };
  28531. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28532. if (this._audioEngine.canUseWebAudio) {
  28533. inputAudioNode.connect(this._webAudioAnalyser);
  28534. this._webAudioAnalyser.connect(outputAudioNode);
  28535. }
  28536. };
  28537. Analyser.prototype.dispose = function () {
  28538. if (this._audioEngine.canUseWebAudio) {
  28539. this._webAudioAnalyser.disconnect();
  28540. }
  28541. };
  28542. return Analyser;
  28543. })();
  28544. BABYLON.Analyser = Analyser;
  28545. })(BABYLON || (BABYLON = {}));
  28546. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28547. (function (BABYLON) {
  28548. var DepthRenderer = (function () {
  28549. function DepthRenderer(scene, type) {
  28550. var _this = this;
  28551. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28552. this._viewMatrix = BABYLON.Matrix.Zero();
  28553. this._projectionMatrix = BABYLON.Matrix.Zero();
  28554. this._transformMatrix = BABYLON.Matrix.Zero();
  28555. this._worldViewProjection = BABYLON.Matrix.Zero();
  28556. this._scene = scene;
  28557. var engine = scene.getEngine();
  28558. // Render target
  28559. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28560. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28561. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28562. this._depthMap.refreshRate = 1;
  28563. this._depthMap.renderParticles = false;
  28564. this._depthMap.renderList = null;
  28565. // Custom render function
  28566. var renderSubMesh = function (subMesh) {
  28567. var mesh = subMesh.getRenderingMesh();
  28568. var scene = _this._scene;
  28569. var engine = scene.getEngine();
  28570. // Culling
  28571. engine.setState(subMesh.getMaterial().backFaceCulling);
  28572. // Managing instances
  28573. var batch = mesh._getInstancesRenderList(subMesh._id);
  28574. if (batch.mustReturn) {
  28575. return;
  28576. }
  28577. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28578. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28579. engine.enableEffect(_this._effect);
  28580. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28581. var material = subMesh.getMaterial();
  28582. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28583. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28584. // Alpha test
  28585. if (material && material.needAlphaTesting()) {
  28586. var alphaTexture = material.getAlphaTestTexture();
  28587. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28588. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28589. }
  28590. // Bones
  28591. if (mesh.useBones) {
  28592. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28593. }
  28594. // Draw
  28595. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28596. }
  28597. };
  28598. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28599. var index;
  28600. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28601. renderSubMesh(opaqueSubMeshes.data[index]);
  28602. }
  28603. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28604. renderSubMesh(alphaTestSubMeshes.data[index]);
  28605. }
  28606. };
  28607. }
  28608. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28609. var defines = [];
  28610. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28611. var mesh = subMesh.getMesh();
  28612. var scene = mesh.getScene();
  28613. var material = subMesh.getMaterial();
  28614. // Alpha test
  28615. if (material && material.needAlphaTesting()) {
  28616. defines.push("#define ALPHATEST");
  28617. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28618. attribs.push(BABYLON.VertexBuffer.UVKind);
  28619. defines.push("#define UV1");
  28620. }
  28621. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28622. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28623. defines.push("#define UV2");
  28624. }
  28625. }
  28626. // Bones
  28627. if (mesh.useBones) {
  28628. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28629. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28630. defines.push("#define BONES");
  28631. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28632. }
  28633. // Instances
  28634. if (useInstances) {
  28635. defines.push("#define INSTANCES");
  28636. attribs.push("world0");
  28637. attribs.push("world1");
  28638. attribs.push("world2");
  28639. attribs.push("world3");
  28640. }
  28641. // Get correct effect
  28642. var join = defines.join("\n");
  28643. if (this._cachedDefines !== join) {
  28644. this._cachedDefines = join;
  28645. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28646. }
  28647. return this._effect.isReady();
  28648. };
  28649. DepthRenderer.prototype.getDepthMap = function () {
  28650. return this._depthMap;
  28651. };
  28652. // Methods
  28653. DepthRenderer.prototype.dispose = function () {
  28654. this._depthMap.dispose();
  28655. };
  28656. return DepthRenderer;
  28657. })();
  28658. BABYLON.DepthRenderer = DepthRenderer;
  28659. })(BABYLON || (BABYLON = {}));
  28660. //# sourceMappingURL=babylon.depthRenderer.js.map
  28661. var BABYLON;
  28662. (function (BABYLON) {
  28663. var SSAORenderingPipeline = (function (_super) {
  28664. __extends(SSAORenderingPipeline, _super);
  28665. /**
  28666. * @constructor
  28667. * @param {string} name - The rendering pipeline name
  28668. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28669. * @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)
  28670. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28671. */
  28672. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28673. var _this = this;
  28674. _super.call(this, scene.getEngine(), name);
  28675. // Members
  28676. /**
  28677. * The PassPostProcess id in the pipeline that contains the original scene color
  28678. * @type {string}
  28679. */
  28680. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28681. /**
  28682. * The SSAO PostProcess id in the pipeline
  28683. * @type {string}
  28684. */
  28685. this.SSAORenderEffect = "SSAORenderEffect";
  28686. /**
  28687. * The horizontal blur PostProcess id in the pipeline
  28688. * @type {string}
  28689. */
  28690. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28691. /**
  28692. * The vertical blur PostProcess id in the pipeline
  28693. * @type {string}
  28694. */
  28695. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28696. /**
  28697. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28698. * @type {string}
  28699. */
  28700. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28701. this._firstUpdate = true;
  28702. this._scene = scene;
  28703. // Set up assets
  28704. this._createRandomTexture();
  28705. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28706. var ssaoRatio = ratio.ssaoRatio || ratio;
  28707. var combineRatio = ratio.combineRatio || ratio;
  28708. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28709. this._createSSAOPostProcess(ssaoRatio);
  28710. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28711. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28712. this._createSSAOCombinePostProcess(combineRatio);
  28713. // Set up pipeline
  28714. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28715. return _this._originalColorPostProcess;
  28716. }, true));
  28717. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28718. return _this._ssaoPostProcess;
  28719. }, true));
  28720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28721. return _this._blurHPostProcess;
  28722. }, true));
  28723. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28724. return _this._blurVPostProcess;
  28725. }, true));
  28726. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28727. return _this._ssaoCombinePostProcess;
  28728. }, true));
  28729. // Finish
  28730. scene.postProcessRenderPipelineManager.addPipeline(this);
  28731. if (cameras)
  28732. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28733. }
  28734. // Public Methods
  28735. /**
  28736. * Returns the horizontal blur PostProcess
  28737. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28738. */
  28739. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28740. return this._blurHPostProcess;
  28741. };
  28742. /**
  28743. * Returns the vertical blur PostProcess
  28744. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28745. */
  28746. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28747. return this._blurVPostProcess;
  28748. };
  28749. /**
  28750. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28751. */
  28752. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28753. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28754. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28755. this._originalColorPostProcess = undefined;
  28756. this._ssaoPostProcess = undefined;
  28757. this._blurHPostProcess = undefined;
  28758. this._blurVPostProcess = undefined;
  28759. this._ssaoCombinePostProcess = undefined;
  28760. this._randomTexture.dispose();
  28761. if (disableDepthRender)
  28762. this._scene.disableDepthRenderer();
  28763. };
  28764. // Private Methods
  28765. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28766. var _this = this;
  28767. var sampleSphere = [
  28768. 0.5381,
  28769. 0.1856,
  28770. -0.4319,
  28771. 0.1379,
  28772. 0.2486,
  28773. 0.4430,
  28774. 0.3371,
  28775. 0.5679,
  28776. -0.0057,
  28777. -0.6999,
  28778. -0.0451,
  28779. -0.0019,
  28780. 0.0689,
  28781. -0.1598,
  28782. -0.8547,
  28783. 0.0560,
  28784. 0.0069,
  28785. -0.1843,
  28786. -0.0146,
  28787. 0.1402,
  28788. 0.0762,
  28789. 0.0100,
  28790. -0.1924,
  28791. -0.0344,
  28792. -0.3577,
  28793. -0.5301,
  28794. -0.4358,
  28795. -0.3169,
  28796. 0.1063,
  28797. 0.0158,
  28798. 0.0103,
  28799. -0.5869,
  28800. 0.0046,
  28801. -0.0897,
  28802. -0.4940,
  28803. 0.3287,
  28804. 0.7119,
  28805. -0.0154,
  28806. -0.0918,
  28807. -0.0533,
  28808. 0.0596,
  28809. -0.5411,
  28810. 0.0352,
  28811. -0.0631,
  28812. 0.5460,
  28813. -0.4776,
  28814. 0.2847,
  28815. -0.0271
  28816. ];
  28817. var samplesFactor = 1.0 / 16.0;
  28818. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28819. this._ssaoPostProcess.onApply = function (effect) {
  28820. if (_this._firstUpdate) {
  28821. effect.setArray3("sampleSphere", sampleSphere);
  28822. effect.setFloat("samplesFactor", samplesFactor);
  28823. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28824. _this._firstUpdate = false;
  28825. }
  28826. effect.setTexture("textureSampler", _this._depthTexture);
  28827. effect.setTexture("randomSampler", _this._randomTexture);
  28828. };
  28829. };
  28830. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28831. var _this = this;
  28832. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28833. this._ssaoCombinePostProcess.onApply = function (effect) {
  28834. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28835. };
  28836. };
  28837. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28838. var size = 512;
  28839. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28840. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28841. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28842. var context = this._randomTexture.getContext();
  28843. var rand = function (min, max) {
  28844. return Math.random() * (max - min) + min;
  28845. };
  28846. for (var x = 0; x < size; x++) {
  28847. for (var y = 0; y < size; y++) {
  28848. var randVector = BABYLON.Vector3.Zero();
  28849. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28850. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28851. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28852. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28853. context.fillRect(x, y, 1, 1);
  28854. }
  28855. }
  28856. this._randomTexture.update(false);
  28857. };
  28858. return SSAORenderingPipeline;
  28859. })(BABYLON.PostProcessRenderPipeline);
  28860. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28861. })(BABYLON || (BABYLON = {}));
  28862. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28863. var BABYLON;
  28864. (function (BABYLON) {
  28865. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28866. var VolumetricLightScatteringPostProcess = (function (_super) {
  28867. __extends(VolumetricLightScatteringPostProcess, _super);
  28868. /**
  28869. * @constructor
  28870. * @param {string} name - The post-process name
  28871. * @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)
  28872. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28873. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28874. * @param {number} samples - The post-process quality, default 100
  28875. * @param {number} samplingMode - The post-process filtering mode
  28876. * @param {BABYLON.Engine} engine - The babylon engine
  28877. * @param {boolean} reusable - If the post-process is reusable
  28878. */
  28879. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28880. var _this = this;
  28881. if (samples === void 0) { samples = 100; }
  28882. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28883. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28884. this._screenCoordinates = BABYLON.Vector2.Zero();
  28885. /**
  28886. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28887. * @type {boolean}
  28888. */
  28889. this.useCustomMeshPosition = false;
  28890. /**
  28891. * If the post-process should inverse the light scattering direction
  28892. * @type {boolean}
  28893. */
  28894. this.invert = true;
  28895. /**
  28896. * Array containing the excluded meshes not rendered in the internal pass
  28897. */
  28898. this.excludedMeshes = new Array();
  28899. this.exposure = 0.3;
  28900. this.decay = 0.96815;
  28901. this.weight = 0.58767;
  28902. this.density = 0.926;
  28903. var scene = camera.getScene();
  28904. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28905. // Configure mesh
  28906. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28907. // Configure
  28908. this._createPass(scene, ratio.passRatio || ratio);
  28909. this.onApply = function (effect) {
  28910. _this._updateMeshScreenCoordinates(scene);
  28911. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28912. effect.setFloat("exposure", _this.exposure);
  28913. effect.setFloat("decay", _this.decay);
  28914. effect.setFloat("weight", _this.weight);
  28915. effect.setFloat("density", _this.density);
  28916. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28917. };
  28918. }
  28919. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28920. var mesh = subMesh.getMesh();
  28921. var defines = [];
  28922. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28923. var material = subMesh.getMaterial();
  28924. // Render this.mesh as default
  28925. if (mesh === this.mesh) {
  28926. defines.push("#define BASIC_RENDER");
  28927. }
  28928. // Alpha test
  28929. if (material) {
  28930. if (material.needAlphaTesting() || mesh === this.mesh)
  28931. defines.push("#define ALPHATEST");
  28932. if (material.opacityTexture !== undefined && mesh === this.mesh)
  28933. defines.push("#define OPACITY");
  28934. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28935. attribs.push(BABYLON.VertexBuffer.UVKind);
  28936. defines.push("#define UV1");
  28937. }
  28938. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28939. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28940. defines.push("#define UV2");
  28941. }
  28942. }
  28943. // Bones
  28944. if (mesh.useBones) {
  28945. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28946. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28947. defines.push("#define BONES");
  28948. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28949. }
  28950. // Instances
  28951. if (useInstances) {
  28952. defines.push("#define INSTANCES");
  28953. attribs.push("world0");
  28954. attribs.push("world1");
  28955. attribs.push("world2");
  28956. attribs.push("world3");
  28957. }
  28958. // Get correct effect
  28959. var join = defines.join("\n");
  28960. if (this._cachedDefines !== join) {
  28961. this._cachedDefines = join;
  28962. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler", "opacitySampler"], join);
  28963. }
  28964. return this._volumetricLightScatteringPass.isReady();
  28965. };
  28966. /**
  28967. * Sets the new light position for light scattering effect
  28968. * @param {BABYLON.Vector3} The new custom light position
  28969. */
  28970. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28971. this._customMeshPosition = position;
  28972. };
  28973. /**
  28974. * Returns the light position for light scattering effect
  28975. * @return {BABYLON.Vector3} The custom light position
  28976. */
  28977. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28978. return this._customMeshPosition;
  28979. };
  28980. /**
  28981. * Disposes the internal assets and detaches the post-process from the camera
  28982. */
  28983. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28984. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28985. if (rttIndex !== -1) {
  28986. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28987. }
  28988. this._volumetricLightScatteringRTT.dispose();
  28989. _super.prototype.dispose.call(this, camera);
  28990. };
  28991. /**
  28992. * Returns the render target texture used by the post-process
  28993. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28994. */
  28995. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28996. return this._volumetricLightScatteringRTT;
  28997. };
  28998. // Private methods
  28999. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  29000. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  29001. return true;
  29002. }
  29003. return false;
  29004. };
  29005. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  29006. var _this = this;
  29007. var engine = scene.getEngine();
  29008. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  29009. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29010. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29011. this._volumetricLightScatteringRTT.renderList = null;
  29012. this._volumetricLightScatteringRTT.renderParticles = false;
  29013. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  29014. // Custom render function for submeshes
  29015. var renderSubMesh = function (subMesh) {
  29016. var mesh = subMesh.getRenderingMesh();
  29017. if (_this._meshExcluded(mesh)) {
  29018. return;
  29019. }
  29020. var scene = mesh.getScene();
  29021. var engine = scene.getEngine();
  29022. // Culling
  29023. engine.setState(subMesh.getMaterial().backFaceCulling);
  29024. // Managing instances
  29025. var batch = mesh._getInstancesRenderList(subMesh._id);
  29026. if (batch.mustReturn) {
  29027. return;
  29028. }
  29029. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  29030. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  29031. engine.enableEffect(_this._volumetricLightScatteringPass);
  29032. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  29033. var material = subMesh.getMaterial();
  29034. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  29035. // Alpha test
  29036. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  29037. var alphaTexture = material.getAlphaTestTexture();
  29038. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  29039. if (alphaTexture) {
  29040. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  29041. }
  29042. if (material.opacityTexture !== undefined)
  29043. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  29044. }
  29045. // Bones
  29046. if (mesh.useBones) {
  29047. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  29048. }
  29049. // Draw
  29050. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  29051. }
  29052. };
  29053. // Render target texture callbacks
  29054. var savedSceneClearColor;
  29055. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  29056. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  29057. savedSceneClearColor = scene.clearColor;
  29058. scene.clearColor = sceneClearColor;
  29059. };
  29060. this._volumetricLightScatteringRTT.onAfterRender = function () {
  29061. scene.clearColor = savedSceneClearColor;
  29062. };
  29063. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  29064. var index;
  29065. for (index = 0; index < opaqueSubMeshes.length; index++) {
  29066. renderSubMesh(opaqueSubMeshes.data[index]);
  29067. }
  29068. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  29069. renderSubMesh(alphaTestSubMeshes.data[index]);
  29070. }
  29071. for (index = 0; index < transparentSubMeshes.length; index++) {
  29072. renderSubMesh(transparentSubMeshes.data[index]);
  29073. }
  29074. };
  29075. };
  29076. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  29077. var transform = scene.getTransformMatrix();
  29078. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  29079. this._screenCoordinates.x = pos.x / this._viewPort.width;
  29080. this._screenCoordinates.y = pos.y / this._viewPort.height;
  29081. if (this.invert)
  29082. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  29083. };
  29084. // Static methods
  29085. /**
  29086. * Creates a default mesh for the Volumeric Light Scattering post-process
  29087. * @param {string} The mesh name
  29088. * @param {BABYLON.Scene} The scene where to create the mesh
  29089. * @return {BABYLON.Mesh} the default mesh
  29090. */
  29091. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  29092. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  29093. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  29094. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  29095. return mesh;
  29096. };
  29097. return VolumetricLightScatteringPostProcess;
  29098. })(BABYLON.PostProcess);
  29099. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  29100. })(BABYLON || (BABYLON = {}));
  29101. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  29102. var BABYLON;
  29103. (function (BABYLON) {
  29104. var LensRenderingPipeline = (function (_super) {
  29105. __extends(LensRenderingPipeline, _super);
  29106. /**
  29107. * @constructor
  29108. * @param {string} name - The rendering pipeline name
  29109. * @param {object} parameters - An object containing all parameters (see below)
  29110. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  29111. * @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)
  29112. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  29113. Effect parameters are as follow:
  29114. {
  29115. chromatic_aberration: number; // from 0 to x (1 for realism)
  29116. edge_blur: number; // from 0 to x (1 for realism)
  29117. distortion: number; // from 0 to x (1 for realism)
  29118. grain_amount: number; // from 0 to 1
  29119. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  29120. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  29121. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  29122. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  29123. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  29124. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  29125. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  29126. }
  29127. Note: if an effect parameter is unset, effect is disabled
  29128. */
  29129. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  29130. var _this = this;
  29131. if (ratio === void 0) { ratio = 1.0; }
  29132. _super.call(this, scene.getEngine(), name);
  29133. // Lens effects can be of the following:
  29134. // - chromatic aberration (slight shift of RGB colors)
  29135. // - blur on the edge of the lens
  29136. // - lens distortion
  29137. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  29138. // - grain/dust-on-lens effect
  29139. // Two additional texture samplers are needed:
  29140. // - depth map (for depth-of-field)
  29141. // - grain texture
  29142. /**
  29143. * The chromatic aberration PostProcess id in the pipeline
  29144. * @type {string}
  29145. */
  29146. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  29147. /**
  29148. * The depth-of-field PostProcess id in the pipeline
  29149. * @type {string}
  29150. */
  29151. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  29152. this._scene = scene;
  29153. // Fetch texture samplers
  29154. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  29155. if (parameters.grain_texture) {
  29156. this._grainTexture = parameters.grain_texture;
  29157. }
  29158. else {
  29159. this._createGrainTexture();
  29160. }
  29161. // save parameters
  29162. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  29163. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  29164. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  29165. this._distortion = parameters.distortion ? parameters.distortion : 0;
  29166. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  29167. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  29168. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  29169. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  29170. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  29171. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  29172. // Create effects
  29173. this._createChromaticAberrationPostProcess(ratio);
  29174. this._createDepthOfFieldPostProcess(ratio);
  29175. // Set up pipeline
  29176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  29177. return _this._chromaticAberrationPostProcess;
  29178. }, true));
  29179. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  29180. return _this._depthOfFieldPostProcess;
  29181. }, true));
  29182. // Finish
  29183. scene.postProcessRenderPipelineManager.addPipeline(this);
  29184. if (cameras) {
  29185. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  29186. }
  29187. }
  29188. // public methods
  29189. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  29190. this._edgeBlur = amount;
  29191. };
  29192. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  29193. this._edgeBlur = 0;
  29194. };
  29195. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  29196. this._grainAmount = amount;
  29197. };
  29198. LensRenderingPipeline.prototype.disableGrain = function () {
  29199. this._grainAmount = 0;
  29200. };
  29201. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  29202. this._chromaticAberration = amount;
  29203. };
  29204. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  29205. this._chromaticAberration = 0;
  29206. };
  29207. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  29208. this._distortion = amount;
  29209. };
  29210. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  29211. this._distortion = 0;
  29212. };
  29213. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  29214. this._highlightsGain = amount;
  29215. };
  29216. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  29217. this._highlightsThreshold = amount;
  29218. };
  29219. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  29220. this._dofDepth = amount;
  29221. };
  29222. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  29223. this._dofDepth = -1;
  29224. };
  29225. LensRenderingPipeline.prototype.setAperture = function (amount) {
  29226. this._dofAperture = amount;
  29227. };
  29228. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  29229. this._dofPentagon = true;
  29230. };
  29231. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  29232. this._dofPentagon = false;
  29233. };
  29234. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  29235. this._blurNoise = true;
  29236. };
  29237. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  29238. this._blurNoise = false;
  29239. };
  29240. /**
  29241. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  29242. */
  29243. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  29244. if (disableDepthRender === void 0) { disableDepthRender = false; }
  29245. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  29246. this._chromaticAberrationPostProcess = undefined;
  29247. this._depthOfFieldPostProcess = undefined;
  29248. this._grainTexture.dispose();
  29249. if (disableDepthRender)
  29250. this._scene.disableDepthRenderer();
  29251. };
  29252. // colors shifting and distortion
  29253. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  29254. var _this = this;
  29255. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29256. this._chromaticAberrationPostProcess.onApply = function (effect) {
  29257. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  29258. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29259. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29260. };
  29261. };
  29262. // colors shifting and distortion
  29263. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  29264. var _this = this;
  29265. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  29266. "gain",
  29267. "threshold",
  29268. "focus_depth",
  29269. "aperture",
  29270. "pentagon",
  29271. "maxZ",
  29272. "edge_blur",
  29273. "chromatic_aberration",
  29274. "distortion",
  29275. "blur_noise",
  29276. "grain_amount",
  29277. "screen_width",
  29278. "screen_height"
  29279. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  29280. this._depthOfFieldPostProcess.onApply = function (effect) {
  29281. effect.setBool('pentagon', _this._dofPentagon);
  29282. effect.setBool('blur_noise', _this._blurNoise);
  29283. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  29284. effect.setFloat('grain_amount', _this._grainAmount);
  29285. effect.setTexture("depthSampler", _this._depthTexture);
  29286. effect.setTexture("grainSampler", _this._grainTexture);
  29287. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  29288. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  29289. effect.setFloat('distortion', _this._distortion);
  29290. effect.setFloat('focus_depth', _this._dofDepth);
  29291. effect.setFloat('aperture', _this._dofAperture);
  29292. effect.setFloat('gain', _this._highlightsGain);
  29293. effect.setFloat('threshold', _this._highlightsThreshold);
  29294. effect.setFloat('edge_blur', _this._edgeBlur);
  29295. };
  29296. };
  29297. // creates a black and white random noise texture, 512x512
  29298. LensRenderingPipeline.prototype._createGrainTexture = function () {
  29299. var size = 512;
  29300. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  29301. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  29302. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  29303. var context = this._grainTexture.getContext();
  29304. var rand = function (min, max) {
  29305. return Math.random() * (max - min) + min;
  29306. };
  29307. var value;
  29308. for (var x = 0; x < size; x++) {
  29309. for (var y = 0; y < size; y++) {
  29310. value = Math.floor(rand(0.42, 0.58) * 255);
  29311. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  29312. context.fillRect(x, y, 1, 1);
  29313. }
  29314. }
  29315. this._grainTexture.update(false);
  29316. };
  29317. return LensRenderingPipeline;
  29318. })(BABYLON.PostProcessRenderPipeline);
  29319. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  29320. })(BABYLON || (BABYLON = {}));
  29321. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map//
  29322. // This post-process allows the modification of rendered colors by using
  29323. // a 'look-up table' (LUT). This effect is also called Color Grading.
  29324. //
  29325. // The object needs to be provided an url to a texture containing the color
  29326. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  29327. // Use an image editing software to tweak the LUT to match your needs.
  29328. //
  29329. // For an example of a color LUT, see here:
  29330. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  29331. // For explanations on color grading, see here:
  29332. // http://udn.epicgames.com/Three/ColorGrading.html
  29333. //
  29334. var BABYLON;
  29335. (function (BABYLON) {
  29336. var ColorCorrectionPostProcess = (function (_super) {
  29337. __extends(ColorCorrectionPostProcess, _super);
  29338. function ColorCorrectionPostProcess(name, colorTableUrl, ratio, camera, samplingMode, engine, reusable) {
  29339. var _this = this;
  29340. _super.call(this, name, 'colorCorrection', null, ['colorTable'], ratio, camera, samplingMode, engine, reusable);
  29341. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  29342. this._colorTableTexture.anisotropicFilteringLevel = 1;
  29343. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29344. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29345. this.onApply = function (effect) {
  29346. effect.setTexture("colorTable", _this._colorTableTexture);
  29347. };
  29348. }
  29349. return ColorCorrectionPostProcess;
  29350. })(BABYLON.PostProcess);
  29351. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  29352. })(BABYLON || (BABYLON = {}));
  29353. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map