babylon.2.1-alpha.debug.js 1.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918
  1. var __extends = this.__extends || function (d, b) {
  2. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  3. function __() { this.constructor = d; }
  4. __.prototype = b.prototype;
  5. d.prototype = new __();
  6. };var BABYLON;
  7. (function (BABYLON) {
  8. var Color3 = (function () {
  9. function Color3(r, g, b) {
  10. if (r === void 0) { r = 0; }
  11. if (g === void 0) { g = 0; }
  12. if (b === void 0) { b = 0; }
  13. this.r = r;
  14. this.g = g;
  15. this.b = b;
  16. }
  17. Color3.prototype.toString = function () {
  18. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  19. };
  20. // Operators
  21. Color3.prototype.toArray = function (array, index) {
  22. if (index === undefined) {
  23. index = 0;
  24. }
  25. array[index] = this.r;
  26. array[index + 1] = this.g;
  27. array[index + 2] = this.b;
  28. return this;
  29. };
  30. Color3.prototype.toColor4 = function (alpha) {
  31. if (alpha === void 0) { alpha = 1; }
  32. return new Color4(this.r, this.g, this.b, alpha);
  33. };
  34. Color3.prototype.asArray = function () {
  35. var result = [];
  36. this.toArray(result, 0);
  37. return result;
  38. };
  39. Color3.prototype.toLuminance = function () {
  40. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  41. };
  42. Color3.prototype.multiply = function (otherColor) {
  43. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  44. };
  45. Color3.prototype.multiplyToRef = function (otherColor, result) {
  46. result.r = this.r * otherColor.r;
  47. result.g = this.g * otherColor.g;
  48. result.b = this.b * otherColor.b;
  49. return this;
  50. };
  51. Color3.prototype.equals = function (otherColor) {
  52. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  53. };
  54. Color3.prototype.scale = function (scale) {
  55. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  56. };
  57. Color3.prototype.scaleToRef = function (scale, result) {
  58. result.r = this.r * scale;
  59. result.g = this.g * scale;
  60. result.b = this.b * scale;
  61. return this;
  62. };
  63. Color3.prototype.add = function (otherColor) {
  64. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  65. };
  66. Color3.prototype.addToRef = function (otherColor, result) {
  67. result.r = this.r + otherColor.r;
  68. result.g = this.g + otherColor.g;
  69. result.b = this.b + otherColor.b;
  70. return this;
  71. };
  72. Color3.prototype.subtract = function (otherColor) {
  73. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  74. };
  75. Color3.prototype.subtractToRef = function (otherColor, result) {
  76. result.r = this.r - otherColor.r;
  77. result.g = this.g - otherColor.g;
  78. result.b = this.b - otherColor.b;
  79. return this;
  80. };
  81. Color3.prototype.clone = function () {
  82. return new Color3(this.r, this.g, this.b);
  83. };
  84. Color3.prototype.copyFrom = function (source) {
  85. this.r = source.r;
  86. this.g = source.g;
  87. this.b = source.b;
  88. return this;
  89. };
  90. Color3.prototype.copyFromFloats = function (r, g, b) {
  91. this.r = r;
  92. this.g = g;
  93. this.b = b;
  94. return this;
  95. };
  96. // Statics
  97. Color3.FromArray = function (array, offset) {
  98. if (offset === void 0) { offset = 0; }
  99. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  100. };
  101. Color3.FromInts = function (r, g, b) {
  102. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  103. };
  104. Color3.Lerp = function (start, end, amount) {
  105. var r = start.r + ((end.r - start.r) * amount);
  106. var g = start.g + ((end.g - start.g) * amount);
  107. var b = start.b + ((end.b - start.b) * amount);
  108. return new Color3(r, g, b);
  109. };
  110. Color3.Red = function () {
  111. return new Color3(1, 0, 0);
  112. };
  113. Color3.Green = function () {
  114. return new Color3(0, 1, 0);
  115. };
  116. Color3.Blue = function () {
  117. return new Color3(0, 0, 1);
  118. };
  119. Color3.Black = function () {
  120. return new Color3(0, 0, 0);
  121. };
  122. Color3.White = function () {
  123. return new Color3(1, 1, 1);
  124. };
  125. Color3.Purple = function () {
  126. return new Color3(0.5, 0, 0.5);
  127. };
  128. Color3.Magenta = function () {
  129. return new Color3(1, 0, 1);
  130. };
  131. Color3.Yellow = function () {
  132. return new Color3(1, 1, 0);
  133. };
  134. Color3.Gray = function () {
  135. return new Color3(0.5, 0.5, 0.5);
  136. };
  137. return Color3;
  138. })();
  139. BABYLON.Color3 = Color3;
  140. var Color4 = (function () {
  141. function Color4(r, g, b, a) {
  142. this.r = r;
  143. this.g = g;
  144. this.b = b;
  145. this.a = a;
  146. }
  147. // Operators
  148. Color4.prototype.addInPlace = function (right) {
  149. this.r += right.r;
  150. this.g += right.g;
  151. this.b += right.b;
  152. this.a += right.a;
  153. return this;
  154. };
  155. Color4.prototype.asArray = function () {
  156. var result = [];
  157. this.toArray(result, 0);
  158. return result;
  159. };
  160. Color4.prototype.toArray = function (array, index) {
  161. if (index === undefined) {
  162. index = 0;
  163. }
  164. array[index] = this.r;
  165. array[index + 1] = this.g;
  166. array[index + 2] = this.b;
  167. array[index + 3] = this.a;
  168. return this;
  169. };
  170. Color4.prototype.add = function (right) {
  171. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  172. };
  173. Color4.prototype.subtract = function (right) {
  174. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  175. };
  176. Color4.prototype.subtractToRef = function (right, result) {
  177. result.r = this.r - right.r;
  178. result.g = this.g - right.g;
  179. result.b = this.b - right.b;
  180. result.a = this.a - right.a;
  181. return this;
  182. };
  183. Color4.prototype.scale = function (scale) {
  184. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  185. };
  186. Color4.prototype.scaleToRef = function (scale, result) {
  187. result.r = this.r * scale;
  188. result.g = this.g * scale;
  189. result.b = this.b * scale;
  190. result.a = this.a * scale;
  191. return this;
  192. };
  193. Color4.prototype.toString = function () {
  194. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  195. };
  196. Color4.prototype.clone = function () {
  197. return new Color4(this.r, this.g, this.b, this.a);
  198. };
  199. Color4.prototype.copyFrom = function (source) {
  200. this.r = source.r;
  201. this.g = source.g;
  202. this.b = source.b;
  203. this.a = source.a;
  204. return this;
  205. };
  206. // Statics
  207. Color4.Lerp = function (left, right, amount) {
  208. var result = new Color4(0, 0, 0, 0);
  209. Color4.LerpToRef(left, right, amount, result);
  210. return result;
  211. };
  212. Color4.LerpToRef = function (left, right, amount, result) {
  213. result.r = left.r + (right.r - left.r) * amount;
  214. result.g = left.g + (right.g - left.g) * amount;
  215. result.b = left.b + (right.b - left.b) * amount;
  216. result.a = left.a + (right.a - left.a) * amount;
  217. };
  218. Color4.FromArray = function (array, offset) {
  219. if (offset === void 0) { offset = 0; }
  220. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  221. };
  222. Color4.FromInts = function (r, g, b, a) {
  223. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  224. };
  225. return Color4;
  226. })();
  227. BABYLON.Color4 = Color4;
  228. var Vector2 = (function () {
  229. function Vector2(x, y) {
  230. this.x = x;
  231. this.y = y;
  232. }
  233. Vector2.prototype.toString = function () {
  234. return "{X: " + this.x + " Y:" + this.y + "}";
  235. };
  236. // Operators
  237. Vector2.prototype.toArray = function (array, index) {
  238. if (index === void 0) { index = 0; }
  239. array[index] = this.x;
  240. array[index + 1] = this.y;
  241. return this;
  242. };
  243. Vector2.prototype.asArray = function () {
  244. var result = [];
  245. this.toArray(result, 0);
  246. return result;
  247. };
  248. Vector2.prototype.copyFrom = function (source) {
  249. this.x = source.x;
  250. this.y = source.y;
  251. return this;
  252. };
  253. Vector2.prototype.copyFromFloats = function (x, y) {
  254. this.x = x;
  255. this.y = y;
  256. return this;
  257. };
  258. Vector2.prototype.add = function (otherVector) {
  259. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  260. };
  261. Vector2.prototype.addVector3 = function (otherVector) {
  262. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  263. };
  264. Vector2.prototype.subtract = function (otherVector) {
  265. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  266. };
  267. Vector2.prototype.subtractInPlace = function (otherVector) {
  268. this.x -= otherVector.x;
  269. this.y -= otherVector.y;
  270. return this;
  271. };
  272. Vector2.prototype.multiplyInPlace = function (otherVector) {
  273. this.x *= otherVector.x;
  274. this.y *= otherVector.y;
  275. return this;
  276. };
  277. Vector2.prototype.multiply = function (otherVector) {
  278. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  279. };
  280. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  281. result.x = this.x * otherVector.x;
  282. result.y = this.y * otherVector.y;
  283. return this;
  284. };
  285. Vector2.prototype.multiplyByFloats = function (x, y) {
  286. return new Vector2(this.x * x, this.y * y);
  287. };
  288. Vector2.prototype.divide = function (otherVector) {
  289. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  290. };
  291. Vector2.prototype.divideToRef = function (otherVector, result) {
  292. result.x = this.x / otherVector.x;
  293. result.y = this.y / otherVector.y;
  294. return this;
  295. };
  296. Vector2.prototype.negate = function () {
  297. return new Vector2(-this.x, -this.y);
  298. };
  299. Vector2.prototype.scaleInPlace = function (scale) {
  300. this.x *= scale;
  301. this.y *= scale;
  302. return this;
  303. };
  304. Vector2.prototype.scale = function (scale) {
  305. return new Vector2(this.x * scale, this.y * scale);
  306. };
  307. Vector2.prototype.equals = function (otherVector) {
  308. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  309. };
  310. // Properties
  311. Vector2.prototype.length = function () {
  312. return Math.sqrt(this.x * this.x + this.y * this.y);
  313. };
  314. Vector2.prototype.lengthSquared = function () {
  315. return (this.x * this.x + this.y * this.y);
  316. };
  317. // Methods
  318. Vector2.prototype.normalize = function () {
  319. var len = this.length();
  320. if (len === 0)
  321. return this;
  322. var num = 1.0 / len;
  323. this.x *= num;
  324. this.y *= num;
  325. return this;
  326. };
  327. Vector2.prototype.clone = function () {
  328. return new Vector2(this.x, this.y);
  329. };
  330. // Statics
  331. Vector2.Zero = function () {
  332. return new Vector2(0, 0);
  333. };
  334. Vector2.FromArray = function (array, offset) {
  335. if (offset === void 0) { offset = 0; }
  336. return new Vector2(array[offset], array[offset + 1]);
  337. };
  338. Vector2.FromArrayToRef = function (array, offset, result) {
  339. result.x = array[offset];
  340. result.y = array[offset + 1];
  341. };
  342. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  343. var squared = amount * amount;
  344. var cubed = amount * squared;
  345. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  346. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  347. return new Vector2(x, y);
  348. };
  349. Vector2.Clamp = function (value, min, max) {
  350. var x = value.x;
  351. x = (x > max.x) ? max.x : x;
  352. x = (x < min.x) ? min.x : x;
  353. var y = value.y;
  354. y = (y > max.y) ? max.y : y;
  355. y = (y < min.y) ? min.y : y;
  356. return new Vector2(x, y);
  357. };
  358. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  359. var squared = amount * amount;
  360. var cubed = amount * squared;
  361. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  362. var part2 = (-2.0 * cubed) + (3.0 * squared);
  363. var part3 = (cubed - (2.0 * squared)) + amount;
  364. var part4 = cubed - squared;
  365. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  366. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  367. return new Vector2(x, y);
  368. };
  369. Vector2.Lerp = function (start, end, amount) {
  370. var x = start.x + ((end.x - start.x) * amount);
  371. var y = start.y + ((end.y - start.y) * amount);
  372. return new Vector2(x, y);
  373. };
  374. Vector2.Dot = function (left, right) {
  375. return left.x * right.x + left.y * right.y;
  376. };
  377. Vector2.Normalize = function (vector) {
  378. var newVector = vector.clone();
  379. newVector.normalize();
  380. return newVector;
  381. };
  382. Vector2.Minimize = function (left, right) {
  383. var x = (left.x < right.x) ? left.x : right.x;
  384. var y = (left.y < right.y) ? left.y : right.y;
  385. return new Vector2(x, y);
  386. };
  387. Vector2.Maximize = function (left, right) {
  388. var x = (left.x > right.x) ? left.x : right.x;
  389. var y = (left.y > right.y) ? left.y : right.y;
  390. return new Vector2(x, y);
  391. };
  392. Vector2.Transform = function (vector, transformation) {
  393. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]);
  394. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]);
  395. return new Vector2(x, y);
  396. };
  397. Vector2.Distance = function (value1, value2) {
  398. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  399. };
  400. Vector2.DistanceSquared = function (value1, value2) {
  401. var x = value1.x - value2.x;
  402. var y = value1.y - value2.y;
  403. return (x * x) + (y * y);
  404. };
  405. return Vector2;
  406. })();
  407. BABYLON.Vector2 = Vector2;
  408. var Vector3 = (function () {
  409. function Vector3(x, y, z) {
  410. this.x = x;
  411. this.y = y;
  412. this.z = z;
  413. }
  414. Vector3.prototype.toString = function () {
  415. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  416. };
  417. // Operators
  418. Vector3.prototype.asArray = function () {
  419. var result = [];
  420. this.toArray(result, 0);
  421. return result;
  422. };
  423. Vector3.prototype.toArray = function (array, index) {
  424. if (index === void 0) { index = 0; }
  425. array[index] = this.x;
  426. array[index + 1] = this.y;
  427. array[index + 2] = this.z;
  428. return this;
  429. };
  430. Vector3.prototype.toQuaternion = function () {
  431. var result = new Quaternion(0, 0, 0, 1);
  432. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  433. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  434. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  435. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  436. var cosy = Math.cos(this.y * 0.5);
  437. var siny = Math.sin(this.y * 0.5);
  438. result.x = coszMinusx * siny;
  439. result.y = -sinzMinusx * siny;
  440. result.z = sinxPlusz * cosy;
  441. result.w = cosxPlusz * cosy;
  442. return result;
  443. };
  444. Vector3.prototype.addInPlace = function (otherVector) {
  445. this.x += otherVector.x;
  446. this.y += otherVector.y;
  447. this.z += otherVector.z;
  448. return this;
  449. };
  450. Vector3.prototype.add = function (otherVector) {
  451. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  452. };
  453. Vector3.prototype.addToRef = function (otherVector, result) {
  454. result.x = this.x + otherVector.x;
  455. result.y = this.y + otherVector.y;
  456. result.z = this.z + otherVector.z;
  457. return this;
  458. };
  459. Vector3.prototype.subtractInPlace = function (otherVector) {
  460. this.x -= otherVector.x;
  461. this.y -= otherVector.y;
  462. this.z -= otherVector.z;
  463. return this;
  464. };
  465. Vector3.prototype.subtract = function (otherVector) {
  466. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  467. };
  468. Vector3.prototype.subtractToRef = function (otherVector, result) {
  469. result.x = this.x - otherVector.x;
  470. result.y = this.y - otherVector.y;
  471. result.z = this.z - otherVector.z;
  472. return this;
  473. };
  474. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  475. return new Vector3(this.x - x, this.y - y, this.z - z);
  476. };
  477. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  478. result.x = this.x - x;
  479. result.y = this.y - y;
  480. result.z = this.z - z;
  481. return this;
  482. };
  483. Vector3.prototype.negate = function () {
  484. return new Vector3(-this.x, -this.y, -this.z);
  485. };
  486. Vector3.prototype.scaleInPlace = function (scale) {
  487. this.x *= scale;
  488. this.y *= scale;
  489. this.z *= scale;
  490. return this;
  491. };
  492. Vector3.prototype.scale = function (scale) {
  493. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  494. };
  495. Vector3.prototype.scaleToRef = function (scale, result) {
  496. result.x = this.x * scale;
  497. result.y = this.y * scale;
  498. result.z = this.z * scale;
  499. };
  500. Vector3.prototype.equals = function (otherVector) {
  501. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  502. };
  503. Vector3.prototype.equalsWithEpsilon = function (otherVector) {
  504. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon;
  505. };
  506. Vector3.prototype.equalsToFloats = function (x, y, z) {
  507. return this.x === x && this.y === y && this.z === z;
  508. };
  509. Vector3.prototype.multiplyInPlace = function (otherVector) {
  510. this.x *= otherVector.x;
  511. this.y *= otherVector.y;
  512. this.z *= otherVector.z;
  513. return this;
  514. };
  515. Vector3.prototype.multiply = function (otherVector) {
  516. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  517. };
  518. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  519. result.x = this.x * otherVector.x;
  520. result.y = this.y * otherVector.y;
  521. result.z = this.z * otherVector.z;
  522. return this;
  523. };
  524. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  525. return new Vector3(this.x * x, this.y * y, this.z * z);
  526. };
  527. Vector3.prototype.divide = function (otherVector) {
  528. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  529. };
  530. Vector3.prototype.divideToRef = function (otherVector, result) {
  531. result.x = this.x / otherVector.x;
  532. result.y = this.y / otherVector.y;
  533. result.z = this.z / otherVector.z;
  534. return this;
  535. };
  536. Vector3.prototype.MinimizeInPlace = function (other) {
  537. if (other.x < this.x)
  538. this.x = other.x;
  539. if (other.y < this.y)
  540. this.y = other.y;
  541. if (other.z < this.z)
  542. this.z = other.z;
  543. return this;
  544. };
  545. Vector3.prototype.MaximizeInPlace = function (other) {
  546. if (other.x > this.x)
  547. this.x = other.x;
  548. if (other.y > this.y)
  549. this.y = other.y;
  550. if (other.z > this.z)
  551. this.z = other.z;
  552. return this;
  553. };
  554. // Properties
  555. Vector3.prototype.length = function () {
  556. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  557. };
  558. Vector3.prototype.lengthSquared = function () {
  559. return (this.x * this.x + this.y * this.y + this.z * this.z);
  560. };
  561. // Methods
  562. Vector3.prototype.normalize = function () {
  563. var len = this.length();
  564. if (len === 0)
  565. return this;
  566. var num = 1.0 / len;
  567. this.x *= num;
  568. this.y *= num;
  569. this.z *= num;
  570. return this;
  571. };
  572. Vector3.prototype.clone = function () {
  573. return new Vector3(this.x, this.y, this.z);
  574. };
  575. Vector3.prototype.copyFrom = function (source) {
  576. this.x = source.x;
  577. this.y = source.y;
  578. this.z = source.z;
  579. return this;
  580. };
  581. Vector3.prototype.copyFromFloats = function (x, y, z) {
  582. this.x = x;
  583. this.y = y;
  584. this.z = z;
  585. return this;
  586. };
  587. // Statics
  588. Vector3.FromArray = function (array, offset) {
  589. if (!offset) {
  590. offset = 0;
  591. }
  592. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  593. };
  594. Vector3.FromArrayToRef = function (array, offset, result) {
  595. result.x = array[offset];
  596. result.y = array[offset + 1];
  597. result.z = array[offset + 2];
  598. };
  599. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  600. result.x = array[offset];
  601. result.y = array[offset + 1];
  602. result.z = array[offset + 2];
  603. };
  604. Vector3.FromFloatsToRef = function (x, y, z, result) {
  605. result.x = x;
  606. result.y = y;
  607. result.z = z;
  608. };
  609. Vector3.Zero = function () {
  610. return new Vector3(0, 0, 0);
  611. };
  612. Vector3.Up = function () {
  613. return new Vector3(0, 1.0, 0);
  614. };
  615. Vector3.TransformCoordinates = function (vector, transformation) {
  616. var result = Vector3.Zero();
  617. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  618. return result;
  619. };
  620. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  621. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  622. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  623. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  624. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  625. result.x = x / w;
  626. result.y = y / w;
  627. result.z = z / w;
  628. };
  629. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  630. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  631. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  632. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  633. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  634. result.x = rx / rw;
  635. result.y = ry / rw;
  636. result.z = rz / rw;
  637. };
  638. Vector3.TransformNormal = function (vector, transformation) {
  639. var result = Vector3.Zero();
  640. Vector3.TransformNormalToRef(vector, transformation, result);
  641. return result;
  642. };
  643. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  644. result.x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  645. result.y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  646. result.z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  647. };
  648. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  649. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  650. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  651. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  652. };
  653. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  654. var squared = amount * amount;
  655. var cubed = amount * squared;
  656. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) + (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) + ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  657. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) + (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) + ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  658. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) + (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) + ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  659. return new Vector3(x, y, z);
  660. };
  661. Vector3.Clamp = function (value, min, max) {
  662. var x = value.x;
  663. x = (x > max.x) ? max.x : x;
  664. x = (x < min.x) ? min.x : x;
  665. var y = value.y;
  666. y = (y > max.y) ? max.y : y;
  667. y = (y < min.y) ? min.y : y;
  668. var z = value.z;
  669. z = (z > max.z) ? max.z : z;
  670. z = (z < min.z) ? min.z : z;
  671. return new Vector3(x, y, z);
  672. };
  673. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  674. var squared = amount * amount;
  675. var cubed = amount * squared;
  676. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  677. var part2 = (-2.0 * cubed) + (3.0 * squared);
  678. var part3 = (cubed - (2.0 * squared)) + amount;
  679. var part4 = cubed - squared;
  680. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  681. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  682. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  683. return new Vector3(x, y, z);
  684. };
  685. Vector3.Lerp = function (start, end, amount) {
  686. var x = start.x + ((end.x - start.x) * amount);
  687. var y = start.y + ((end.y - start.y) * amount);
  688. var z = start.z + ((end.z - start.z) * amount);
  689. return new Vector3(x, y, z);
  690. };
  691. Vector3.Dot = function (left, right) {
  692. return (left.x * right.x + left.y * right.y + left.z * right.z);
  693. };
  694. Vector3.Cross = function (left, right) {
  695. var result = Vector3.Zero();
  696. Vector3.CrossToRef(left, right, result);
  697. return result;
  698. };
  699. Vector3.CrossToRef = function (left, right, result) {
  700. result.x = left.y * right.z - left.z * right.y;
  701. result.y = left.z * right.x - left.x * right.z;
  702. result.z = left.x * right.y - left.y * right.x;
  703. };
  704. Vector3.Normalize = function (vector) {
  705. var result = Vector3.Zero();
  706. Vector3.NormalizeToRef(vector, result);
  707. return result;
  708. };
  709. Vector3.NormalizeToRef = function (vector, result) {
  710. result.copyFrom(vector);
  711. result.normalize();
  712. };
  713. Vector3.Project = function (vector, world, transform, viewport) {
  714. var cw = viewport.width;
  715. var ch = viewport.height;
  716. var cx = viewport.x;
  717. var cy = viewport.y;
  718. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 1, 0, cx + cw / 2.0, ch / 2.0 + cy, 0, 1);
  719. var finalMatrix = world.multiply(transform).multiply(viewportMatrix);
  720. return Vector3.TransformCoordinates(vector, finalMatrix);
  721. };
  722. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  723. var matrix = world.multiply(transform);
  724. matrix.invert();
  725. source.x = source.x / viewportWidth * 2 - 1;
  726. source.y = -(source.y / viewportHeight * 2 - 1);
  727. var vector = Vector3.TransformCoordinates(source, matrix);
  728. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  729. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  730. vector = vector.scale(1.0 / num);
  731. }
  732. return vector;
  733. };
  734. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  735. var matrix = world.multiply(view).multiply(projection);
  736. matrix.invert();
  737. source.x = source.x / viewportWidth * 2 - 1;
  738. source.y = -(source.y / viewportHeight * 2 - 1);
  739. var vector = Vector3.TransformCoordinates(source, matrix);
  740. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  741. if (BABYLON.Tools.WithinEpsilon(num, 1.0)) {
  742. vector = vector.scale(1.0 / num);
  743. }
  744. return vector;
  745. };
  746. Vector3.Minimize = function (left, right) {
  747. var min = left.clone();
  748. min.MinimizeInPlace(right);
  749. return min;
  750. };
  751. Vector3.Maximize = function (left, right) {
  752. var max = left.clone();
  753. max.MaximizeInPlace(right);
  754. return max;
  755. };
  756. Vector3.Distance = function (value1, value2) {
  757. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  758. };
  759. Vector3.DistanceSquared = function (value1, value2) {
  760. var x = value1.x - value2.x;
  761. var y = value1.y - value2.y;
  762. var z = value1.z - value2.z;
  763. return (x * x) + (y * y) + (z * z);
  764. };
  765. Vector3.Center = function (value1, value2) {
  766. var center = value1.add(value2);
  767. center.scaleInPlace(0.5);
  768. return center;
  769. };
  770. return Vector3;
  771. })();
  772. BABYLON.Vector3 = Vector3;
  773. //Vector4 class created for EulerAngle class conversion to Quaternion
  774. var Vector4 = (function () {
  775. function Vector4(x, y, z, w) {
  776. this.x = x;
  777. this.y = y;
  778. this.z = z;
  779. this.w = w;
  780. }
  781. Vector4.prototype.toString = function () {
  782. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "W:" + this.w + "}";
  783. };
  784. // Operators
  785. Vector4.prototype.asArray = function () {
  786. var result = [];
  787. this.toArray(result, 0);
  788. return result;
  789. };
  790. Vector4.prototype.toArray = function (array, index) {
  791. if (index === undefined) {
  792. index = 0;
  793. }
  794. array[index] = this.x;
  795. array[index + 1] = this.y;
  796. array[index + 2] = this.z;
  797. array[index + 3] = this.w;
  798. return this;
  799. };
  800. Vector4.prototype.addInPlace = function (otherVector) {
  801. this.x += otherVector.x;
  802. this.y += otherVector.y;
  803. this.z += otherVector.z;
  804. this.w += otherVector.w;
  805. return this;
  806. };
  807. Vector4.prototype.add = function (otherVector) {
  808. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  809. };
  810. Vector4.prototype.addToRef = function (otherVector, result) {
  811. result.x = this.x + otherVector.x;
  812. result.y = this.y + otherVector.y;
  813. result.z = this.z + otherVector.z;
  814. result.w = this.w + otherVector.w;
  815. return this;
  816. };
  817. Vector4.prototype.subtractInPlace = function (otherVector) {
  818. this.x -= otherVector.x;
  819. this.y -= otherVector.y;
  820. this.z -= otherVector.z;
  821. this.w -= otherVector.w;
  822. return this;
  823. };
  824. Vector4.prototype.subtract = function (otherVector) {
  825. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  826. };
  827. Vector4.prototype.subtractToRef = function (otherVector, result) {
  828. result.x = this.x - otherVector.x;
  829. result.y = this.y - otherVector.y;
  830. result.z = this.z - otherVector.z;
  831. result.w = this.w - otherVector.w;
  832. return this;
  833. };
  834. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  835. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  836. };
  837. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  838. result.x = this.x - x;
  839. result.y = this.y - y;
  840. result.z = this.z - z;
  841. result.w = this.w - w;
  842. return this;
  843. };
  844. Vector4.prototype.negate = function () {
  845. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  846. };
  847. Vector4.prototype.scaleInPlace = function (scale) {
  848. this.x *= scale;
  849. this.y *= scale;
  850. this.z *= scale;
  851. this.w *= scale;
  852. return this;
  853. };
  854. Vector4.prototype.scale = function (scale) {
  855. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  856. };
  857. Vector4.prototype.scaleToRef = function (scale, result) {
  858. result.x = this.x * scale;
  859. result.y = this.y * scale;
  860. result.z = this.z * scale;
  861. result.w = this.w * scale;
  862. };
  863. Vector4.prototype.equals = function (otherVector) {
  864. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  865. };
  866. Vector4.prototype.equalsWithEpsilon = function (otherVector) {
  867. return Math.abs(this.x - otherVector.x) < BABYLON.Engine.Epsilon && Math.abs(this.y - otherVector.y) < BABYLON.Engine.Epsilon && Math.abs(this.z - otherVector.z) < BABYLON.Engine.Epsilon && Math.abs(this.w - otherVector.w) < BABYLON.Engine.Epsilon;
  868. };
  869. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  870. return this.x === x && this.y === y && this.z === z && this.w === w;
  871. };
  872. Vector4.prototype.multiplyInPlace = function (otherVector) {
  873. this.x *= otherVector.x;
  874. this.y *= otherVector.y;
  875. this.z *= otherVector.z;
  876. this.w *= otherVector.w;
  877. return this;
  878. };
  879. Vector4.prototype.multiply = function (otherVector) {
  880. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  881. };
  882. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  883. result.x = this.x * otherVector.x;
  884. result.y = this.y * otherVector.y;
  885. result.z = this.z * otherVector.z;
  886. result.w = this.w * otherVector.w;
  887. return this;
  888. };
  889. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  890. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  891. };
  892. Vector4.prototype.divide = function (otherVector) {
  893. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  894. };
  895. Vector4.prototype.divideToRef = function (otherVector, result) {
  896. result.x = this.x / otherVector.x;
  897. result.y = this.y / otherVector.y;
  898. result.z = this.z / otherVector.z;
  899. result.w = this.w / otherVector.w;
  900. return this;
  901. };
  902. Vector4.prototype.MinimizeInPlace = function (other) {
  903. if (other.x < this.x)
  904. this.x = other.x;
  905. if (other.y < this.y)
  906. this.y = other.y;
  907. if (other.z < this.z)
  908. this.z = other.z;
  909. if (other.w < this.w)
  910. this.w = other.w;
  911. return this;
  912. };
  913. Vector4.prototype.MaximizeInPlace = function (other) {
  914. if (other.x > this.x)
  915. this.x = other.x;
  916. if (other.y > this.y)
  917. this.y = other.y;
  918. if (other.z > this.z)
  919. this.z = other.z;
  920. if (other.w > this.w)
  921. this.w = other.w;
  922. return this;
  923. };
  924. // Properties
  925. Vector4.prototype.length = function () {
  926. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  927. };
  928. Vector4.prototype.lengthSquared = function () {
  929. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  930. };
  931. // Methods
  932. Vector4.prototype.normalize = function () {
  933. var len = this.length();
  934. if (len === 0)
  935. return this;
  936. var num = 1.0 / len;
  937. this.x *= num;
  938. this.y *= num;
  939. this.z *= num;
  940. this.w *= num;
  941. return this;
  942. };
  943. Vector4.prototype.clone = function () {
  944. return new Vector4(this.x, this.y, this.z, this.w);
  945. };
  946. Vector4.prototype.copyFrom = function (source) {
  947. this.x = source.x;
  948. this.y = source.y;
  949. this.z = source.z;
  950. this.w = source.w;
  951. return this;
  952. };
  953. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  954. this.x = x;
  955. this.y = y;
  956. this.z = z;
  957. this.w = w;
  958. return this;
  959. };
  960. // Statics
  961. Vector4.FromArray = function (array, offset) {
  962. if (!offset) {
  963. offset = 0;
  964. }
  965. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  966. };
  967. Vector4.FromArrayToRef = function (array, offset, result) {
  968. result.x = array[offset];
  969. result.y = array[offset + 1];
  970. result.z = array[offset + 2];
  971. result.w = array[offset + 3];
  972. };
  973. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  974. result.x = array[offset];
  975. result.y = array[offset + 1];
  976. result.z = array[offset + 2];
  977. result.w = array[offset + 3];
  978. };
  979. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  980. result.x = x;
  981. result.y = y;
  982. result.z = z;
  983. result.w = w;
  984. };
  985. Vector4.Zero = function () {
  986. return new Vector4(0, 0, 0, 0);
  987. };
  988. Vector4.Normalize = function (vector) {
  989. var result = Vector4.Zero();
  990. Vector4.NormalizeToRef(vector, result);
  991. return result;
  992. };
  993. Vector4.NormalizeToRef = function (vector, result) {
  994. result.copyFrom(vector);
  995. result.normalize();
  996. };
  997. Vector4.Minimize = function (left, right) {
  998. var min = left.clone();
  999. min.MinimizeInPlace(right);
  1000. return min;
  1001. };
  1002. Vector4.Maximize = function (left, right) {
  1003. var max = left.clone();
  1004. max.MaximizeInPlace(right);
  1005. return max;
  1006. };
  1007. Vector4.Distance = function (value1, value2) {
  1008. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1009. };
  1010. Vector4.DistanceSquared = function (value1, value2) {
  1011. var x = value1.x - value2.x;
  1012. var y = value1.y - value2.y;
  1013. var z = value1.z - value2.z;
  1014. var w = value1.w - value2.w;
  1015. return (x * x) + (y * y) + (z * z) + (w * w);
  1016. };
  1017. Vector4.Center = function (value1, value2) {
  1018. var center = value1.add(value2);
  1019. center.scaleInPlace(0.5);
  1020. return center;
  1021. };
  1022. return Vector4;
  1023. })();
  1024. BABYLON.Vector4 = Vector4;
  1025. var Quaternion = (function () {
  1026. function Quaternion(x, y, z, w) {
  1027. if (x === void 0) { x = 0; }
  1028. if (y === void 0) { y = 0; }
  1029. if (z === void 0) { z = 0; }
  1030. if (w === void 0) { w = 1; }
  1031. this.x = x;
  1032. this.y = y;
  1033. this.z = z;
  1034. this.w = w;
  1035. }
  1036. Quaternion.prototype.toString = function () {
  1037. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1038. };
  1039. Quaternion.prototype.asArray = function () {
  1040. return [this.x, this.y, this.z, this.w];
  1041. };
  1042. Quaternion.prototype.equals = function (otherQuaternion) {
  1043. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1044. };
  1045. Quaternion.prototype.clone = function () {
  1046. return new Quaternion(this.x, this.y, this.z, this.w);
  1047. };
  1048. Quaternion.prototype.copyFrom = function (other) {
  1049. this.x = other.x;
  1050. this.y = other.y;
  1051. this.z = other.z;
  1052. this.w = other.w;
  1053. return this;
  1054. };
  1055. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1056. this.x = x;
  1057. this.y = y;
  1058. this.z = z;
  1059. this.w = w;
  1060. return this;
  1061. };
  1062. Quaternion.prototype.add = function (other) {
  1063. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1064. };
  1065. Quaternion.prototype.subtract = function (other) {
  1066. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1067. };
  1068. Quaternion.prototype.scale = function (value) {
  1069. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1070. };
  1071. Quaternion.prototype.multiply = function (q1) {
  1072. var result = new Quaternion(0, 0, 0, 1.0);
  1073. this.multiplyToRef(q1, result);
  1074. return result;
  1075. };
  1076. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1077. result.x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1078. result.y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1079. result.z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1080. result.w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1081. return this;
  1082. };
  1083. Quaternion.prototype.length = function () {
  1084. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1085. };
  1086. Quaternion.prototype.normalize = function () {
  1087. var length = 1.0 / this.length();
  1088. this.x *= length;
  1089. this.y *= length;
  1090. this.z *= length;
  1091. this.w *= length;
  1092. return this;
  1093. };
  1094. Quaternion.prototype.toEulerAngles = function () {
  1095. var result = Vector3.Zero();
  1096. this.toEulerAnglesToRef(result);
  1097. return result;
  1098. };
  1099. Quaternion.prototype.toEulerAnglesToRef = function (result) {
  1100. //result is an EulerAngles in the in the z-x-z convention
  1101. var qx = this.x;
  1102. var qy = this.y;
  1103. var qz = this.z;
  1104. var qw = this.w;
  1105. var qxy = qx * qy;
  1106. var qxz = qx * qz;
  1107. var qwy = qw * qy;
  1108. var qwz = qw * qz;
  1109. var qwx = qw * qx;
  1110. var qyz = qy * qz;
  1111. var sqx = qx * qx;
  1112. var sqy = qy * qy;
  1113. var determinant = sqx + sqy;
  1114. if (determinant !== 0.000 && determinant !== 1.000) {
  1115. result.x = Math.atan2(qxz + qwy, qwx - qyz);
  1116. result.y = Math.acos(1 - 2 * determinant);
  1117. result.z = Math.atan2(qxz - qwy, qwx + qyz);
  1118. }
  1119. else {
  1120. if (determinant === 0.0) {
  1121. result.x = 0.0;
  1122. result.y = 0.0;
  1123. result.z = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x+z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1124. }
  1125. else {
  1126. result.x = Math.atan2(qxy - qwz, 0.5 - sqy - qz * qz); //actually, degeneracy gives us choice with x-z=Math.atan2(qxy-qwz,0.5-sqy-qz*qz)
  1127. result.y = Math.PI;
  1128. result.z = 0.0;
  1129. }
  1130. }
  1131. return this;
  1132. };
  1133. Quaternion.prototype.toRotationMatrix = function (result) {
  1134. var xx = this.x * this.x;
  1135. var yy = this.y * this.y;
  1136. var zz = this.z * this.z;
  1137. var xy = this.x * this.y;
  1138. var zw = this.z * this.w;
  1139. var zx = this.z * this.x;
  1140. var yw = this.y * this.w;
  1141. var yz = this.y * this.z;
  1142. var xw = this.x * this.w;
  1143. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1144. result.m[1] = 2.0 * (xy + zw);
  1145. result.m[2] = 2.0 * (zx - yw);
  1146. result.m[3] = 0;
  1147. result.m[4] = 2.0 * (xy - zw);
  1148. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1149. result.m[6] = 2.0 * (yz + xw);
  1150. result.m[7] = 0;
  1151. result.m[8] = 2.0 * (zx + yw);
  1152. result.m[9] = 2.0 * (yz - xw);
  1153. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1154. result.m[11] = 0;
  1155. result.m[12] = 0;
  1156. result.m[13] = 0;
  1157. result.m[14] = 0;
  1158. result.m[15] = 1.0;
  1159. return this;
  1160. };
  1161. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1162. Quaternion.FromRotationMatrixToRef(matrix, this);
  1163. return this;
  1164. };
  1165. // Statics
  1166. Quaternion.FromRotationMatrix = function (matrix) {
  1167. var result = new Quaternion();
  1168. Quaternion.FromRotationMatrixToRef(matrix, result);
  1169. return result;
  1170. };
  1171. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1172. var data = matrix.m;
  1173. var m11 = data[0], m12 = data[4], m13 = data[8];
  1174. var m21 = data[1], m22 = data[5], m23 = data[9];
  1175. var m31 = data[2], m32 = data[6], m33 = data[10];
  1176. var trace = m11 + m22 + m33;
  1177. var s;
  1178. if (trace > 0) {
  1179. s = 0.5 / Math.sqrt(trace + 1.0);
  1180. result.w = 0.25 / s;
  1181. result.x = (m32 - m23) * s;
  1182. result.y = (m13 - m31) * s;
  1183. result.z = (m21 - m12) * s;
  1184. }
  1185. else if (m11 > m22 && m11 > m33) {
  1186. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1187. result.w = (m32 - m23) / s;
  1188. result.x = 0.25 * s;
  1189. result.y = (m12 + m21) / s;
  1190. result.z = (m13 + m31) / s;
  1191. }
  1192. else if (m22 > m33) {
  1193. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1194. result.w = (m13 - m31) / s;
  1195. result.x = (m12 + m21) / s;
  1196. result.y = 0.25 * s;
  1197. result.z = (m23 + m32) / s;
  1198. }
  1199. else {
  1200. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1201. result.w = (m21 - m12) / s;
  1202. result.x = (m13 + m31) / s;
  1203. result.y = (m23 + m32) / s;
  1204. result.z = 0.25 * s;
  1205. }
  1206. };
  1207. Quaternion.Inverse = function (q) {
  1208. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1209. };
  1210. Quaternion.Identity = function () {
  1211. return new Quaternion(0, 0, 0, 1);
  1212. };
  1213. Quaternion.RotationAxis = function (axis, angle) {
  1214. var result = new Quaternion();
  1215. var sin = Math.sin(angle / 2);
  1216. result.w = Math.cos(angle / 2);
  1217. result.x = axis.x * sin;
  1218. result.y = axis.y * sin;
  1219. result.z = axis.z * sin;
  1220. return result;
  1221. };
  1222. Quaternion.FromArray = function (array, offset) {
  1223. if (!offset) {
  1224. offset = 0;
  1225. }
  1226. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1227. };
  1228. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1229. var result = new Quaternion();
  1230. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1231. return result;
  1232. };
  1233. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1234. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1235. var halfRoll = roll * 0.5;
  1236. var halfPitch = pitch * 0.5;
  1237. var halfYaw = yaw * 0.5;
  1238. var sinRoll = Math.sin(halfRoll);
  1239. var cosRoll = Math.cos(halfRoll);
  1240. var sinPitch = Math.sin(halfPitch);
  1241. var cosPitch = Math.cos(halfPitch);
  1242. var sinYaw = Math.sin(halfYaw);
  1243. var cosYaw = Math.cos(halfYaw);
  1244. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1245. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1246. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1247. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1248. };
  1249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1250. var result = new Quaternion();
  1251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1252. return result;
  1253. };
  1254. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1255. // Produces a quaternion from Euler angles in the z-x-z orientation
  1256. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1257. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1258. var halfBeta = beta * 0.5;
  1259. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1260. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1261. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1262. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1263. };
  1264. Quaternion.Slerp = function (left, right, amount) {
  1265. var num2;
  1266. var num3;
  1267. var num = amount;
  1268. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1269. var flag = false;
  1270. if (num4 < 0) {
  1271. flag = true;
  1272. num4 = -num4;
  1273. }
  1274. if (num4 > 0.999999) {
  1275. num3 = 1 - num;
  1276. num2 = flag ? -num : num;
  1277. }
  1278. else {
  1279. var num5 = Math.acos(num4);
  1280. var num6 = (1.0 / Math.sin(num5));
  1281. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1282. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1283. }
  1284. return new Quaternion((num3 * left.x) + (num2 * right.x), (num3 * left.y) + (num2 * right.y), (num3 * left.z) + (num2 * right.z), (num3 * left.w) + (num2 * right.w));
  1285. };
  1286. return Quaternion;
  1287. })();
  1288. BABYLON.Quaternion = Quaternion;
  1289. var Matrix = (function () {
  1290. function Matrix() {
  1291. this.m = new Float32Array(16);
  1292. }
  1293. // Properties
  1294. Matrix.prototype.isIdentity = function () {
  1295. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1296. return false;
  1297. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 || this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 || this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 || this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1298. return false;
  1299. return true;
  1300. };
  1301. Matrix.prototype.determinant = function () {
  1302. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1303. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1304. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1305. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1306. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1307. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1308. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) - (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) - (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1309. };
  1310. // Methods
  1311. Matrix.prototype.toArray = function () {
  1312. return this.m;
  1313. };
  1314. Matrix.prototype.asArray = function () {
  1315. return this.toArray();
  1316. };
  1317. Matrix.prototype.invert = function () {
  1318. this.invertToRef(this);
  1319. return this;
  1320. };
  1321. Matrix.prototype.invertToRef = function (other) {
  1322. var l1 = this.m[0];
  1323. var l2 = this.m[1];
  1324. var l3 = this.m[2];
  1325. var l4 = this.m[3];
  1326. var l5 = this.m[4];
  1327. var l6 = this.m[5];
  1328. var l7 = this.m[6];
  1329. var l8 = this.m[7];
  1330. var l9 = this.m[8];
  1331. var l10 = this.m[9];
  1332. var l11 = this.m[10];
  1333. var l12 = this.m[11];
  1334. var l13 = this.m[12];
  1335. var l14 = this.m[13];
  1336. var l15 = this.m[14];
  1337. var l16 = this.m[15];
  1338. var l17 = (l11 * l16) - (l12 * l15);
  1339. var l18 = (l10 * l16) - (l12 * l14);
  1340. var l19 = (l10 * l15) - (l11 * l14);
  1341. var l20 = (l9 * l16) - (l12 * l13);
  1342. var l21 = (l9 * l15) - (l11 * l13);
  1343. var l22 = (l9 * l14) - (l10 * l13);
  1344. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1345. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1346. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1347. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1348. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1349. var l28 = (l7 * l16) - (l8 * l15);
  1350. var l29 = (l6 * l16) - (l8 * l14);
  1351. var l30 = (l6 * l15) - (l7 * l14);
  1352. var l31 = (l5 * l16) - (l8 * l13);
  1353. var l32 = (l5 * l15) - (l7 * l13);
  1354. var l33 = (l5 * l14) - (l6 * l13);
  1355. var l34 = (l7 * l12) - (l8 * l11);
  1356. var l35 = (l6 * l12) - (l8 * l10);
  1357. var l36 = (l6 * l11) - (l7 * l10);
  1358. var l37 = (l5 * l12) - (l8 * l9);
  1359. var l38 = (l5 * l11) - (l7 * l9);
  1360. var l39 = (l5 * l10) - (l6 * l9);
  1361. other.m[0] = l23 * l27;
  1362. other.m[4] = l24 * l27;
  1363. other.m[8] = l25 * l27;
  1364. other.m[12] = l26 * l27;
  1365. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1366. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1367. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1368. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1369. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1370. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1371. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1372. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1373. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1374. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1375. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1376. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1377. return this;
  1378. };
  1379. Matrix.prototype.setTranslation = function (vector3) {
  1380. this.m[12] = vector3.x;
  1381. this.m[13] = vector3.y;
  1382. this.m[14] = vector3.z;
  1383. return this;
  1384. };
  1385. Matrix.prototype.multiply = function (other) {
  1386. var result = new Matrix();
  1387. this.multiplyToRef(other, result);
  1388. return result;
  1389. };
  1390. Matrix.prototype.copyFrom = function (other) {
  1391. for (var index = 0; index < 16; index++) {
  1392. this.m[index] = other.m[index];
  1393. }
  1394. return this;
  1395. };
  1396. Matrix.prototype.copyToArray = function (array, offset) {
  1397. if (offset === void 0) { offset = 0; }
  1398. for (var index = 0; index < 16; index++) {
  1399. array[offset + index] = this.m[index];
  1400. }
  1401. return this;
  1402. };
  1403. Matrix.prototype.multiplyToRef = function (other, result) {
  1404. this.multiplyToArray(other, result.m, 0);
  1405. return this;
  1406. };
  1407. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1408. var tm0 = this.m[0];
  1409. var tm1 = this.m[1];
  1410. var tm2 = this.m[2];
  1411. var tm3 = this.m[3];
  1412. var tm4 = this.m[4];
  1413. var tm5 = this.m[5];
  1414. var tm6 = this.m[6];
  1415. var tm7 = this.m[7];
  1416. var tm8 = this.m[8];
  1417. var tm9 = this.m[9];
  1418. var tm10 = this.m[10];
  1419. var tm11 = this.m[11];
  1420. var tm12 = this.m[12];
  1421. var tm13 = this.m[13];
  1422. var tm14 = this.m[14];
  1423. var tm15 = this.m[15];
  1424. var om0 = other.m[0];
  1425. var om1 = other.m[1];
  1426. var om2 = other.m[2];
  1427. var om3 = other.m[3];
  1428. var om4 = other.m[4];
  1429. var om5 = other.m[5];
  1430. var om6 = other.m[6];
  1431. var om7 = other.m[7];
  1432. var om8 = other.m[8];
  1433. var om9 = other.m[9];
  1434. var om10 = other.m[10];
  1435. var om11 = other.m[11];
  1436. var om12 = other.m[12];
  1437. var om13 = other.m[13];
  1438. var om14 = other.m[14];
  1439. var om15 = other.m[15];
  1440. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1441. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1442. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1443. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1444. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1445. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1446. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1447. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1448. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1449. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1450. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1451. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1452. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1453. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1454. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1455. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1456. return this;
  1457. };
  1458. Matrix.prototype.equals = function (value) {
  1459. return value && (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] && this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] && this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] && this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1460. };
  1461. Matrix.prototype.clone = function () {
  1462. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1463. };
  1464. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1465. translation.x = this.m[12];
  1466. translation.y = this.m[13];
  1467. translation.z = this.m[14];
  1468. var xs = BABYLON.Tools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1469. var ys = BABYLON.Tools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1470. var zs = BABYLON.Tools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1471. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1472. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1473. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1474. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1475. rotation.x = 0;
  1476. rotation.y = 0;
  1477. rotation.z = 0;
  1478. rotation.w = 1;
  1479. return false;
  1480. }
  1481. var rotationMatrix = Matrix.FromValues(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1);
  1482. Quaternion.FromRotationMatrixToRef(rotationMatrix, rotation);
  1483. return true;
  1484. };
  1485. // Statics
  1486. Matrix.FromArray = function (array, offset) {
  1487. var result = new Matrix();
  1488. if (!offset) {
  1489. offset = 0;
  1490. }
  1491. Matrix.FromArrayToRef(array, offset, result);
  1492. return result;
  1493. };
  1494. Matrix.FromArrayToRef = function (array, offset, result) {
  1495. for (var index = 0; index < 16; index++) {
  1496. result.m[index] = array[index + offset];
  1497. }
  1498. };
  1499. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  1500. result.m[0] = initialM11;
  1501. result.m[1] = initialM12;
  1502. result.m[2] = initialM13;
  1503. result.m[3] = initialM14;
  1504. result.m[4] = initialM21;
  1505. result.m[5] = initialM22;
  1506. result.m[6] = initialM23;
  1507. result.m[7] = initialM24;
  1508. result.m[8] = initialM31;
  1509. result.m[9] = initialM32;
  1510. result.m[10] = initialM33;
  1511. result.m[11] = initialM34;
  1512. result.m[12] = initialM41;
  1513. result.m[13] = initialM42;
  1514. result.m[14] = initialM43;
  1515. result.m[15] = initialM44;
  1516. };
  1517. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  1518. var result = new Matrix();
  1519. result.m[0] = initialM11;
  1520. result.m[1] = initialM12;
  1521. result.m[2] = initialM13;
  1522. result.m[3] = initialM14;
  1523. result.m[4] = initialM21;
  1524. result.m[5] = initialM22;
  1525. result.m[6] = initialM23;
  1526. result.m[7] = initialM24;
  1527. result.m[8] = initialM31;
  1528. result.m[9] = initialM32;
  1529. result.m[10] = initialM33;
  1530. result.m[11] = initialM34;
  1531. result.m[12] = initialM41;
  1532. result.m[13] = initialM42;
  1533. result.m[14] = initialM43;
  1534. result.m[15] = initialM44;
  1535. return result;
  1536. };
  1537. Matrix.Compose = function (scale, rotation, translation) {
  1538. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  1539. var rotationMatrix = Matrix.Identity();
  1540. rotation.toRotationMatrix(rotationMatrix);
  1541. result = result.multiply(rotationMatrix);
  1542. result.setTranslation(translation);
  1543. return result;
  1544. };
  1545. Matrix.Identity = function () {
  1546. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  1547. };
  1548. Matrix.IdentityToRef = function (result) {
  1549. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  1550. };
  1551. Matrix.Zero = function () {
  1552. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  1553. };
  1554. Matrix.RotationX = function (angle) {
  1555. var result = new Matrix();
  1556. Matrix.RotationXToRef(angle, result);
  1557. return result;
  1558. };
  1559. Matrix.Invert = function (source) {
  1560. var result = new Matrix();
  1561. source.invertToRef(result);
  1562. return result;
  1563. };
  1564. Matrix.RotationXToRef = function (angle, result) {
  1565. var s = Math.sin(angle);
  1566. var c = Math.cos(angle);
  1567. result.m[0] = 1.0;
  1568. result.m[15] = 1.0;
  1569. result.m[5] = c;
  1570. result.m[10] = c;
  1571. result.m[9] = -s;
  1572. result.m[6] = s;
  1573. result.m[1] = 0;
  1574. result.m[2] = 0;
  1575. result.m[3] = 0;
  1576. result.m[4] = 0;
  1577. result.m[7] = 0;
  1578. result.m[8] = 0;
  1579. result.m[11] = 0;
  1580. result.m[12] = 0;
  1581. result.m[13] = 0;
  1582. result.m[14] = 0;
  1583. };
  1584. Matrix.RotationY = function (angle) {
  1585. var result = new Matrix();
  1586. Matrix.RotationYToRef(angle, result);
  1587. return result;
  1588. };
  1589. Matrix.RotationYToRef = function (angle, result) {
  1590. var s = Math.sin(angle);
  1591. var c = Math.cos(angle);
  1592. result.m[5] = 1.0;
  1593. result.m[15] = 1.0;
  1594. result.m[0] = c;
  1595. result.m[2] = -s;
  1596. result.m[8] = s;
  1597. result.m[10] = c;
  1598. result.m[1] = 0;
  1599. result.m[3] = 0;
  1600. result.m[4] = 0;
  1601. result.m[6] = 0;
  1602. result.m[7] = 0;
  1603. result.m[9] = 0;
  1604. result.m[11] = 0;
  1605. result.m[12] = 0;
  1606. result.m[13] = 0;
  1607. result.m[14] = 0;
  1608. };
  1609. Matrix.RotationZ = function (angle) {
  1610. var result = new Matrix();
  1611. Matrix.RotationZToRef(angle, result);
  1612. return result;
  1613. };
  1614. Matrix.RotationZToRef = function (angle, result) {
  1615. var s = Math.sin(angle);
  1616. var c = Math.cos(angle);
  1617. result.m[10] = 1.0;
  1618. result.m[15] = 1.0;
  1619. result.m[0] = c;
  1620. result.m[1] = s;
  1621. result.m[4] = -s;
  1622. result.m[5] = c;
  1623. result.m[2] = 0;
  1624. result.m[3] = 0;
  1625. result.m[6] = 0;
  1626. result.m[7] = 0;
  1627. result.m[8] = 0;
  1628. result.m[9] = 0;
  1629. result.m[11] = 0;
  1630. result.m[12] = 0;
  1631. result.m[13] = 0;
  1632. result.m[14] = 0;
  1633. };
  1634. Matrix.RotationAxis = function (axis, angle) {
  1635. var s = Math.sin(-angle);
  1636. var c = Math.cos(-angle);
  1637. var c1 = 1 - c;
  1638. axis.normalize();
  1639. var result = Matrix.Zero();
  1640. result.m[0] = (axis.x * axis.x) * c1 + c;
  1641. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  1642. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  1643. result.m[3] = 0.0;
  1644. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  1645. result.m[5] = (axis.y * axis.y) * c1 + c;
  1646. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  1647. result.m[7] = 0.0;
  1648. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  1649. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  1650. result.m[10] = (axis.z * axis.z) * c1 + c;
  1651. result.m[11] = 0.0;
  1652. result.m[15] = 1.0;
  1653. return result;
  1654. };
  1655. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1656. var result = new Matrix();
  1657. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  1658. return result;
  1659. };
  1660. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1661. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  1662. this._tempQuaternion.toRotationMatrix(result);
  1663. };
  1664. Matrix.Scaling = function (x, y, z) {
  1665. var result = Matrix.Zero();
  1666. Matrix.ScalingToRef(x, y, z, result);
  1667. return result;
  1668. };
  1669. Matrix.ScalingToRef = function (x, y, z, result) {
  1670. result.m[0] = x;
  1671. result.m[1] = 0;
  1672. result.m[2] = 0;
  1673. result.m[3] = 0;
  1674. result.m[4] = 0;
  1675. result.m[5] = y;
  1676. result.m[6] = 0;
  1677. result.m[7] = 0;
  1678. result.m[8] = 0;
  1679. result.m[9] = 0;
  1680. result.m[10] = z;
  1681. result.m[11] = 0;
  1682. result.m[12] = 0;
  1683. result.m[13] = 0;
  1684. result.m[14] = 0;
  1685. result.m[15] = 1.0;
  1686. };
  1687. Matrix.Translation = function (x, y, z) {
  1688. var result = Matrix.Identity();
  1689. Matrix.TranslationToRef(x, y, z, result);
  1690. return result;
  1691. };
  1692. Matrix.TranslationToRef = function (x, y, z, result) {
  1693. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  1694. };
  1695. Matrix.LookAtLH = function (eye, target, up) {
  1696. var result = Matrix.Zero();
  1697. Matrix.LookAtLHToRef(eye, target, up, result);
  1698. return result;
  1699. };
  1700. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  1701. // Z axis
  1702. target.subtractToRef(eye, this._zAxis);
  1703. this._zAxis.normalize();
  1704. // X axis
  1705. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  1706. this._xAxis.normalize();
  1707. // Y axis
  1708. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  1709. this._yAxis.normalize();
  1710. // Eye angles
  1711. var ex = -Vector3.Dot(this._xAxis, eye);
  1712. var ey = -Vector3.Dot(this._yAxis, eye);
  1713. var ez = -Vector3.Dot(this._zAxis, eye);
  1714. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  1715. };
  1716. Matrix.OrthoLH = function (width, height, znear, zfar) {
  1717. var matrix = Matrix.Zero();
  1718. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  1719. return matrix;
  1720. };
  1721. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  1722. var hw = 2.0 / width;
  1723. var hh = 2.0 / height;
  1724. var id = 1.0 / (zfar - znear);
  1725. var nid = znear / (znear - zfar);
  1726. Matrix.FromValuesToRef(hw, 0, 0, 0, 0, hh, 0, 0, 0, 0, id, 0, 0, 0, nid, 1, result);
  1727. };
  1728. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  1729. var matrix = Matrix.Zero();
  1730. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  1731. return matrix;
  1732. };
  1733. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  1734. result.m[0] = 2.0 / (right - left);
  1735. result.m[1] = result.m[2] = result.m[3] = 0;
  1736. result.m[5] = 2.0 / (top - bottom);
  1737. result.m[4] = result.m[6] = result.m[7] = 0;
  1738. result.m[10] = -1.0 / (znear - zfar);
  1739. result.m[8] = result.m[9] = result.m[11] = 0;
  1740. result.m[12] = (left + right) / (left - right);
  1741. result.m[13] = (top + bottom) / (bottom - top);
  1742. result.m[14] = znear / (znear - zfar);
  1743. result.m[15] = 1.0;
  1744. };
  1745. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  1746. var matrix = Matrix.Zero();
  1747. matrix.m[0] = (2.0 * znear) / width;
  1748. matrix.m[1] = matrix.m[2] = matrix.m[3] = 0.0;
  1749. matrix.m[5] = (2.0 * znear) / height;
  1750. matrix.m[4] = matrix.m[6] = matrix.m[7] = 0.0;
  1751. matrix.m[10] = -zfar / (znear - zfar);
  1752. matrix.m[8] = matrix.m[9] = 0.0;
  1753. matrix.m[11] = 1.0;
  1754. matrix.m[12] = matrix.m[13] = matrix.m[15] = 0.0;
  1755. matrix.m[14] = (znear * zfar) / (znear - zfar);
  1756. return matrix;
  1757. };
  1758. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  1759. var matrix = Matrix.Zero();
  1760. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  1761. return matrix;
  1762. };
  1763. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, fovMode) {
  1764. if (fovMode === void 0) { fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED; }
  1765. var tan = 1.0 / (Math.tan(fov * 0.5));
  1766. var v_fixed = (fovMode === BABYLON.Camera.FOVMODE_VERTICAL_FIXED);
  1767. if (v_fixed) {
  1768. result.m[0] = tan / aspect;
  1769. }
  1770. else {
  1771. result.m[0] = tan;
  1772. }
  1773. result.m[1] = result.m[2] = result.m[3] = 0.0;
  1774. if (v_fixed) {
  1775. result.m[5] = tan;
  1776. }
  1777. else {
  1778. result.m[5] = tan * aspect;
  1779. }
  1780. result.m[4] = result.m[6] = result.m[7] = 0.0;
  1781. result.m[8] = result.m[9] = 0.0;
  1782. result.m[10] = -zfar / (znear - zfar);
  1783. result.m[11] = 1.0;
  1784. result.m[12] = result.m[13] = result.m[15] = 0.0;
  1785. result.m[14] = (znear * zfar) / (znear - zfar);
  1786. };
  1787. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  1788. var cw = viewport.width;
  1789. var ch = viewport.height;
  1790. var cx = viewport.x;
  1791. var cy = viewport.y;
  1792. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  1793. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  1794. };
  1795. Matrix.Transpose = function (matrix) {
  1796. var result = new Matrix();
  1797. result.m[0] = matrix.m[0];
  1798. result.m[1] = matrix.m[4];
  1799. result.m[2] = matrix.m[8];
  1800. result.m[3] = matrix.m[12];
  1801. result.m[4] = matrix.m[1];
  1802. result.m[5] = matrix.m[5];
  1803. result.m[6] = matrix.m[9];
  1804. result.m[7] = matrix.m[13];
  1805. result.m[8] = matrix.m[2];
  1806. result.m[9] = matrix.m[6];
  1807. result.m[10] = matrix.m[10];
  1808. result.m[11] = matrix.m[14];
  1809. result.m[12] = matrix.m[3];
  1810. result.m[13] = matrix.m[7];
  1811. result.m[14] = matrix.m[11];
  1812. result.m[15] = matrix.m[15];
  1813. return result;
  1814. };
  1815. Matrix.Reflection = function (plane) {
  1816. var matrix = new Matrix();
  1817. Matrix.ReflectionToRef(plane, matrix);
  1818. return matrix;
  1819. };
  1820. Matrix.ReflectionToRef = function (plane, result) {
  1821. plane.normalize();
  1822. var x = plane.normal.x;
  1823. var y = plane.normal.y;
  1824. var z = plane.normal.z;
  1825. var temp = -2 * x;
  1826. var temp2 = -2 * y;
  1827. var temp3 = -2 * z;
  1828. result.m[0] = (temp * x) + 1;
  1829. result.m[1] = temp2 * x;
  1830. result.m[2] = temp3 * x;
  1831. result.m[3] = 0.0;
  1832. result.m[4] = temp * y;
  1833. result.m[5] = (temp2 * y) + 1;
  1834. result.m[6] = temp3 * y;
  1835. result.m[7] = 0.0;
  1836. result.m[8] = temp * z;
  1837. result.m[9] = temp2 * z;
  1838. result.m[10] = (temp3 * z) + 1;
  1839. result.m[11] = 0.0;
  1840. result.m[12] = temp * plane.d;
  1841. result.m[13] = temp2 * plane.d;
  1842. result.m[14] = temp3 * plane.d;
  1843. result.m[15] = 1.0;
  1844. };
  1845. Matrix._tempQuaternion = new Quaternion();
  1846. Matrix._xAxis = Vector3.Zero();
  1847. Matrix._yAxis = Vector3.Zero();
  1848. Matrix._zAxis = Vector3.Zero();
  1849. return Matrix;
  1850. })();
  1851. BABYLON.Matrix = Matrix;
  1852. var Plane = (function () {
  1853. function Plane(a, b, c, d) {
  1854. this.normal = new Vector3(a, b, c);
  1855. this.d = d;
  1856. }
  1857. Plane.prototype.asArray = function () {
  1858. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  1859. };
  1860. // Methods
  1861. Plane.prototype.clone = function () {
  1862. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  1863. };
  1864. Plane.prototype.normalize = function () {
  1865. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  1866. var magnitude = 0;
  1867. if (norm !== 0) {
  1868. magnitude = 1.0 / norm;
  1869. }
  1870. this.normal.x *= magnitude;
  1871. this.normal.y *= magnitude;
  1872. this.normal.z *= magnitude;
  1873. this.d *= magnitude;
  1874. return this;
  1875. };
  1876. Plane.prototype.transform = function (transformation) {
  1877. var transposedMatrix = Matrix.Transpose(transformation);
  1878. var x = this.normal.x;
  1879. var y = this.normal.y;
  1880. var z = this.normal.z;
  1881. var d = this.d;
  1882. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  1883. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  1884. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  1885. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  1886. return new Plane(normalX, normalY, normalZ, finalD);
  1887. };
  1888. Plane.prototype.dotCoordinate = function (point) {
  1889. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  1890. };
  1891. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  1892. var x1 = point2.x - point1.x;
  1893. var y1 = point2.y - point1.y;
  1894. var z1 = point2.z - point1.z;
  1895. var x2 = point3.x - point1.x;
  1896. var y2 = point3.y - point1.y;
  1897. var z2 = point3.z - point1.z;
  1898. var yz = (y1 * z2) - (z1 * y2);
  1899. var xz = (z1 * x2) - (x1 * z2);
  1900. var xy = (x1 * y2) - (y1 * x2);
  1901. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  1902. var invPyth;
  1903. if (pyth !== 0) {
  1904. invPyth = 1.0 / pyth;
  1905. }
  1906. else {
  1907. invPyth = 0;
  1908. }
  1909. this.normal.x = yz * invPyth;
  1910. this.normal.y = xz * invPyth;
  1911. this.normal.z = xy * invPyth;
  1912. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  1913. return this;
  1914. };
  1915. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  1916. var dot = Vector3.Dot(this.normal, direction);
  1917. return (dot <= epsilon);
  1918. };
  1919. Plane.prototype.signedDistanceTo = function (point) {
  1920. return Vector3.Dot(point, this.normal) + this.d;
  1921. };
  1922. // Statics
  1923. Plane.FromArray = function (array) {
  1924. return new Plane(array[0], array[1], array[2], array[3]);
  1925. };
  1926. Plane.FromPoints = function (point1, point2, point3) {
  1927. var result = new Plane(0, 0, 0, 0);
  1928. result.copyFromPoints(point1, point2, point3);
  1929. return result;
  1930. };
  1931. Plane.FromPositionAndNormal = function (origin, normal) {
  1932. var result = new Plane(0, 0, 0, 0);
  1933. normal.normalize();
  1934. result.normal = normal;
  1935. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1936. return result;
  1937. };
  1938. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  1939. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  1940. return Vector3.Dot(point, normal) + d;
  1941. };
  1942. return Plane;
  1943. })();
  1944. BABYLON.Plane = Plane;
  1945. var Viewport = (function () {
  1946. function Viewport(x, y, width, height) {
  1947. this.x = x;
  1948. this.y = y;
  1949. this.width = width;
  1950. this.height = height;
  1951. }
  1952. Viewport.prototype.toGlobal = function (engine) {
  1953. var width = engine.getRenderWidth();
  1954. var height = engine.getRenderHeight();
  1955. return new Viewport(this.x * width, this.y * height, this.width * width, this.height * height);
  1956. };
  1957. return Viewport;
  1958. })();
  1959. BABYLON.Viewport = Viewport;
  1960. var Frustum = (function () {
  1961. function Frustum() {
  1962. }
  1963. Frustum.GetPlanes = function (transform) {
  1964. var frustumPlanes = [];
  1965. for (var index = 0; index < 6; index++) {
  1966. frustumPlanes.push(new Plane(0, 0, 0, 0));
  1967. }
  1968. Frustum.GetPlanesToRef(transform, frustumPlanes);
  1969. return frustumPlanes;
  1970. };
  1971. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  1972. // Near
  1973. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  1974. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  1975. frustumPlanes[0].normal.z = transform.m[10] + transform.m[10];
  1976. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  1977. frustumPlanes[0].normalize();
  1978. // Far
  1979. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  1980. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  1981. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  1982. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  1983. frustumPlanes[1].normalize();
  1984. // Left
  1985. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  1986. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  1987. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  1988. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  1989. frustumPlanes[2].normalize();
  1990. // Right
  1991. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  1992. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  1993. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  1994. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  1995. frustumPlanes[3].normalize();
  1996. // Top
  1997. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  1998. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  1999. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2000. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2001. frustumPlanes[4].normalize();
  2002. // Bottom
  2003. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2004. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2005. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2006. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2007. frustumPlanes[5].normalize();
  2008. };
  2009. return Frustum;
  2010. })();
  2011. BABYLON.Frustum = Frustum;
  2012. var Ray = (function () {
  2013. function Ray(origin, direction, length) {
  2014. if (length === void 0) { length = Number.MAX_VALUE; }
  2015. this.origin = origin;
  2016. this.direction = direction;
  2017. this.length = length;
  2018. }
  2019. // Methods
  2020. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  2021. var d = 0.0;
  2022. var maxValue = Number.MAX_VALUE;
  2023. if (Math.abs(this.direction.x) < 0.0000001) {
  2024. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  2025. return false;
  2026. }
  2027. }
  2028. else {
  2029. var inv = 1.0 / this.direction.x;
  2030. var min = (minimum.x - this.origin.x) * inv;
  2031. var max = (maximum.x - this.origin.x) * inv;
  2032. if (max === -Infinity) {
  2033. max = Infinity;
  2034. }
  2035. if (min > max) {
  2036. var temp = min;
  2037. min = max;
  2038. max = temp;
  2039. }
  2040. d = Math.max(min, d);
  2041. maxValue = Math.min(max, maxValue);
  2042. if (d > maxValue) {
  2043. return false;
  2044. }
  2045. }
  2046. if (Math.abs(this.direction.y) < 0.0000001) {
  2047. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  2048. return false;
  2049. }
  2050. }
  2051. else {
  2052. inv = 1.0 / this.direction.y;
  2053. min = (minimum.y - this.origin.y) * inv;
  2054. max = (maximum.y - this.origin.y) * inv;
  2055. if (max === -Infinity) {
  2056. max = Infinity;
  2057. }
  2058. if (min > max) {
  2059. temp = min;
  2060. min = max;
  2061. max = temp;
  2062. }
  2063. d = Math.max(min, d);
  2064. maxValue = Math.min(max, maxValue);
  2065. if (d > maxValue) {
  2066. return false;
  2067. }
  2068. }
  2069. if (Math.abs(this.direction.z) < 0.0000001) {
  2070. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  2071. return false;
  2072. }
  2073. }
  2074. else {
  2075. inv = 1.0 / this.direction.z;
  2076. min = (minimum.z - this.origin.z) * inv;
  2077. max = (maximum.z - this.origin.z) * inv;
  2078. if (max === -Infinity) {
  2079. max = Infinity;
  2080. }
  2081. if (min > max) {
  2082. temp = min;
  2083. min = max;
  2084. max = temp;
  2085. }
  2086. d = Math.max(min, d);
  2087. maxValue = Math.min(max, maxValue);
  2088. if (d > maxValue) {
  2089. return false;
  2090. }
  2091. }
  2092. return true;
  2093. };
  2094. Ray.prototype.intersectsBox = function (box) {
  2095. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  2096. };
  2097. Ray.prototype.intersectsSphere = function (sphere) {
  2098. var x = sphere.center.x - this.origin.x;
  2099. var y = sphere.center.y - this.origin.y;
  2100. var z = sphere.center.z - this.origin.z;
  2101. var pyth = (x * x) + (y * y) + (z * z);
  2102. var rr = sphere.radius * sphere.radius;
  2103. if (pyth <= rr) {
  2104. return true;
  2105. }
  2106. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  2107. if (dot < 0.0) {
  2108. return false;
  2109. }
  2110. var temp = pyth - (dot * dot);
  2111. return temp <= rr;
  2112. };
  2113. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  2114. if (!this._edge1) {
  2115. this._edge1 = Vector3.Zero();
  2116. this._edge2 = Vector3.Zero();
  2117. this._pvec = Vector3.Zero();
  2118. this._tvec = Vector3.Zero();
  2119. this._qvec = Vector3.Zero();
  2120. }
  2121. vertex1.subtractToRef(vertex0, this._edge1);
  2122. vertex2.subtractToRef(vertex0, this._edge2);
  2123. Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  2124. var det = Vector3.Dot(this._edge1, this._pvec);
  2125. if (det === 0) {
  2126. return null;
  2127. }
  2128. var invdet = 1 / det;
  2129. this.origin.subtractToRef(vertex0, this._tvec);
  2130. var bu = Vector3.Dot(this._tvec, this._pvec) * invdet;
  2131. if (bu < 0 || bu > 1.0) {
  2132. return null;
  2133. }
  2134. Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  2135. var bv = Vector3.Dot(this.direction, this._qvec) * invdet;
  2136. if (bv < 0 || bu + bv > 1.0) {
  2137. return null;
  2138. }
  2139. //check if the distance is longer than the predefined length.
  2140. var distance = Vector3.Dot(this._edge2, this._qvec) * invdet;
  2141. if (distance > this.length) {
  2142. return null;
  2143. }
  2144. return new BABYLON.IntersectionInfo(bu, bv, distance);
  2145. };
  2146. // Statics
  2147. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  2148. var start = Vector3.Unproject(new Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  2149. var end = Vector3.Unproject(new Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  2150. var direction = end.subtract(start);
  2151. direction.normalize();
  2152. return new Ray(start, direction);
  2153. };
  2154. /**
  2155. * Function will create a new transformed ray starting from origin and ending at the end point. Ray's length will be set, and ray will be
  2156. * transformed to the given world matrix.
  2157. * @param origin The origin point
  2158. * @param end The end point
  2159. * @param world a matrix to transform the ray to. Default is the identity matrix.
  2160. */
  2161. Ray.CreateNewFromTo = function (origin, end, world) {
  2162. if (world === void 0) { world = Matrix.Identity(); }
  2163. var direction = end.subtract(origin);
  2164. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  2165. direction.normalize();
  2166. return Ray.Transform(new Ray(origin, direction, length), world);
  2167. };
  2168. Ray.Transform = function (ray, matrix) {
  2169. var newOrigin = Vector3.TransformCoordinates(ray.origin, matrix);
  2170. var newDirection = Vector3.TransformNormal(ray.direction, matrix);
  2171. return new Ray(newOrigin, newDirection, ray.length);
  2172. };
  2173. return Ray;
  2174. })();
  2175. BABYLON.Ray = Ray;
  2176. (function (Space) {
  2177. Space[Space["LOCAL"] = 0] = "LOCAL";
  2178. Space[Space["WORLD"] = 1] = "WORLD";
  2179. })(BABYLON.Space || (BABYLON.Space = {}));
  2180. var Space = BABYLON.Space;
  2181. var Axis = (function () {
  2182. function Axis() {
  2183. }
  2184. Axis.X = new Vector3(1, 0, 0);
  2185. Axis.Y = new Vector3(0, 1, 0);
  2186. Axis.Z = new Vector3(0, 0, 1);
  2187. return Axis;
  2188. })();
  2189. BABYLON.Axis = Axis;
  2190. ;
  2191. var BezierCurve = (function () {
  2192. function BezierCurve() {
  2193. }
  2194. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2195. // Extract X (which is equal to time here)
  2196. var f0 = 1 - 3 * x2 + 3 * x1;
  2197. var f1 = 3 * x2 - 6 * x1;
  2198. var f2 = 3 * x1;
  2199. var refinedT = t;
  2200. for (var i = 0; i < 5; i++) {
  2201. var refinedT2 = refinedT * refinedT;
  2202. var refinedT3 = refinedT2 * refinedT;
  2203. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2204. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2205. refinedT -= (x - t) * slope;
  2206. refinedT = Math.min(1, Math.max(0, refinedT));
  2207. }
  2208. // Resolve cubic bezier for the given x
  2209. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 + 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 + Math.pow(refinedT, 3);
  2210. };
  2211. return BezierCurve;
  2212. })();
  2213. BABYLON.BezierCurve = BezierCurve;
  2214. (function (Orientation) {
  2215. Orientation[Orientation["CW"] = 0] = "CW";
  2216. Orientation[Orientation["CCW"] = 1] = "CCW";
  2217. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2218. var Orientation = BABYLON.Orientation;
  2219. var Angle = (function () {
  2220. function Angle(radians) {
  2221. var _this = this;
  2222. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2223. this.radians = function () { return _this._radians; };
  2224. this._radians = radians;
  2225. if (this._radians < 0)
  2226. this._radians += (2 * Math.PI);
  2227. }
  2228. Angle.BetweenTwoPoints = function (a, b) {
  2229. var delta = b.subtract(a);
  2230. var theta = Math.atan2(delta.y, delta.x);
  2231. return new Angle(theta);
  2232. };
  2233. Angle.FromRadians = function (radians) {
  2234. return new Angle(radians);
  2235. };
  2236. Angle.FromDegrees = function (degrees) {
  2237. return new Angle(degrees * Math.PI / 180);
  2238. };
  2239. return Angle;
  2240. })();
  2241. BABYLON.Angle = Angle;
  2242. var Arc2 = (function () {
  2243. function Arc2(startPoint, midPoint, endPoint) {
  2244. this.startPoint = startPoint;
  2245. this.midPoint = midPoint;
  2246. this.endPoint = endPoint;
  2247. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2248. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2249. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2250. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2251. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2252. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2253. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2254. var a1 = this.startAngle.degrees();
  2255. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2256. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2257. // angles correction
  2258. if (a2 - a1 > +180.0)
  2259. a2 -= 360.0;
  2260. if (a2 - a1 < -180.0)
  2261. a2 += 360.0;
  2262. if (a3 - a2 > +180.0)
  2263. a3 -= 360.0;
  2264. if (a3 - a2 < -180.0)
  2265. a3 += 360.0;
  2266. this.orientation = (a2 - a1) < 0 ? 0 /* CW */ : 1 /* CCW */;
  2267. this.angle = Angle.FromDegrees(this.orientation === 0 /* CW */ ? a1 - a3 : a3 - a1);
  2268. }
  2269. return Arc2;
  2270. })();
  2271. BABYLON.Arc2 = Arc2;
  2272. var PathCursor = (function () {
  2273. function PathCursor(path) {
  2274. this.path = path;
  2275. this._onchange = new Array();
  2276. this.value = 0;
  2277. this.animations = new Array();
  2278. }
  2279. PathCursor.prototype.getPoint = function () {
  2280. var point = this.path.getPointAtLengthPosition(this.value);
  2281. return new Vector3(point.x, 0, point.y);
  2282. };
  2283. PathCursor.prototype.moveAhead = function (step) {
  2284. if (step === void 0) { step = 0.002; }
  2285. this.move(step);
  2286. return this;
  2287. };
  2288. PathCursor.prototype.moveBack = function (step) {
  2289. if (step === void 0) { step = 0.002; }
  2290. this.move(-step);
  2291. return this;
  2292. };
  2293. PathCursor.prototype.move = function (step) {
  2294. if (Math.abs(step) > 1) {
  2295. throw "step size should be less than 1.";
  2296. }
  2297. this.value += step;
  2298. this.ensureLimits();
  2299. this.raiseOnChange();
  2300. return this;
  2301. };
  2302. PathCursor.prototype.ensureLimits = function () {
  2303. while (this.value > 1) {
  2304. this.value -= 1;
  2305. }
  2306. while (this.value < 0) {
  2307. this.value += 1;
  2308. }
  2309. return this;
  2310. };
  2311. // used by animation engine
  2312. PathCursor.prototype.markAsDirty = function (propertyName) {
  2313. this.ensureLimits();
  2314. this.raiseOnChange();
  2315. return this;
  2316. };
  2317. PathCursor.prototype.raiseOnChange = function () {
  2318. var _this = this;
  2319. this._onchange.forEach(function (f) { return f(_this); });
  2320. return this;
  2321. };
  2322. PathCursor.prototype.onchange = function (f) {
  2323. this._onchange.push(f);
  2324. return this;
  2325. };
  2326. return PathCursor;
  2327. })();
  2328. BABYLON.PathCursor = PathCursor;
  2329. var Path2 = (function () {
  2330. function Path2(x, y) {
  2331. this._points = [];
  2332. this._length = 0;
  2333. this.closed = false;
  2334. this._points.push(new Vector2(x, y));
  2335. }
  2336. Path2.prototype.addLineTo = function (x, y) {
  2337. if (closed) {
  2338. BABYLON.Tools.Error("cannot add lines to closed paths");
  2339. return this;
  2340. }
  2341. var newPoint = new Vector2(x, y);
  2342. var previousPoint = this._points[this._points.length - 1];
  2343. this._points.push(newPoint);
  2344. this._length += newPoint.subtract(previousPoint).length();
  2345. return this;
  2346. };
  2347. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2348. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2349. if (closed) {
  2350. BABYLON.Tools.Error("cannot add arcs to closed paths");
  2351. return this;
  2352. }
  2353. var startPoint = this._points[this._points.length - 1];
  2354. var midPoint = new Vector2(midX, midY);
  2355. var endPoint = new Vector2(endX, endY);
  2356. var arc = new Arc2(startPoint, midPoint, endPoint);
  2357. var increment = arc.angle.radians() / numberOfSegments;
  2358. if (arc.orientation === 0 /* CW */)
  2359. increment *= -1;
  2360. var currentAngle = arc.startAngle.radians() + increment;
  2361. for (var i = 0; i < numberOfSegments; i++) {
  2362. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2363. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2364. this.addLineTo(x, y);
  2365. currentAngle += increment;
  2366. }
  2367. return this;
  2368. };
  2369. Path2.prototype.close = function () {
  2370. this.closed = true;
  2371. return this;
  2372. };
  2373. Path2.prototype.length = function () {
  2374. var result = this._length;
  2375. if (!this.closed) {
  2376. var lastPoint = this._points[this._points.length - 1];
  2377. var firstPoint = this._points[0];
  2378. result += (firstPoint.subtract(lastPoint).length());
  2379. }
  2380. return result;
  2381. };
  2382. Path2.prototype.getPoints = function () {
  2383. return this._points;
  2384. };
  2385. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2386. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2387. BABYLON.Tools.Error("normalized length position should be between 0 and 1.");
  2388. return Vector2.Zero();
  2389. }
  2390. var lengthPosition = normalizedLengthPosition * this.length();
  2391. var previousOffset = 0;
  2392. for (var i = 0; i < this._points.length; i++) {
  2393. var j = (i + 1) % this._points.length;
  2394. var a = this._points[i];
  2395. var b = this._points[j];
  2396. var bToA = b.subtract(a);
  2397. var nextOffset = (bToA.length() + previousOffset);
  2398. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2399. var dir = bToA.normalize();
  2400. var localOffset = lengthPosition - previousOffset;
  2401. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2402. }
  2403. previousOffset = nextOffset;
  2404. }
  2405. BABYLON.Tools.Error("internal error");
  2406. return Vector2.Zero();
  2407. };
  2408. Path2.StartingAt = function (x, y) {
  2409. return new Path2(x, y);
  2410. };
  2411. return Path2;
  2412. })();
  2413. BABYLON.Path2 = Path2;
  2414. var Path3D = (function () {
  2415. function Path3D(path) {
  2416. this.path = path;
  2417. this._curve = [];
  2418. this._distances = [];
  2419. this._tangents = [];
  2420. this._normals = [];
  2421. this._binormals = [];
  2422. this._curve = path.slice(); // copy array
  2423. var l = this._curve.length;
  2424. // first and last tangents
  2425. this._tangents[0] = this._curve[1].subtract(this._curve[0]);
  2426. this._tangents[0].normalize();
  2427. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2428. this._tangents[l - 1].normalize();
  2429. // normals and binormals at first point : arbitrary vector with _normalVector()
  2430. var tg0 = this._tangents[0];
  2431. var pp0 = this._normalVector(this._curve[0], tg0);
  2432. this._normals[0] = pp0;
  2433. this._normals[0].normalize();
  2434. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2435. this._normals[0].normalize();
  2436. this._distances[0] = 0;
  2437. // normals and binormals : next points
  2438. var prev; // previous vector (segment)
  2439. var cur; // current vector (segment)
  2440. var curTang; // current tangent
  2441. var prevNorm; // previous normal
  2442. var prevBinor; // previous binormal
  2443. for (var i = 1; i < l; i++) {
  2444. // tangents
  2445. prev = this._curve[i].subtract(this._curve[i - 1]);
  2446. if (i < l - 1) {
  2447. cur = this._curve[i + 1].subtract(this._curve[i]);
  2448. this._tangents[i] = prev.add(cur);
  2449. this._tangents[i].normalize();
  2450. }
  2451. this._distances[i] = this._distances[i - 1] + prev.length();
  2452. // normals and binormals
  2453. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2454. curTang = this._tangents[i];
  2455. prevNorm = this._normals[i - 1];
  2456. prevBinor = this._binormals[i - 1];
  2457. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2458. this._normals[i].normalize();
  2459. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2460. this._binormals[i].normalize();
  2461. }
  2462. }
  2463. Path3D.prototype.getCurve = function () {
  2464. return this._curve;
  2465. };
  2466. Path3D.prototype.getTangents = function () {
  2467. return this._tangents;
  2468. };
  2469. Path3D.prototype.getNormals = function () {
  2470. return this._normals;
  2471. };
  2472. Path3D.prototype.getBinormals = function () {
  2473. return this._binormals;
  2474. };
  2475. Path3D.prototype.getDistances = function () {
  2476. return this._distances;
  2477. };
  2478. // private function normalVector(v0, vt) :
  2479. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2480. Path3D.prototype._normalVector = function (v0, vt) {
  2481. var point;
  2482. if (vt.x !== 1) {
  2483. point = new Vector3(1, 0, 0);
  2484. }
  2485. else if (vt.y !== 1) {
  2486. point = new Vector3(0, 1, 0);
  2487. }
  2488. else if (vt.z !== 1) {
  2489. point = new Vector3(0, 0, 1);
  2490. }
  2491. var normal0 = Vector3.Cross(vt, point);
  2492. normal0.normalize();
  2493. return normal0;
  2494. };
  2495. return Path3D;
  2496. })();
  2497. BABYLON.Path3D = Path3D;
  2498. })(BABYLON || (BABYLON = {}));
  2499. //# sourceMappingURL=babylon.math.js.mapvar BABYLON;
  2500. (function (BABYLON) {
  2501. // Screenshots
  2502. var screenshotCanvas;
  2503. var cloneValue = function (source, destinationObject) {
  2504. if (!source)
  2505. return null;
  2506. if (source instanceof BABYLON.Mesh) {
  2507. return null;
  2508. }
  2509. if (source instanceof BABYLON.SubMesh) {
  2510. return source.clone(destinationObject);
  2511. }
  2512. else if (source.clone) {
  2513. return source.clone();
  2514. }
  2515. return null;
  2516. };
  2517. var Tools = (function () {
  2518. function Tools() {
  2519. }
  2520. Tools.GetFilename = function (path) {
  2521. var index = path.lastIndexOf("/");
  2522. if (index < 0)
  2523. return path;
  2524. return path.substring(index + 1);
  2525. };
  2526. Tools.GetDOMTextContent = function (element) {
  2527. var result = "";
  2528. var child = element.firstChild;
  2529. while (child) {
  2530. if (child.nodeType === 3) {
  2531. result += child.textContent;
  2532. }
  2533. child = child.nextSibling;
  2534. }
  2535. return result;
  2536. };
  2537. Tools.ToDegrees = function (angle) {
  2538. return angle * 180 / Math.PI;
  2539. };
  2540. Tools.ToRadians = function (angle) {
  2541. return angle * Math.PI / 180;
  2542. };
  2543. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount) {
  2544. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2545. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2546. for (var index = indexStart; index < indexStart + indexCount; index++) {
  2547. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  2548. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2549. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2550. }
  2551. return {
  2552. minimum: minimum,
  2553. maximum: maximum
  2554. };
  2555. };
  2556. Tools.ExtractMinAndMax = function (positions, start, count) {
  2557. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  2558. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  2559. for (var index = start; index < start + count; index++) {
  2560. var current = new BABYLON.Vector3(positions[index * 3], positions[index * 3 + 1], positions[index * 3 + 2]);
  2561. minimum = BABYLON.Vector3.Minimize(current, minimum);
  2562. maximum = BABYLON.Vector3.Maximize(current, maximum);
  2563. }
  2564. return {
  2565. minimum: minimum,
  2566. maximum: maximum
  2567. };
  2568. };
  2569. Tools.MakeArray = function (obj, allowsNullUndefined) {
  2570. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  2571. return undefined;
  2572. return Array.isArray(obj) ? obj : [obj];
  2573. };
  2574. // Misc.
  2575. Tools.GetPointerPrefix = function () {
  2576. var eventPrefix = "pointer";
  2577. // Check if hand.js is referenced or if the browser natively supports pointer events
  2578. if (!navigator.pointerEnabled) {
  2579. eventPrefix = "mouse";
  2580. }
  2581. return eventPrefix;
  2582. };
  2583. Tools.QueueNewFrame = function (func) {
  2584. if (window.requestAnimationFrame)
  2585. window.requestAnimationFrame(func);
  2586. else if (window.msRequestAnimationFrame)
  2587. window.msRequestAnimationFrame(func);
  2588. else if (window.webkitRequestAnimationFrame)
  2589. window.webkitRequestAnimationFrame(func);
  2590. else if (window.mozRequestAnimationFrame)
  2591. window.mozRequestAnimationFrame(func);
  2592. else if (window.oRequestAnimationFrame)
  2593. window.oRequestAnimationFrame(func);
  2594. else {
  2595. window.setTimeout(func, 16);
  2596. }
  2597. };
  2598. Tools.RequestFullscreen = function (element) {
  2599. if (element.requestFullscreen)
  2600. element.requestFullscreen();
  2601. else if (element.msRequestFullscreen)
  2602. element.msRequestFullscreen();
  2603. else if (element.webkitRequestFullscreen)
  2604. element.webkitRequestFullscreen();
  2605. else if (element.mozRequestFullScreen)
  2606. element.mozRequestFullScreen();
  2607. };
  2608. Tools.ExitFullscreen = function () {
  2609. if (document.exitFullscreen) {
  2610. document.exitFullscreen();
  2611. }
  2612. else if (document.mozCancelFullScreen) {
  2613. document.mozCancelFullScreen();
  2614. }
  2615. else if (document.webkitCancelFullScreen) {
  2616. document.webkitCancelFullScreen();
  2617. }
  2618. else if (document.msCancelFullScreen) {
  2619. document.msCancelFullScreen();
  2620. }
  2621. };
  2622. // External files
  2623. Tools.CleanUrl = function (url) {
  2624. url = url.replace(/#/mg, "%23");
  2625. return url;
  2626. };
  2627. Tools.LoadImage = function (url, onload, onerror, database) {
  2628. url = Tools.CleanUrl(url);
  2629. var img = new Image();
  2630. if (url.substr(0, 5) !== "data:")
  2631. img.crossOrigin = 'anonymous';
  2632. img.onload = function () {
  2633. onload(img);
  2634. };
  2635. img.onerror = function (err) {
  2636. onerror(img, err);
  2637. };
  2638. var noIndexedDB = function () {
  2639. img.src = url;
  2640. };
  2641. var loadFromIndexedDB = function () {
  2642. database.loadImageFromDB(url, img);
  2643. };
  2644. //ANY database to do!
  2645. if (database && database.enableTexturesOffline && BABYLON.Database.isUASupportingBlobStorage) {
  2646. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2647. }
  2648. else {
  2649. if (url.indexOf("file:") === -1) {
  2650. noIndexedDB();
  2651. }
  2652. else {
  2653. try {
  2654. var textureName = url.substring(5);
  2655. var blobURL;
  2656. try {
  2657. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  2658. }
  2659. catch (ex) {
  2660. // Chrome doesn't support oneTimeOnly parameter
  2661. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  2662. }
  2663. img.src = blobURL;
  2664. }
  2665. catch (e) {
  2666. Tools.Log("Error while trying to load texture: " + textureName);
  2667. img.src = null;
  2668. }
  2669. }
  2670. }
  2671. return img;
  2672. };
  2673. //ANY
  2674. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  2675. url = Tools.CleanUrl(url);
  2676. var noIndexedDB = function () {
  2677. var request = new XMLHttpRequest();
  2678. var loadUrl = Tools.BaseUrl + url;
  2679. request.open('GET', loadUrl, true);
  2680. if (useArrayBuffer) {
  2681. request.responseType = "arraybuffer";
  2682. }
  2683. request.onprogress = progressCallBack;
  2684. request.onreadystatechange = function () {
  2685. if (request.readyState === 4) {
  2686. if (request.status === 200 || Tools.ValidateXHRData(request, !useArrayBuffer ? 1 : 6)) {
  2687. callback(!useArrayBuffer ? request.responseText : request.response);
  2688. }
  2689. else {
  2690. if (onError) {
  2691. onError();
  2692. }
  2693. else {
  2694. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  2695. }
  2696. }
  2697. }
  2698. };
  2699. request.send(null);
  2700. };
  2701. var loadFromIndexedDB = function () {
  2702. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  2703. };
  2704. if (url.indexOf("file:") !== -1) {
  2705. var fileName = url.substring(5);
  2706. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, true);
  2707. }
  2708. else {
  2709. // Caching all files
  2710. if (database && database.enableSceneOffline) {
  2711. database.openAsync(loadFromIndexedDB, noIndexedDB);
  2712. }
  2713. else {
  2714. noIndexedDB();
  2715. }
  2716. }
  2717. };
  2718. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  2719. var reader = new FileReader();
  2720. reader.onload = function (e) {
  2721. //target doesn't have result from ts 1.3
  2722. callback(e.target['result']);
  2723. };
  2724. reader.onprogress = progressCallback;
  2725. reader.readAsDataURL(fileToLoad);
  2726. };
  2727. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  2728. var reader = new FileReader();
  2729. reader.onerror = function (e) {
  2730. Tools.Log("Error while reading file: " + fileToLoad.name);
  2731. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.81, 0], meshes: [], cameras: [], lights: [] }));
  2732. };
  2733. reader.onload = function (e) {
  2734. //target doesn't have result from ts 1.3
  2735. callback(e.target['result']);
  2736. };
  2737. reader.onprogress = progressCallBack;
  2738. if (!useArrayBuffer) {
  2739. // Asynchronous read
  2740. reader.readAsText(fileToLoad);
  2741. }
  2742. else {
  2743. reader.readAsArrayBuffer(fileToLoad);
  2744. }
  2745. };
  2746. // Misc.
  2747. Tools.Clamp = function (value, min, max) {
  2748. if (min === void 0) { min = 0; }
  2749. if (max === void 0) { max = 1; }
  2750. return Math.min(max, Math.max(min, value));
  2751. };
  2752. // Returns -1 when value is a negative number and
  2753. // +1 when value is a positive number.
  2754. Tools.Sign = function (value) {
  2755. value = +value; // convert to a number
  2756. if (value === 0 || isNaN(value))
  2757. return value;
  2758. return value > 0 ? 1 : -1;
  2759. };
  2760. Tools.Format = function (value, decimals) {
  2761. if (decimals === void 0) { decimals = 2; }
  2762. return value.toFixed(decimals);
  2763. };
  2764. Tools.CheckExtends = function (v, min, max) {
  2765. if (v.x < min.x)
  2766. min.x = v.x;
  2767. if (v.y < min.y)
  2768. min.y = v.y;
  2769. if (v.z < min.z)
  2770. min.z = v.z;
  2771. if (v.x > max.x)
  2772. max.x = v.x;
  2773. if (v.y > max.y)
  2774. max.y = v.y;
  2775. if (v.z > max.z)
  2776. max.z = v.z;
  2777. };
  2778. Tools.WithinEpsilon = function (a, b, epsilon) {
  2779. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  2780. var num = a - b;
  2781. return -epsilon <= num && num <= epsilon;
  2782. };
  2783. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  2784. for (var prop in source) {
  2785. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  2786. continue;
  2787. }
  2788. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  2789. continue;
  2790. }
  2791. var sourceValue = source[prop];
  2792. var typeOfSourceValue = typeof sourceValue;
  2793. if (typeOfSourceValue === "function") {
  2794. continue;
  2795. }
  2796. if (typeOfSourceValue === "object") {
  2797. if (sourceValue instanceof Array) {
  2798. destination[prop] = [];
  2799. if (sourceValue.length > 0) {
  2800. if (typeof sourceValue[0] == "object") {
  2801. for (var index = 0; index < sourceValue.length; index++) {
  2802. var clonedValue = cloneValue(sourceValue[index], destination);
  2803. if (destination[prop].indexOf(clonedValue) === -1) {
  2804. destination[prop].push(clonedValue);
  2805. }
  2806. }
  2807. }
  2808. else {
  2809. destination[prop] = sourceValue.slice(0);
  2810. }
  2811. }
  2812. }
  2813. else {
  2814. destination[prop] = cloneValue(sourceValue, destination);
  2815. }
  2816. }
  2817. else {
  2818. destination[prop] = sourceValue;
  2819. }
  2820. }
  2821. };
  2822. Tools.IsEmpty = function (obj) {
  2823. for (var i in obj) {
  2824. return false;
  2825. }
  2826. return true;
  2827. };
  2828. Tools.RegisterTopRootEvents = function (events) {
  2829. for (var index = 0; index < events.length; index++) {
  2830. var event = events[index];
  2831. window.addEventListener(event.name, event.handler, false);
  2832. try {
  2833. if (window.parent) {
  2834. window.parent.addEventListener(event.name, event.handler, false);
  2835. }
  2836. }
  2837. catch (e) {
  2838. }
  2839. }
  2840. };
  2841. Tools.UnregisterTopRootEvents = function (events) {
  2842. for (var index = 0; index < events.length; index++) {
  2843. var event = events[index];
  2844. window.removeEventListener(event.name, event.handler);
  2845. try {
  2846. if (window.parent) {
  2847. window.parent.removeEventListener(event.name, event.handler);
  2848. }
  2849. }
  2850. catch (e) {
  2851. }
  2852. }
  2853. };
  2854. Tools.DumpFramebuffer = function (width, height, engine) {
  2855. // Read the contents of the framebuffer
  2856. var numberOfChannelsByLine = width * 4;
  2857. var halfHeight = height / 2;
  2858. //Reading datas from WebGL
  2859. var data = engine.readPixels(0, 0, width, height);
  2860. for (var i = 0; i < halfHeight; i++) {
  2861. for (var j = 0; j < numberOfChannelsByLine; j++) {
  2862. var currentCell = j + i * numberOfChannelsByLine;
  2863. var targetLine = height - i - 1;
  2864. var targetCell = j + targetLine * numberOfChannelsByLine;
  2865. var temp = data[currentCell];
  2866. data[currentCell] = data[targetCell];
  2867. data[targetCell] = temp;
  2868. }
  2869. }
  2870. // Create a 2D canvas to store the result
  2871. if (!screenshotCanvas) {
  2872. screenshotCanvas = document.createElement('canvas');
  2873. }
  2874. screenshotCanvas.width = width;
  2875. screenshotCanvas.height = height;
  2876. var context = screenshotCanvas.getContext('2d');
  2877. // Copy the pixels to a 2D canvas
  2878. var imageData = context.createImageData(width, height);
  2879. //cast is due to ts error in lib.d.ts, see here - https://github.com/Microsoft/TypeScript/issues/949
  2880. var castData = imageData.data;
  2881. castData.set(data);
  2882. context.putImageData(imageData, 0, 0);
  2883. var base64Image = screenshotCanvas.toDataURL();
  2884. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  2885. if (("download" in document.createElement("a"))) {
  2886. var a = window.document.createElement("a");
  2887. a.href = base64Image;
  2888. var date = new Date();
  2889. var stringDate = date.getFullYear() + "/" + date.getMonth() + "/" + date.getDate() + "-" + date.getHours() + ":" + date.getMinutes();
  2890. a.setAttribute("download", "screenshot-" + stringDate + ".png");
  2891. window.document.body.appendChild(a);
  2892. a.addEventListener("click", function () {
  2893. a.parentElement.removeChild(a);
  2894. });
  2895. a.click();
  2896. }
  2897. else {
  2898. var newWindow = window.open("");
  2899. var img = newWindow.document.createElement("img");
  2900. img.src = base64Image;
  2901. newWindow.document.body.appendChild(img);
  2902. }
  2903. };
  2904. Tools.CreateScreenshot = function (engine, camera, size) {
  2905. var width;
  2906. var height;
  2907. var scene = camera.getScene();
  2908. var previousCamera = null;
  2909. if (scene.activeCamera !== camera) {
  2910. previousCamera = scene.activeCamera;
  2911. scene.activeCamera = camera;
  2912. }
  2913. //If a precision value is specified
  2914. if (size.precision) {
  2915. width = Math.round(engine.getRenderWidth() * size.precision);
  2916. height = Math.round(width / engine.getAspectRatio(camera));
  2917. size = { width: width, height: height };
  2918. }
  2919. else if (size.width && size.height) {
  2920. width = size.width;
  2921. height = size.height;
  2922. }
  2923. else if (size.width && !size.height) {
  2924. width = size.width;
  2925. height = Math.round(width / engine.getAspectRatio(camera));
  2926. size = { width: width, height: height };
  2927. }
  2928. else if (size.height && !size.width) {
  2929. height = size.height;
  2930. width = Math.round(height * engine.getAspectRatio(camera));
  2931. size = { width: width, height: height };
  2932. }
  2933. else if (!isNaN(size)) {
  2934. height = size;
  2935. width = size;
  2936. }
  2937. else {
  2938. Tools.Error("Invalid 'size' parameter !");
  2939. return;
  2940. }
  2941. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  2942. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  2943. texture.renderList = scene.meshes;
  2944. texture.onAfterRender = function () {
  2945. Tools.DumpFramebuffer(width, height, engine);
  2946. };
  2947. scene.incrementRenderId();
  2948. texture.render(true);
  2949. texture.dispose();
  2950. if (previousCamera) {
  2951. scene.activeCamera = previousCamera;
  2952. }
  2953. };
  2954. // XHR response validator for local file scenario
  2955. Tools.ValidateXHRData = function (xhr, dataType) {
  2956. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  2957. if (dataType === void 0) { dataType = 7; }
  2958. try {
  2959. if (dataType & 1) {
  2960. if (xhr.responseText && xhr.responseText.length > 0) {
  2961. return true;
  2962. }
  2963. else if (dataType === 1) {
  2964. return false;
  2965. }
  2966. }
  2967. if (dataType & 2) {
  2968. // Check header width and height since there is no "TGA" magic number
  2969. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  2970. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  2971. return true;
  2972. }
  2973. else if (dataType === 2) {
  2974. return false;
  2975. }
  2976. }
  2977. if (dataType & 4) {
  2978. // Check for the "DDS" magic number
  2979. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  2980. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  2981. return true;
  2982. }
  2983. else {
  2984. return false;
  2985. }
  2986. }
  2987. }
  2988. catch (e) {
  2989. }
  2990. return false;
  2991. };
  2992. Object.defineProperty(Tools, "NoneLogLevel", {
  2993. get: function () {
  2994. return Tools._NoneLogLevel;
  2995. },
  2996. enumerable: true,
  2997. configurable: true
  2998. });
  2999. Object.defineProperty(Tools, "MessageLogLevel", {
  3000. get: function () {
  3001. return Tools._MessageLogLevel;
  3002. },
  3003. enumerable: true,
  3004. configurable: true
  3005. });
  3006. Object.defineProperty(Tools, "WarningLogLevel", {
  3007. get: function () {
  3008. return Tools._WarningLogLevel;
  3009. },
  3010. enumerable: true,
  3011. configurable: true
  3012. });
  3013. Object.defineProperty(Tools, "ErrorLogLevel", {
  3014. get: function () {
  3015. return Tools._ErrorLogLevel;
  3016. },
  3017. enumerable: true,
  3018. configurable: true
  3019. });
  3020. Object.defineProperty(Tools, "AllLogLevel", {
  3021. get: function () {
  3022. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  3023. },
  3024. enumerable: true,
  3025. configurable: true
  3026. });
  3027. Tools._AddLogEntry = function (entry) {
  3028. Tools._LogCache = entry + Tools._LogCache;
  3029. if (Tools.OnNewCacheEntry) {
  3030. Tools.OnNewCacheEntry(entry);
  3031. }
  3032. };
  3033. Tools._FormatMessage = function (message) {
  3034. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  3035. var date = new Date();
  3036. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  3037. };
  3038. Tools._LogDisabled = function (message) {
  3039. // nothing to do
  3040. };
  3041. Tools._LogEnabled = function (message) {
  3042. var formattedMessage = Tools._FormatMessage(message);
  3043. console.log("BJS - " + formattedMessage);
  3044. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  3045. Tools._AddLogEntry(entry);
  3046. };
  3047. Tools._WarnDisabled = function (message) {
  3048. // nothing to do
  3049. };
  3050. Tools._WarnEnabled = function (message) {
  3051. var formattedMessage = Tools._FormatMessage(message);
  3052. console.warn("BJS - " + formattedMessage);
  3053. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  3054. Tools._AddLogEntry(entry);
  3055. };
  3056. Tools._ErrorDisabled = function (message) {
  3057. // nothing to do
  3058. };
  3059. Tools._ErrorEnabled = function (message) {
  3060. var formattedMessage = Tools._FormatMessage(message);
  3061. console.error("BJS - " + formattedMessage);
  3062. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  3063. Tools._AddLogEntry(entry);
  3064. };
  3065. Object.defineProperty(Tools, "LogCache", {
  3066. get: function () {
  3067. return Tools._LogCache;
  3068. },
  3069. enumerable: true,
  3070. configurable: true
  3071. });
  3072. Object.defineProperty(Tools, "LogLevels", {
  3073. set: function (level) {
  3074. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  3075. Tools.Log = Tools._LogEnabled;
  3076. }
  3077. else {
  3078. Tools.Log = Tools._LogDisabled;
  3079. }
  3080. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  3081. Tools.Warn = Tools._WarnEnabled;
  3082. }
  3083. else {
  3084. Tools.Warn = Tools._WarnDisabled;
  3085. }
  3086. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  3087. Tools.Error = Tools._ErrorEnabled;
  3088. }
  3089. else {
  3090. Tools.Error = Tools._ErrorDisabled;
  3091. }
  3092. },
  3093. enumerable: true,
  3094. configurable: true
  3095. });
  3096. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  3097. get: function () {
  3098. return Tools._PerformanceNoneLogLevel;
  3099. },
  3100. enumerable: true,
  3101. configurable: true
  3102. });
  3103. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  3104. get: function () {
  3105. return Tools._PerformanceUserMarkLogLevel;
  3106. },
  3107. enumerable: true,
  3108. configurable: true
  3109. });
  3110. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  3111. get: function () {
  3112. return Tools._PerformanceConsoleLogLevel;
  3113. },
  3114. enumerable: true,
  3115. configurable: true
  3116. });
  3117. Object.defineProperty(Tools, "PerformanceLogLevel", {
  3118. set: function (level) {
  3119. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  3120. Tools.StartPerformanceCounter = Tools._StartUserMark;
  3121. Tools.EndPerformanceCounter = Tools._EndUserMark;
  3122. return;
  3123. }
  3124. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  3125. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  3126. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  3127. return;
  3128. }
  3129. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3130. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3131. },
  3132. enumerable: true,
  3133. configurable: true
  3134. });
  3135. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  3136. };
  3137. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  3138. };
  3139. Tools._StartUserMark = function (counterName, condition) {
  3140. if (condition === void 0) { condition = true; }
  3141. if (!condition || !Tools._performance.mark) {
  3142. return;
  3143. }
  3144. Tools._performance.mark(counterName + "-Begin");
  3145. };
  3146. Tools._EndUserMark = function (counterName, condition) {
  3147. if (condition === void 0) { condition = true; }
  3148. if (!condition || !Tools._performance.mark) {
  3149. return;
  3150. }
  3151. Tools._performance.mark(counterName + "-End");
  3152. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  3153. };
  3154. Tools._StartPerformanceConsole = function (counterName, condition) {
  3155. if (condition === void 0) { condition = true; }
  3156. if (!condition) {
  3157. return;
  3158. }
  3159. Tools._StartUserMark(counterName, condition);
  3160. if (console.time) {
  3161. console.time(counterName);
  3162. }
  3163. };
  3164. Tools._EndPerformanceConsole = function (counterName, condition) {
  3165. if (condition === void 0) { condition = true; }
  3166. if (!condition) {
  3167. return;
  3168. }
  3169. Tools._EndUserMark(counterName, condition);
  3170. if (console.time) {
  3171. console.timeEnd(counterName);
  3172. }
  3173. };
  3174. Object.defineProperty(Tools, "Now", {
  3175. get: function () {
  3176. if (window.performance && window.performance.now) {
  3177. return window.performance.now();
  3178. }
  3179. return new Date().getTime();
  3180. },
  3181. enumerable: true,
  3182. configurable: true
  3183. });
  3184. // Deprecated
  3185. Tools.GetFps = function () {
  3186. Tools.Warn("Tools.GetFps() is deprecated. Please use engine.getFps() instead");
  3187. return 0;
  3188. };
  3189. Tools.BaseUrl = "";
  3190. Tools.GetExponantOfTwo = function (value, max) {
  3191. var count = 1;
  3192. do {
  3193. count *= 2;
  3194. } while (count < value);
  3195. if (count > max)
  3196. count = max;
  3197. return count;
  3198. };
  3199. // Logs
  3200. Tools._NoneLogLevel = 0;
  3201. Tools._MessageLogLevel = 1;
  3202. Tools._WarningLogLevel = 2;
  3203. Tools._ErrorLogLevel = 4;
  3204. Tools._LogCache = "";
  3205. Tools.Log = Tools._LogEnabled;
  3206. Tools.Warn = Tools._WarnEnabled;
  3207. Tools.Error = Tools._ErrorEnabled;
  3208. // Performances
  3209. Tools._PerformanceNoneLogLevel = 0;
  3210. Tools._PerformanceUserMarkLogLevel = 1;
  3211. Tools._PerformanceConsoleLogLevel = 2;
  3212. Tools._performance = window.performance;
  3213. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  3214. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  3215. return Tools;
  3216. })();
  3217. BABYLON.Tools = Tools;
  3218. /**
  3219. * An implementation of a loop for asynchronous functions.
  3220. */
  3221. var AsyncLoop = (function () {
  3222. /**
  3223. * Constroctor.
  3224. * @param iterations the number of iterations.
  3225. * @param _fn the function to run each iteration
  3226. * @param _successCallback the callback that will be called upon succesful execution
  3227. * @param offset starting offset.
  3228. */
  3229. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  3230. if (offset === void 0) { offset = 0; }
  3231. this.iterations = iterations;
  3232. this._fn = _fn;
  3233. this._successCallback = _successCallback;
  3234. this.index = offset - 1;
  3235. this._done = false;
  3236. }
  3237. /**
  3238. * Execute the next iteration. Must be called after the last iteration was finished.
  3239. */
  3240. AsyncLoop.prototype.executeNext = function () {
  3241. if (!this._done) {
  3242. if (this.index + 1 < this.iterations) {
  3243. ++this.index;
  3244. this._fn(this);
  3245. }
  3246. else {
  3247. this.breakLoop();
  3248. }
  3249. }
  3250. };
  3251. /**
  3252. * Break the loop and run the success callback.
  3253. */
  3254. AsyncLoop.prototype.breakLoop = function () {
  3255. this._done = true;
  3256. this._successCallback();
  3257. };
  3258. /**
  3259. * Helper function
  3260. */
  3261. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  3262. if (offset === void 0) { offset = 0; }
  3263. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  3264. loop.executeNext();
  3265. return loop;
  3266. };
  3267. /**
  3268. * A for-loop that will run a given number of iterations synchronous and the rest async.
  3269. * @param iterations total number of iterations
  3270. * @param syncedIterations number of synchronous iterations in each async iteration.
  3271. * @param fn the function to call each iteration.
  3272. * @param callback a success call back that will be called when iterating stops.
  3273. * @param breakFunction a break condition (optional)
  3274. * @param timeout timeout settings for the setTimeout function. default - 0.
  3275. * @constructor
  3276. */
  3277. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  3278. if (timeout === void 0) { timeout = 0; }
  3279. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  3280. if (breakFunction && breakFunction())
  3281. loop.breakLoop();
  3282. else {
  3283. setTimeout(function () {
  3284. for (var i = 0; i < syncedIterations; ++i) {
  3285. var iteration = (loop.index * syncedIterations) + i;
  3286. if (iteration >= iterations)
  3287. break;
  3288. fn(iteration);
  3289. if (breakFunction && breakFunction()) {
  3290. loop.breakLoop();
  3291. break;
  3292. }
  3293. }
  3294. loop.executeNext();
  3295. }, timeout);
  3296. }
  3297. }, callback);
  3298. };
  3299. return AsyncLoop;
  3300. })();
  3301. BABYLON.AsyncLoop = AsyncLoop;
  3302. })(BABYLON || (BABYLON = {}));
  3303. //# sourceMappingURL=babylon.tools.js.mapvar BABYLON;
  3304. (function (BABYLON) {
  3305. var _DepthCullingState = (function () {
  3306. function _DepthCullingState() {
  3307. this._isDepthTestDirty = false;
  3308. this._isDepthMaskDirty = false;
  3309. this._isDepthFuncDirty = false;
  3310. this._isCullFaceDirty = false;
  3311. this._isCullDirty = false;
  3312. }
  3313. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  3314. get: function () {
  3315. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty;
  3316. },
  3317. enumerable: true,
  3318. configurable: true
  3319. });
  3320. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  3321. get: function () {
  3322. return this._cullFace;
  3323. },
  3324. set: function (value) {
  3325. if (this._cullFace === value) {
  3326. return;
  3327. }
  3328. this._cullFace = value;
  3329. this._isCullFaceDirty = true;
  3330. },
  3331. enumerable: true,
  3332. configurable: true
  3333. });
  3334. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  3335. get: function () {
  3336. return this._cull;
  3337. },
  3338. set: function (value) {
  3339. if (this._cull === value) {
  3340. return;
  3341. }
  3342. this._cull = value;
  3343. this._isCullDirty = true;
  3344. },
  3345. enumerable: true,
  3346. configurable: true
  3347. });
  3348. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  3349. get: function () {
  3350. return this._depthFunc;
  3351. },
  3352. set: function (value) {
  3353. if (this._depthFunc === value) {
  3354. return;
  3355. }
  3356. this._depthFunc = value;
  3357. this._isDepthFuncDirty = true;
  3358. },
  3359. enumerable: true,
  3360. configurable: true
  3361. });
  3362. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  3363. get: function () {
  3364. return this._depthMask;
  3365. },
  3366. set: function (value) {
  3367. if (this._depthMask === value) {
  3368. return;
  3369. }
  3370. this._depthMask = value;
  3371. this._isDepthMaskDirty = true;
  3372. },
  3373. enumerable: true,
  3374. configurable: true
  3375. });
  3376. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  3377. get: function () {
  3378. return this._depthTest;
  3379. },
  3380. set: function (value) {
  3381. if (this._depthTest === value) {
  3382. return;
  3383. }
  3384. this._depthTest = value;
  3385. this._isDepthTestDirty = true;
  3386. },
  3387. enumerable: true,
  3388. configurable: true
  3389. });
  3390. _DepthCullingState.prototype.reset = function () {
  3391. this._depthMask = true;
  3392. this._depthTest = true;
  3393. this._depthFunc = null;
  3394. this._cull = null;
  3395. this._cullFace = null;
  3396. this._isDepthTestDirty = true;
  3397. this._isDepthMaskDirty = true;
  3398. this._isDepthFuncDirty = false;
  3399. this._isCullFaceDirty = false;
  3400. this._isCullDirty = false;
  3401. };
  3402. _DepthCullingState.prototype.apply = function (gl) {
  3403. if (!this.isDirty) {
  3404. return;
  3405. }
  3406. // Cull
  3407. if (this._isCullDirty) {
  3408. if (this.cull) {
  3409. gl.enable(gl.CULL_FACE);
  3410. }
  3411. else {
  3412. gl.disable(gl.CULL_FACE);
  3413. }
  3414. this._isCullDirty = false;
  3415. }
  3416. // Cull face
  3417. if (this._isCullFaceDirty) {
  3418. gl.cullFace(this.cullFace);
  3419. this._isCullFaceDirty = false;
  3420. }
  3421. // Depth mask
  3422. if (this._isDepthMaskDirty) {
  3423. gl.depthMask(this.depthMask);
  3424. this._isDepthMaskDirty = false;
  3425. }
  3426. // Depth test
  3427. if (this._isDepthTestDirty) {
  3428. if (this.depthTest) {
  3429. gl.enable(gl.DEPTH_TEST);
  3430. }
  3431. else {
  3432. gl.disable(gl.DEPTH_TEST);
  3433. }
  3434. this._isDepthTestDirty = false;
  3435. }
  3436. // Depth func
  3437. if (this._isDepthFuncDirty) {
  3438. gl.depthFunc(this.depthFunc);
  3439. this._isDepthFuncDirty = false;
  3440. }
  3441. };
  3442. return _DepthCullingState;
  3443. })();
  3444. BABYLON._DepthCullingState = _DepthCullingState;
  3445. var _AlphaState = (function () {
  3446. function _AlphaState() {
  3447. this._isAlphaBlendDirty = false;
  3448. this._isBlendFunctionParametersDirty = false;
  3449. this._alphaBlend = false;
  3450. this._blendFunctionParameters = new Array(4);
  3451. }
  3452. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  3453. get: function () {
  3454. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  3455. },
  3456. enumerable: true,
  3457. configurable: true
  3458. });
  3459. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  3460. get: function () {
  3461. return this._alphaBlend;
  3462. },
  3463. set: function (value) {
  3464. if (this._alphaBlend === value) {
  3465. return;
  3466. }
  3467. this._alphaBlend = value;
  3468. this._isAlphaBlendDirty = true;
  3469. },
  3470. enumerable: true,
  3471. configurable: true
  3472. });
  3473. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  3474. if (this._blendFunctionParameters[0] === value0 && this._blendFunctionParameters[1] === value1 && this._blendFunctionParameters[2] === value2 && this._blendFunctionParameters[3] === value3) {
  3475. return;
  3476. }
  3477. this._blendFunctionParameters[0] = value0;
  3478. this._blendFunctionParameters[1] = value1;
  3479. this._blendFunctionParameters[2] = value2;
  3480. this._blendFunctionParameters[3] = value3;
  3481. this._isBlendFunctionParametersDirty = true;
  3482. };
  3483. _AlphaState.prototype.reset = function () {
  3484. this._alphaBlend = false;
  3485. this._blendFunctionParameters[0] = null;
  3486. this._blendFunctionParameters[1] = null;
  3487. this._blendFunctionParameters[2] = null;
  3488. this._blendFunctionParameters[3] = null;
  3489. this._isAlphaBlendDirty = true;
  3490. this._isBlendFunctionParametersDirty = false;
  3491. };
  3492. _AlphaState.prototype.apply = function (gl) {
  3493. if (!this.isDirty) {
  3494. return;
  3495. }
  3496. // Alpha blend
  3497. if (this._isAlphaBlendDirty) {
  3498. if (this._alphaBlend) {
  3499. gl.enable(gl.BLEND);
  3500. }
  3501. else {
  3502. gl.disable(gl.BLEND);
  3503. }
  3504. this._isAlphaBlendDirty = false;
  3505. }
  3506. // Alpha function
  3507. if (this._isBlendFunctionParametersDirty) {
  3508. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  3509. this._isBlendFunctionParametersDirty = false;
  3510. }
  3511. };
  3512. return _AlphaState;
  3513. })();
  3514. BABYLON._AlphaState = _AlphaState;
  3515. var compileShader = function (gl, source, type, defines) {
  3516. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  3517. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  3518. gl.compileShader(shader);
  3519. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  3520. throw new Error(gl.getShaderInfoLog(shader));
  3521. }
  3522. return shader;
  3523. };
  3524. var getWebGLTextureType = function (gl, type) {
  3525. var textureType = gl.UNSIGNED_BYTE;
  3526. if (type === Engine.TEXTURETYPE_FLOAT)
  3527. textureType = gl.FLOAT;
  3528. return textureType;
  3529. };
  3530. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  3531. var magFilter = gl.NEAREST;
  3532. var minFilter = gl.NEAREST;
  3533. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  3534. magFilter = gl.LINEAR;
  3535. if (generateMipMaps) {
  3536. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  3537. }
  3538. else {
  3539. minFilter = gl.LINEAR;
  3540. }
  3541. }
  3542. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  3543. magFilter = gl.LINEAR;
  3544. if (generateMipMaps) {
  3545. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  3546. }
  3547. else {
  3548. minFilter = gl.LINEAR;
  3549. }
  3550. }
  3551. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  3552. magFilter = gl.NEAREST;
  3553. if (generateMipMaps) {
  3554. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  3555. }
  3556. else {
  3557. minFilter = gl.NEAREST;
  3558. }
  3559. }
  3560. return {
  3561. min: minFilter,
  3562. mag: magFilter
  3563. };
  3564. };
  3565. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  3566. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  3567. var engine = scene.getEngine();
  3568. var potWidth = BABYLON.Tools.GetExponantOfTwo(width, engine.getCaps().maxTextureSize);
  3569. var potHeight = BABYLON.Tools.GetExponantOfTwo(height, engine.getCaps().maxTextureSize);
  3570. gl.bindTexture(gl.TEXTURE_2D, texture);
  3571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  3572. processFunction(potWidth, potHeight);
  3573. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  3574. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  3575. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  3576. if (!noMipmap && !isCompressed) {
  3577. gl.generateMipmap(gl.TEXTURE_2D);
  3578. }
  3579. gl.bindTexture(gl.TEXTURE_2D, null);
  3580. engine._activeTexturesCache = [];
  3581. texture._baseWidth = width;
  3582. texture._baseHeight = height;
  3583. texture._width = potWidth;
  3584. texture._height = potHeight;
  3585. texture.isReady = true;
  3586. texture.samplingMode = samplingMode;
  3587. scene._removePendingData(texture);
  3588. };
  3589. var partialLoad = function (url, index, loadedImages, scene, onfinish) {
  3590. var onload = function () {
  3591. loadedImages[index] = img;
  3592. loadedImages._internalCount++;
  3593. scene._removePendingData(img);
  3594. if (loadedImages._internalCount === 6) {
  3595. onfinish(loadedImages);
  3596. }
  3597. };
  3598. var onerror = function () {
  3599. scene._removePendingData(img);
  3600. };
  3601. var img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  3602. scene._addPendingData(img);
  3603. };
  3604. var cascadeLoad = function (rootUrl, scene, onfinish, extensions) {
  3605. var loadedImages = [];
  3606. loadedImages._internalCount = 0;
  3607. for (var index = 0; index < 6; index++) {
  3608. partialLoad(rootUrl + extensions[index], index, loadedImages, scene, onfinish);
  3609. }
  3610. };
  3611. var EngineCapabilities = (function () {
  3612. function EngineCapabilities() {
  3613. }
  3614. return EngineCapabilities;
  3615. })();
  3616. BABYLON.EngineCapabilities = EngineCapabilities;
  3617. /**
  3618. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  3619. */
  3620. var Engine = (function () {
  3621. /**
  3622. * @constructor
  3623. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  3624. * @param {boolean} [antialias] - enable antialias
  3625. * @param options - further options to be sent to the getContext function
  3626. */
  3627. function Engine(canvas, antialias, options) {
  3628. var _this = this;
  3629. // Public members
  3630. this.isFullscreen = false;
  3631. this.isPointerLock = false;
  3632. this.cullBackFaces = true;
  3633. this.renderEvenInBackground = true;
  3634. this.scenes = new Array();
  3635. this._windowIsBackground = false;
  3636. this._loadingDivBackgroundColor = "black";
  3637. this._drawCalls = 0;
  3638. this._renderingQueueLaunched = false;
  3639. this._activeRenderLoops = [];
  3640. // FPS
  3641. this.fpsRange = 60;
  3642. this.previousFramesDuration = [];
  3643. this.fps = 60;
  3644. this.deltaTime = 0;
  3645. // States
  3646. this._depthCullingState = new _DepthCullingState();
  3647. this._alphaState = new _AlphaState();
  3648. this._alphaMode = Engine.ALPHA_DISABLE;
  3649. // Cache
  3650. this._loadedTexturesCache = new Array();
  3651. this._activeTexturesCache = new Array();
  3652. this._compiledEffects = {};
  3653. this._uintIndicesCurrentlySet = false;
  3654. this._renderingCanvas = canvas;
  3655. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  3656. options = options || {};
  3657. options.antialias = antialias;
  3658. try {
  3659. this._gl = canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options);
  3660. }
  3661. catch (e) {
  3662. throw new Error("WebGL not supported");
  3663. }
  3664. if (!this._gl) {
  3665. throw new Error("WebGL not supported");
  3666. }
  3667. this._onBlur = function () {
  3668. _this._windowIsBackground = true;
  3669. };
  3670. this._onFocus = function () {
  3671. _this._windowIsBackground = false;
  3672. };
  3673. window.addEventListener("blur", this._onBlur);
  3674. window.addEventListener("focus", this._onFocus);
  3675. // Textures
  3676. this._workingCanvas = document.createElement("canvas");
  3677. this._workingContext = this._workingCanvas.getContext("2d");
  3678. // Viewport
  3679. this._hardwareScalingLevel = 1.0 / (window.devicePixelRatio || 1.0);
  3680. this.resize();
  3681. // Caps
  3682. this._caps = new EngineCapabilities();
  3683. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  3684. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  3685. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  3686. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  3687. // Infos
  3688. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  3689. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  3690. if (rendererInfo != null) {
  3691. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  3692. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  3693. }
  3694. if (!this._glVendor) {
  3695. this._glVendor = "Unknown vendor";
  3696. }
  3697. if (!this._glRenderer) {
  3698. this._glRenderer = "Unknown renderer";
  3699. }
  3700. // Extensions
  3701. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  3702. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  3703. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  3704. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  3705. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  3706. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  3707. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  3708. // Depth buffer
  3709. this.setDepthBuffer(true);
  3710. this.setDepthFunctionToLessOrEqual();
  3711. this.setDepthWrite(true);
  3712. // Fullscreen
  3713. this._onFullscreenChange = function () {
  3714. if (document.fullscreen !== undefined) {
  3715. _this.isFullscreen = document.fullscreen;
  3716. }
  3717. else if (document.mozFullScreen !== undefined) {
  3718. _this.isFullscreen = document.mozFullScreen;
  3719. }
  3720. else if (document.webkitIsFullScreen !== undefined) {
  3721. _this.isFullscreen = document.webkitIsFullScreen;
  3722. }
  3723. else if (document.msIsFullScreen !== undefined) {
  3724. _this.isFullscreen = document.msIsFullScreen;
  3725. }
  3726. // Pointer lock
  3727. if (_this.isFullscreen && _this._pointerLockRequested) {
  3728. canvas.requestPointerLock = canvas.requestPointerLock || canvas.msRequestPointerLock || canvas.mozRequestPointerLock || canvas.webkitRequestPointerLock;
  3729. if (canvas.requestPointerLock) {
  3730. canvas.requestPointerLock();
  3731. }
  3732. }
  3733. };
  3734. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  3735. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  3736. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  3737. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  3738. // Pointer lock
  3739. this._onPointerLockChange = function () {
  3740. _this.isPointerLock = (document.mozPointerLockElement === canvas || document.webkitPointerLockElement === canvas || document.msPointerLockElement === canvas || document.pointerLockElement === canvas);
  3741. };
  3742. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  3743. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  3744. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  3745. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  3746. if (!Engine.audioEngine) {
  3747. Engine.audioEngine = new BABYLON.AudioEngine();
  3748. }
  3749. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  3750. }
  3751. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  3752. get: function () {
  3753. return Engine._ALPHA_DISABLE;
  3754. },
  3755. enumerable: true,
  3756. configurable: true
  3757. });
  3758. Object.defineProperty(Engine, "ALPHA_ADD", {
  3759. get: function () {
  3760. return Engine._ALPHA_ADD;
  3761. },
  3762. enumerable: true,
  3763. configurable: true
  3764. });
  3765. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  3766. get: function () {
  3767. return Engine._ALPHA_COMBINE;
  3768. },
  3769. enumerable: true,
  3770. configurable: true
  3771. });
  3772. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  3773. get: function () {
  3774. return Engine._DELAYLOADSTATE_NONE;
  3775. },
  3776. enumerable: true,
  3777. configurable: true
  3778. });
  3779. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  3780. get: function () {
  3781. return Engine._DELAYLOADSTATE_LOADED;
  3782. },
  3783. enumerable: true,
  3784. configurable: true
  3785. });
  3786. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  3787. get: function () {
  3788. return Engine._DELAYLOADSTATE_LOADING;
  3789. },
  3790. enumerable: true,
  3791. configurable: true
  3792. });
  3793. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  3794. get: function () {
  3795. return Engine._DELAYLOADSTATE_NOTLOADED;
  3796. },
  3797. enumerable: true,
  3798. configurable: true
  3799. });
  3800. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  3801. get: function () {
  3802. return Engine._TEXTUREFORMAT_ALPHA;
  3803. },
  3804. enumerable: true,
  3805. configurable: true
  3806. });
  3807. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  3808. get: function () {
  3809. return Engine._TEXTUREFORMAT_LUMINANCE;
  3810. },
  3811. enumerable: true,
  3812. configurable: true
  3813. });
  3814. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  3815. get: function () {
  3816. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  3817. },
  3818. enumerable: true,
  3819. configurable: true
  3820. });
  3821. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  3822. get: function () {
  3823. return Engine._TEXTUREFORMAT_RGB;
  3824. },
  3825. enumerable: true,
  3826. configurable: true
  3827. });
  3828. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  3829. get: function () {
  3830. return Engine._TEXTUREFORMAT_RGBA;
  3831. },
  3832. enumerable: true,
  3833. configurable: true
  3834. });
  3835. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  3836. get: function () {
  3837. return Engine._TEXTURETYPE_UNSIGNED_INT;
  3838. },
  3839. enumerable: true,
  3840. configurable: true
  3841. });
  3842. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  3843. get: function () {
  3844. return Engine._TEXTURETYPE_FLOAT;
  3845. },
  3846. enumerable: true,
  3847. configurable: true
  3848. });
  3849. Object.defineProperty(Engine, "Version", {
  3850. get: function () {
  3851. return "2.0.0";
  3852. },
  3853. enumerable: true,
  3854. configurable: true
  3855. });
  3856. Engine.prototype.getGlInfo = function () {
  3857. return {
  3858. vendor: this._glVendor,
  3859. renderer: this._glRenderer,
  3860. version: this._glVersion
  3861. };
  3862. };
  3863. Engine.prototype.getAspectRatio = function (camera) {
  3864. var viewport = camera.viewport;
  3865. return (this.getRenderWidth() * viewport.width) / (this.getRenderHeight() * viewport.height);
  3866. };
  3867. Engine.prototype.getRenderWidth = function () {
  3868. if (this._currentRenderTarget) {
  3869. return this._currentRenderTarget._width;
  3870. }
  3871. return this._renderingCanvas.width;
  3872. };
  3873. Engine.prototype.getRenderHeight = function () {
  3874. if (this._currentRenderTarget) {
  3875. return this._currentRenderTarget._height;
  3876. }
  3877. return this._renderingCanvas.height;
  3878. };
  3879. Engine.prototype.getRenderingCanvas = function () {
  3880. return this._renderingCanvas;
  3881. };
  3882. Engine.prototype.getRenderingCanvasClientRect = function () {
  3883. return this._renderingCanvas.getBoundingClientRect();
  3884. };
  3885. Engine.prototype.setHardwareScalingLevel = function (level) {
  3886. this._hardwareScalingLevel = level;
  3887. this.resize();
  3888. };
  3889. Engine.prototype.getHardwareScalingLevel = function () {
  3890. return this._hardwareScalingLevel;
  3891. };
  3892. Engine.prototype.getLoadedTexturesCache = function () {
  3893. return this._loadedTexturesCache;
  3894. };
  3895. Engine.prototype.getCaps = function () {
  3896. return this._caps;
  3897. };
  3898. Object.defineProperty(Engine.prototype, "drawCalls", {
  3899. get: function () {
  3900. return this._drawCalls;
  3901. },
  3902. enumerable: true,
  3903. configurable: true
  3904. });
  3905. // Methods
  3906. Engine.prototype.resetDrawCalls = function () {
  3907. this._drawCalls = 0;
  3908. };
  3909. Engine.prototype.setDepthFunctionToGreater = function () {
  3910. this._depthCullingState.depthFunc = this._gl.GREATER;
  3911. };
  3912. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  3913. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  3914. };
  3915. Engine.prototype.setDepthFunctionToLess = function () {
  3916. this._depthCullingState.depthFunc = this._gl.LESS;
  3917. };
  3918. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  3919. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  3920. };
  3921. /**
  3922. * stop executing a render loop function and remove it from the execution array
  3923. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  3924. */
  3925. Engine.prototype.stopRenderLoop = function (renderFunction) {
  3926. if (!renderFunction) {
  3927. this._activeRenderLoops = [];
  3928. return;
  3929. }
  3930. var index = this._activeRenderLoops.indexOf(renderFunction);
  3931. if (index >= 0) {
  3932. this._activeRenderLoops.splice(index, 1);
  3933. }
  3934. };
  3935. Engine.prototype._renderLoop = function () {
  3936. var _this = this;
  3937. var shouldRender = true;
  3938. if (!this.renderEvenInBackground && this._windowIsBackground) {
  3939. shouldRender = false;
  3940. }
  3941. if (shouldRender) {
  3942. // Start new frame
  3943. this.beginFrame();
  3944. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  3945. var renderFunction = this._activeRenderLoops[index];
  3946. renderFunction();
  3947. }
  3948. // Present
  3949. this.endFrame();
  3950. }
  3951. if (this._activeRenderLoops.length > 0) {
  3952. // Register new frame
  3953. BABYLON.Tools.QueueNewFrame(function () {
  3954. _this._renderLoop();
  3955. });
  3956. }
  3957. else {
  3958. this._renderingQueueLaunched = false;
  3959. }
  3960. };
  3961. /**
  3962. * Register and execute a render loop. The engine can have more than one render function.
  3963. * @param {Function} renderFunction - the function to continuesly execute starting the next render loop.
  3964. * @example
  3965. * engine.runRenderLoop(function () {
  3966. * scene.render()
  3967. * })
  3968. */
  3969. Engine.prototype.runRenderLoop = function (renderFunction) {
  3970. var _this = this;
  3971. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  3972. return;
  3973. }
  3974. this._activeRenderLoops.push(renderFunction);
  3975. if (!this._renderingQueueLaunched) {
  3976. this._renderingQueueLaunched = true;
  3977. BABYLON.Tools.QueueNewFrame(function () {
  3978. _this._renderLoop();
  3979. });
  3980. }
  3981. };
  3982. /**
  3983. * Toggle full screen mode.
  3984. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  3985. */
  3986. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  3987. if (this.isFullscreen) {
  3988. BABYLON.Tools.ExitFullscreen();
  3989. }
  3990. else {
  3991. this._pointerLockRequested = requestPointerLock;
  3992. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  3993. }
  3994. };
  3995. Engine.prototype.clear = function (color, backBuffer, depthStencil) {
  3996. this.applyStates();
  3997. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  3998. if (this._depthCullingState.depthMask) {
  3999. this._gl.clearDepth(1.0);
  4000. }
  4001. var mode = 0;
  4002. if (backBuffer)
  4003. mode |= this._gl.COLOR_BUFFER_BIT;
  4004. if (depthStencil && this._depthCullingState.depthMask)
  4005. mode |= this._gl.DEPTH_BUFFER_BIT;
  4006. this._gl.clear(mode);
  4007. };
  4008. /**
  4009. * Set the WebGL's viewport
  4010. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  4011. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  4012. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  4013. */
  4014. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  4015. var width = requiredWidth || this._renderingCanvas.width;
  4016. var height = requiredHeight || this._renderingCanvas.height;
  4017. var x = viewport.x || 0;
  4018. var y = viewport.y || 0;
  4019. this._cachedViewport = viewport;
  4020. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  4021. };
  4022. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  4023. this._cachedViewport = null;
  4024. this._gl.viewport(x, y, width, height);
  4025. };
  4026. Engine.prototype.beginFrame = function () {
  4027. this._measureFps();
  4028. };
  4029. Engine.prototype.endFrame = function () {
  4030. //this.flushFramebuffer();
  4031. };
  4032. /**
  4033. * resize the view according to the canvas' size.
  4034. * @example
  4035. * window.addEventListener("resize", function () {
  4036. * engine.resize();
  4037. * });
  4038. */
  4039. Engine.prototype.resize = function () {
  4040. this.setSize(this._renderingCanvas.clientWidth / this._hardwareScalingLevel, this._renderingCanvas.clientHeight / this._hardwareScalingLevel);
  4041. };
  4042. /**
  4043. * force a specific size of the canvas
  4044. * @param {number} width - the new canvas' width
  4045. * @param {number} height - the new canvas' height
  4046. */
  4047. Engine.prototype.setSize = function (width, height) {
  4048. this._renderingCanvas.width = width;
  4049. this._renderingCanvas.height = height;
  4050. this._canvasClientRect = this._renderingCanvas.getBoundingClientRect();
  4051. };
  4052. Engine.prototype.bindFramebuffer = function (texture) {
  4053. this._currentRenderTarget = texture;
  4054. var gl = this._gl;
  4055. gl.bindFramebuffer(gl.FRAMEBUFFER, texture._framebuffer);
  4056. this._gl.viewport(0, 0, texture._width, texture._height);
  4057. this.wipeCaches();
  4058. };
  4059. Engine.prototype.unBindFramebuffer = function (texture) {
  4060. this._currentRenderTarget = null;
  4061. if (texture.generateMipMaps) {
  4062. var gl = this._gl;
  4063. gl.bindTexture(gl.TEXTURE_2D, texture);
  4064. gl.generateMipmap(gl.TEXTURE_2D);
  4065. gl.bindTexture(gl.TEXTURE_2D, null);
  4066. }
  4067. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4068. };
  4069. Engine.prototype.flushFramebuffer = function () {
  4070. this._gl.flush();
  4071. };
  4072. Engine.prototype.restoreDefaultFramebuffer = function () {
  4073. this._currentRenderTarget = null;
  4074. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
  4075. this.setViewport(this._cachedViewport);
  4076. this.wipeCaches();
  4077. };
  4078. // VBOs
  4079. Engine.prototype._resetVertexBufferBinding = function () {
  4080. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, null);
  4081. this._cachedVertexBuffers = null;
  4082. };
  4083. Engine.prototype.createVertexBuffer = function (vertices) {
  4084. var vbo = this._gl.createBuffer();
  4085. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4086. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  4087. this._resetVertexBufferBinding();
  4088. vbo.references = 1;
  4089. return vbo;
  4090. };
  4091. Engine.prototype.createDynamicVertexBuffer = function (capacity) {
  4092. var vbo = this._gl.createBuffer();
  4093. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vbo);
  4094. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4095. this._resetVertexBufferBinding();
  4096. vbo.references = 1;
  4097. return vbo;
  4098. };
  4099. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset) {
  4100. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4101. if (offset === undefined) {
  4102. offset = 0;
  4103. }
  4104. if (vertices instanceof Float32Array) {
  4105. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  4106. }
  4107. else {
  4108. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  4109. }
  4110. this._resetVertexBufferBinding();
  4111. };
  4112. Engine.prototype._resetIndexBufferBinding = function () {
  4113. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, null);
  4114. this._cachedIndexBuffer = null;
  4115. };
  4116. Engine.prototype.createIndexBuffer = function (indices) {
  4117. var vbo = this._gl.createBuffer();
  4118. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, vbo);
  4119. // Check for 32 bits indices
  4120. var arrayBuffer;
  4121. var need32Bits = false;
  4122. if (this._caps.uintIndices) {
  4123. for (var index = 0; index < indices.length; index++) {
  4124. if (indices[index] > 65535) {
  4125. need32Bits = true;
  4126. break;
  4127. }
  4128. }
  4129. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  4130. }
  4131. else {
  4132. arrayBuffer = new Uint16Array(indices);
  4133. }
  4134. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  4135. this._resetIndexBufferBinding();
  4136. vbo.references = 1;
  4137. vbo.is32Bits = need32Bits;
  4138. return vbo;
  4139. };
  4140. Engine.prototype.bindBuffers = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  4141. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  4142. this._cachedVertexBuffers = vertexBuffer;
  4143. this._cachedEffectForVertexBuffers = effect;
  4144. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer);
  4145. var offset = 0;
  4146. for (var index = 0; index < vertexDeclaration.length; index++) {
  4147. var order = effect.getAttributeLocation(index);
  4148. if (order >= 0) {
  4149. this._gl.vertexAttribPointer(order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  4150. }
  4151. offset += vertexDeclaration[index] * 4;
  4152. }
  4153. }
  4154. if (this._cachedIndexBuffer !== indexBuffer) {
  4155. this._cachedIndexBuffer = indexBuffer;
  4156. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4157. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4158. }
  4159. };
  4160. Engine.prototype.bindMultiBuffers = function (vertexBuffers, indexBuffer, effect) {
  4161. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  4162. this._cachedVertexBuffers = vertexBuffers;
  4163. this._cachedEffectForVertexBuffers = effect;
  4164. var attributes = effect.getAttributesNames();
  4165. for (var index = 0; index < attributes.length; index++) {
  4166. var order = effect.getAttributeLocation(index);
  4167. if (order >= 0) {
  4168. var vertexBuffer = vertexBuffers[attributes[index]];
  4169. if (!vertexBuffer) {
  4170. continue;
  4171. }
  4172. var stride = vertexBuffer.getStrideSize();
  4173. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, vertexBuffer.getBuffer());
  4174. this._gl.vertexAttribPointer(order, stride, this._gl.FLOAT, false, stride * 4, 0);
  4175. }
  4176. }
  4177. }
  4178. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  4179. this._cachedIndexBuffer = indexBuffer;
  4180. this._gl.bindBuffer(this._gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
  4181. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  4182. }
  4183. };
  4184. Engine.prototype._releaseBuffer = function (buffer) {
  4185. buffer.references--;
  4186. if (buffer.references === 0) {
  4187. this._gl.deleteBuffer(buffer);
  4188. return true;
  4189. }
  4190. return false;
  4191. };
  4192. Engine.prototype.createInstancesBuffer = function (capacity) {
  4193. var buffer = this._gl.createBuffer();
  4194. buffer.capacity = capacity;
  4195. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, buffer);
  4196. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  4197. return buffer;
  4198. };
  4199. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  4200. this._gl.deleteBuffer(buffer);
  4201. };
  4202. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  4203. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4204. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  4205. for (var index = 0; index < 4; index++) {
  4206. var offsetLocation = offsetLocations[index];
  4207. this._gl.enableVertexAttribArray(offsetLocation);
  4208. this._gl.vertexAttribPointer(offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  4209. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  4210. }
  4211. };
  4212. Engine.prototype.unBindInstancesBuffer = function (instancesBuffer, offsetLocations) {
  4213. this._gl.bindBuffer(this._gl.ARRAY_BUFFER, instancesBuffer);
  4214. for (var index = 0; index < 4; index++) {
  4215. var offsetLocation = offsetLocations[index];
  4216. this._gl.disableVertexAttribArray(offsetLocation);
  4217. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  4218. }
  4219. };
  4220. Engine.prototype.applyStates = function () {
  4221. this._depthCullingState.apply(this._gl);
  4222. this._alphaState.apply(this._gl);
  4223. };
  4224. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  4225. // Apply states
  4226. this.applyStates();
  4227. this._drawCalls++;
  4228. // Render
  4229. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  4230. if (instancesCount) {
  4231. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2, instancesCount);
  4232. return;
  4233. }
  4234. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * 2);
  4235. };
  4236. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  4237. // Apply states
  4238. this.applyStates();
  4239. this._drawCalls++;
  4240. if (instancesCount) {
  4241. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  4242. return;
  4243. }
  4244. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  4245. };
  4246. // Shaders
  4247. Engine.prototype._releaseEffect = function (effect) {
  4248. if (this._compiledEffects[effect._key]) {
  4249. delete this._compiledEffects[effect._key];
  4250. if (effect.getProgram()) {
  4251. this._gl.deleteProgram(effect.getProgram());
  4252. }
  4253. }
  4254. };
  4255. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4256. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  4257. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  4258. var name = vertex + "+" + fragment + "@" + defines;
  4259. if (this._compiledEffects[name]) {
  4260. return this._compiledEffects[name];
  4261. }
  4262. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError);
  4263. effect._key = name;
  4264. this._compiledEffects[name] = effect;
  4265. return effect;
  4266. };
  4267. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  4268. if (uniformsNames === void 0) { uniformsNames = []; }
  4269. if (samplers === void 0) { samplers = []; }
  4270. if (defines === void 0) { defines = ""; }
  4271. return this.createEffect({
  4272. vertex: "particles",
  4273. fragmentElement: fragmentName
  4274. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  4275. };
  4276. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines) {
  4277. var vertexShader = compileShader(this._gl, vertexCode, "vertex", defines);
  4278. var fragmentShader = compileShader(this._gl, fragmentCode, "fragment", defines);
  4279. var shaderProgram = this._gl.createProgram();
  4280. this._gl.attachShader(shaderProgram, vertexShader);
  4281. this._gl.attachShader(shaderProgram, fragmentShader);
  4282. this._gl.linkProgram(shaderProgram);
  4283. var linked = this._gl.getProgramParameter(shaderProgram, this._gl.LINK_STATUS);
  4284. if (!linked) {
  4285. var error = this._gl.getProgramInfoLog(shaderProgram);
  4286. if (error) {
  4287. throw new Error(error);
  4288. }
  4289. }
  4290. this._gl.deleteShader(vertexShader);
  4291. this._gl.deleteShader(fragmentShader);
  4292. return shaderProgram;
  4293. };
  4294. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  4295. var results = [];
  4296. for (var index = 0; index < uniformsNames.length; index++) {
  4297. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  4298. }
  4299. return results;
  4300. };
  4301. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  4302. var results = [];
  4303. for (var index = 0; index < attributesNames.length; index++) {
  4304. try {
  4305. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  4306. }
  4307. catch (e) {
  4308. results.push(-1);
  4309. }
  4310. }
  4311. return results;
  4312. };
  4313. Engine.prototype.enableEffect = function (effect) {
  4314. if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  4315. if (effect && effect.onBind) {
  4316. effect.onBind(effect);
  4317. }
  4318. return;
  4319. }
  4320. this._vertexAttribArrays = this._vertexAttribArrays || [];
  4321. // Use program
  4322. this._gl.useProgram(effect.getProgram());
  4323. for (var i in this._vertexAttribArrays) {
  4324. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4325. continue;
  4326. }
  4327. this._vertexAttribArrays[i] = false;
  4328. this._gl.disableVertexAttribArray(i);
  4329. }
  4330. var attributesCount = effect.getAttributesCount();
  4331. for (var index = 0; index < attributesCount; index++) {
  4332. // Attributes
  4333. var order = effect.getAttributeLocation(index);
  4334. if (order >= 0) {
  4335. this._vertexAttribArrays[order] = true;
  4336. this._gl.enableVertexAttribArray(order);
  4337. }
  4338. }
  4339. this._currentEffect = effect;
  4340. if (effect.onBind) {
  4341. effect.onBind(effect);
  4342. }
  4343. };
  4344. Engine.prototype.setArray = function (uniform, array) {
  4345. if (!uniform)
  4346. return;
  4347. this._gl.uniform1fv(uniform, array);
  4348. };
  4349. Engine.prototype.setArray2 = function (uniform, array) {
  4350. if (!uniform || array.length % 2 !== 0)
  4351. return;
  4352. this._gl.uniform2fv(uniform, array);
  4353. };
  4354. Engine.prototype.setArray3 = function (uniform, array) {
  4355. if (!uniform || array.length % 3 !== 0)
  4356. return;
  4357. this._gl.uniform3fv(uniform, array);
  4358. };
  4359. Engine.prototype.setArray4 = function (uniform, array) {
  4360. if (!uniform || array.length % 4 !== 0)
  4361. return;
  4362. this._gl.uniform4fv(uniform, array);
  4363. };
  4364. Engine.prototype.setMatrices = function (uniform, matrices) {
  4365. if (!uniform)
  4366. return;
  4367. this._gl.uniformMatrix4fv(uniform, false, matrices);
  4368. };
  4369. Engine.prototype.setMatrix = function (uniform, matrix) {
  4370. if (!uniform)
  4371. return;
  4372. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  4373. };
  4374. Engine.prototype.setFloat = function (uniform, value) {
  4375. if (!uniform)
  4376. return;
  4377. this._gl.uniform1f(uniform, value);
  4378. };
  4379. Engine.prototype.setFloat2 = function (uniform, x, y) {
  4380. if (!uniform)
  4381. return;
  4382. this._gl.uniform2f(uniform, x, y);
  4383. };
  4384. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  4385. if (!uniform)
  4386. return;
  4387. this._gl.uniform3f(uniform, x, y, z);
  4388. };
  4389. Engine.prototype.setBool = function (uniform, bool) {
  4390. if (!uniform)
  4391. return;
  4392. this._gl.uniform1i(uniform, bool);
  4393. };
  4394. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  4395. if (!uniform)
  4396. return;
  4397. this._gl.uniform4f(uniform, x, y, z, w);
  4398. };
  4399. Engine.prototype.setColor3 = function (uniform, color3) {
  4400. if (!uniform)
  4401. return;
  4402. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  4403. };
  4404. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  4405. if (!uniform)
  4406. return;
  4407. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  4408. };
  4409. // States
  4410. Engine.prototype.setState = function (culling, force) {
  4411. // Culling
  4412. if (this._depthCullingState.cull !== culling || force) {
  4413. if (culling) {
  4414. this._depthCullingState.cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  4415. this._depthCullingState.cull = true;
  4416. }
  4417. else {
  4418. this._depthCullingState.cull = false;
  4419. }
  4420. }
  4421. };
  4422. Engine.prototype.setDepthBuffer = function (enable) {
  4423. this._depthCullingState.depthTest = enable;
  4424. };
  4425. Engine.prototype.getDepthWrite = function () {
  4426. return this._depthCullingState.depthMask;
  4427. };
  4428. Engine.prototype.setDepthWrite = function (enable) {
  4429. this._depthCullingState.depthMask = enable;
  4430. };
  4431. Engine.prototype.setColorWrite = function (enable) {
  4432. this._gl.colorMask(enable, enable, enable, enable);
  4433. };
  4434. Engine.prototype.setAlphaMode = function (mode) {
  4435. switch (mode) {
  4436. case Engine.ALPHA_DISABLE:
  4437. this.setDepthWrite(true);
  4438. this._alphaState.alphaBlend = false;
  4439. break;
  4440. case Engine.ALPHA_COMBINE:
  4441. this.setDepthWrite(false);
  4442. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  4443. this._alphaState.alphaBlend = true;
  4444. break;
  4445. case Engine.ALPHA_ADD:
  4446. this.setDepthWrite(false);
  4447. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  4448. this._alphaState.alphaBlend = true;
  4449. break;
  4450. }
  4451. this._alphaMode = mode;
  4452. };
  4453. Engine.prototype.getAlphaMode = function () {
  4454. return this._alphaMode;
  4455. };
  4456. Engine.prototype.setAlphaTesting = function (enable) {
  4457. this._alphaTest = enable;
  4458. };
  4459. Engine.prototype.getAlphaTesting = function () {
  4460. return this._alphaTest;
  4461. };
  4462. // Textures
  4463. Engine.prototype.wipeCaches = function () {
  4464. this._activeTexturesCache = [];
  4465. this._currentEffect = null;
  4466. this._depthCullingState.reset();
  4467. this._alphaState.reset();
  4468. this._cachedVertexBuffers = null;
  4469. this._cachedIndexBuffer = null;
  4470. this._cachedEffectForVertexBuffers = null;
  4471. };
  4472. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  4473. var gl = this._gl;
  4474. gl.bindTexture(gl.TEXTURE_2D, texture);
  4475. var magFilter = gl.NEAREST;
  4476. var minFilter = gl.NEAREST;
  4477. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  4478. magFilter = gl.LINEAR;
  4479. minFilter = gl.LINEAR;
  4480. }
  4481. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  4482. magFilter = gl.LINEAR;
  4483. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  4484. }
  4485. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  4486. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  4487. gl.bindTexture(gl.TEXTURE_2D, null);
  4488. texture.samplingMode = samplingMode;
  4489. };
  4490. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  4491. var _this = this;
  4492. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  4493. if (onLoad === void 0) { onLoad = null; }
  4494. if (onError === void 0) { onError = null; }
  4495. if (buffer === void 0) { buffer = null; }
  4496. var texture = this._gl.createTexture();
  4497. var extension;
  4498. var fromData = false;
  4499. if (url.substr(0, 5) === "data:") {
  4500. fromData = true;
  4501. }
  4502. if (!fromData)
  4503. extension = url.substr(url.length - 4, 4).toLowerCase();
  4504. else {
  4505. var oldUrl = url;
  4506. fromData = oldUrl.split(':');
  4507. url = oldUrl;
  4508. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  4509. }
  4510. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4511. var isTGA = (extension === ".tga");
  4512. scene._addPendingData(texture);
  4513. texture.url = url;
  4514. texture.noMipmap = noMipmap;
  4515. texture.references = 1;
  4516. this._loadedTexturesCache.push(texture);
  4517. var onerror = function () {
  4518. scene._removePendingData(texture);
  4519. if (onError) {
  4520. onError();
  4521. }
  4522. };
  4523. if (isTGA) {
  4524. var callback = function (arrayBuffer) {
  4525. var data = new Uint8Array(arrayBuffer);
  4526. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  4527. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  4528. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  4529. if (onLoad) {
  4530. onLoad();
  4531. }
  4532. }, samplingMode);
  4533. };
  4534. if (!(fromData instanceof Array))
  4535. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  4536. callback(arrayBuffer);
  4537. }, onerror, scene.database, true);
  4538. else
  4539. callback(buffer);
  4540. }
  4541. else if (isDDS) {
  4542. callback = function (data) {
  4543. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4544. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  4545. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  4546. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  4547. if (onLoad) {
  4548. onLoad();
  4549. }
  4550. }, samplingMode);
  4551. };
  4552. if (!(fromData instanceof Array))
  4553. BABYLON.Tools.LoadFile(url, function (data) {
  4554. callback(data);
  4555. }, onerror, scene.database, true);
  4556. else
  4557. callback(buffer);
  4558. }
  4559. else {
  4560. var onload = function (img) {
  4561. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  4562. var isPot = (img.width === potWidth && img.height === potHeight);
  4563. if (!isPot) {
  4564. _this._workingCanvas.width = potWidth;
  4565. _this._workingCanvas.height = potHeight;
  4566. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4567. _this._workingContext.imageSmoothingEnabled = false;
  4568. _this._workingContext.mozImageSmoothingEnabled = false;
  4569. _this._workingContext.oImageSmoothingEnabled = false;
  4570. _this._workingContext.webkitImageSmoothingEnabled = false;
  4571. _this._workingContext.msImageSmoothingEnabled = false;
  4572. }
  4573. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  4574. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  4575. _this._workingContext.imageSmoothingEnabled = true;
  4576. _this._workingContext.mozImageSmoothingEnabled = true;
  4577. _this._workingContext.oImageSmoothingEnabled = true;
  4578. _this._workingContext.webkitImageSmoothingEnabled = true;
  4579. _this._workingContext.msImageSmoothingEnabled = true;
  4580. }
  4581. }
  4582. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  4583. if (onLoad) {
  4584. onLoad();
  4585. }
  4586. }, samplingMode);
  4587. };
  4588. if (!(fromData instanceof Array))
  4589. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  4590. else
  4591. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  4592. }
  4593. return texture;
  4594. };
  4595. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode) {
  4596. var texture = this._gl.createTexture();
  4597. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4598. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  4599. // Format
  4600. var internalFormat = this._gl.RGBA;
  4601. switch (format) {
  4602. case Engine.TEXTUREFORMAT_ALPHA:
  4603. internalFormat = this._gl.ALPHA;
  4604. break;
  4605. case Engine.TEXTUREFORMAT_LUMINANCE:
  4606. internalFormat = this._gl.LUMINANCE;
  4607. break;
  4608. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  4609. internalFormat = this._gl.LUMINANCE_ALPHA;
  4610. break;
  4611. case Engine.TEXTUREFORMAT_RGB:
  4612. internalFormat = this._gl.RGB;
  4613. break;
  4614. case Engine.TEXTUREFORMAT_RGBA:
  4615. internalFormat = this._gl.RGBA;
  4616. break;
  4617. }
  4618. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, width, height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  4619. if (generateMipMaps) {
  4620. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4621. }
  4622. // Filters
  4623. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4624. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4625. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4626. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4627. this._activeTexturesCache = [];
  4628. texture._baseWidth = width;
  4629. texture._baseHeight = height;
  4630. texture._width = width;
  4631. texture._height = height;
  4632. texture.isReady = true;
  4633. texture.references = 1;
  4634. texture.samplingMode = samplingMode;
  4635. this._loadedTexturesCache.push(texture);
  4636. return texture;
  4637. };
  4638. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  4639. var texture = this._gl.createTexture();
  4640. width = BABYLON.Tools.GetExponantOfTwo(width, this._caps.maxTextureSize);
  4641. height = BABYLON.Tools.GetExponantOfTwo(height, this._caps.maxTextureSize);
  4642. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4643. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  4644. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  4645. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  4646. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4647. this._activeTexturesCache = [];
  4648. texture._baseWidth = width;
  4649. texture._baseHeight = height;
  4650. texture._width = width;
  4651. texture._height = height;
  4652. texture.isReady = false;
  4653. texture.generateMipMaps = generateMipMaps;
  4654. texture.references = 1;
  4655. texture.samplingMode = samplingMode;
  4656. this._loadedTexturesCache.push(texture);
  4657. return texture;
  4658. };
  4659. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY) {
  4660. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4661. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  4662. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  4663. if (texture.generateMipMaps) {
  4664. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4665. }
  4666. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4667. this._activeTexturesCache = [];
  4668. texture.isReady = true;
  4669. };
  4670. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  4671. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4672. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  4673. // Scale the video if it is a NPOT using the current working canvas
  4674. if (video.videoWidth !== texture._width || video.videoHeight !== texture._height) {
  4675. if (!texture._workingCanvas) {
  4676. texture._workingCanvas = document.createElement("canvas");
  4677. texture._workingContext = texture._workingCanvas.getContext("2d");
  4678. texture._workingCanvas.width = texture._width;
  4679. texture._workingCanvas.height = texture._height;
  4680. }
  4681. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  4682. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  4683. }
  4684. else {
  4685. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  4686. }
  4687. if (texture.generateMipMaps) {
  4688. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  4689. }
  4690. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4691. this._activeTexturesCache = [];
  4692. texture.isReady = true;
  4693. };
  4694. Engine.prototype.createRenderTargetTexture = function (size, options) {
  4695. // old version had a "generateMipMaps" arg instead of options.
  4696. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  4697. // in the same way, generateDepthBuffer is defaulted to true
  4698. var generateMipMaps = false;
  4699. var generateDepthBuffer = true;
  4700. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4701. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  4702. if (options !== undefined) {
  4703. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipmaps;
  4704. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  4705. type = options.type === undefined ? type : options.type;
  4706. if (options.samplingMode !== undefined) {
  4707. samplingMode = options.samplingMode;
  4708. }
  4709. if (type === Engine.TEXTURETYPE_FLOAT) {
  4710. // if floating point (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  4711. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  4712. }
  4713. }
  4714. var gl = this._gl;
  4715. var texture = gl.createTexture();
  4716. gl.bindTexture(gl.TEXTURE_2D, texture);
  4717. var width = size.width || size;
  4718. var height = size.height || size;
  4719. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  4720. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  4721. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  4722. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  4723. }
  4724. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  4725. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  4726. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4727. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4728. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  4729. var depthBuffer;
  4730. // Create the depth buffer
  4731. if (generateDepthBuffer) {
  4732. depthBuffer = gl.createRenderbuffer();
  4733. gl.bindRenderbuffer(gl.RENDERBUFFER, depthBuffer);
  4734. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  4735. }
  4736. // Create the framebuffer
  4737. var framebuffer = gl.createFramebuffer();
  4738. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  4739. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  4740. if (generateDepthBuffer) {
  4741. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthBuffer);
  4742. }
  4743. // Unbind
  4744. gl.bindTexture(gl.TEXTURE_2D, null);
  4745. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  4746. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  4747. texture._framebuffer = framebuffer;
  4748. if (generateDepthBuffer) {
  4749. texture._depthBuffer = depthBuffer;
  4750. }
  4751. texture._width = width;
  4752. texture._height = height;
  4753. texture.isReady = true;
  4754. texture.generateMipMaps = generateMipMaps;
  4755. texture.references = 1;
  4756. texture.samplingMode = samplingMode;
  4757. this._activeTexturesCache = [];
  4758. this._loadedTexturesCache.push(texture);
  4759. return texture;
  4760. };
  4761. Engine.prototype.createCubeTexture = function (rootUrl, scene, extensions, noMipmap) {
  4762. var _this = this;
  4763. var gl = this._gl;
  4764. var texture = gl.createTexture();
  4765. texture.isCube = true;
  4766. texture.url = rootUrl;
  4767. texture.references = 1;
  4768. this._loadedTexturesCache.push(texture);
  4769. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  4770. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  4771. if (isDDS) {
  4772. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  4773. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  4774. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  4775. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4776. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  4777. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  4778. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  4779. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4780. }
  4781. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4782. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  4783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4785. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4786. _this._activeTexturesCache = [];
  4787. texture._width = info.width;
  4788. texture._height = info.height;
  4789. texture.isReady = true;
  4790. }, null, null, true);
  4791. }
  4792. else {
  4793. cascadeLoad(rootUrl, scene, function (imgs) {
  4794. var width = BABYLON.Tools.GetExponantOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  4795. var height = width;
  4796. _this._workingCanvas.width = width;
  4797. _this._workingCanvas.height = height;
  4798. var faces = [
  4799. gl.TEXTURE_CUBE_MAP_POSITIVE_X,
  4800. gl.TEXTURE_CUBE_MAP_POSITIVE_Y,
  4801. gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  4802. gl.TEXTURE_CUBE_MAP_NEGATIVE_X,
  4803. gl.TEXTURE_CUBE_MAP_NEGATIVE_Y,
  4804. gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  4805. ];
  4806. gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
  4807. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  4808. for (var index = 0; index < faces.length; index++) {
  4809. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  4810. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  4811. }
  4812. if (!noMipmap) {
  4813. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  4814. }
  4815. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  4816. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  4817. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  4818. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  4819. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  4820. _this._activeTexturesCache = [];
  4821. texture._width = width;
  4822. texture._height = height;
  4823. texture.isReady = true;
  4824. }, extensions);
  4825. }
  4826. return texture;
  4827. };
  4828. Engine.prototype._releaseTexture = function (texture) {
  4829. var gl = this._gl;
  4830. if (texture._framebuffer) {
  4831. gl.deleteFramebuffer(texture._framebuffer);
  4832. }
  4833. if (texture._depthBuffer) {
  4834. gl.deleteRenderbuffer(texture._depthBuffer);
  4835. }
  4836. gl.deleteTexture(texture);
  4837. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  4838. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4839. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4840. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4841. this._activeTexturesCache[channel] = null;
  4842. }
  4843. var index = this._loadedTexturesCache.indexOf(texture);
  4844. if (index !== -1) {
  4845. this._loadedTexturesCache.splice(index, 1);
  4846. }
  4847. };
  4848. Engine.prototype.bindSamplers = function (effect) {
  4849. this._gl.useProgram(effect.getProgram());
  4850. var samplers = effect.getSamplers();
  4851. for (var index = 0; index < samplers.length; index++) {
  4852. var uniform = effect.getUniform(samplers[index]);
  4853. this._gl.uniform1i(uniform, index);
  4854. }
  4855. this._currentEffect = null;
  4856. };
  4857. Engine.prototype._bindTexture = function (channel, texture) {
  4858. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4859. this._gl.bindTexture(this._gl.TEXTURE_2D, texture);
  4860. this._activeTexturesCache[channel] = null;
  4861. };
  4862. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  4863. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  4864. };
  4865. Engine.prototype.setTexture = function (channel, texture) {
  4866. if (channel < 0) {
  4867. return;
  4868. }
  4869. // Not ready?
  4870. if (!texture || !texture.isReady()) {
  4871. if (this._activeTexturesCache[channel] != null) {
  4872. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4873. this._gl.bindTexture(this._gl.TEXTURE_2D, null);
  4874. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, null);
  4875. this._activeTexturesCache[channel] = null;
  4876. }
  4877. return;
  4878. }
  4879. // Video
  4880. if (texture instanceof BABYLON.VideoTexture) {
  4881. if (texture.update()) {
  4882. this._activeTexturesCache[channel] = null;
  4883. }
  4884. }
  4885. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  4886. texture.delayLoad();
  4887. return;
  4888. }
  4889. if (this._activeTexturesCache[channel] === texture) {
  4890. return;
  4891. }
  4892. this._activeTexturesCache[channel] = texture;
  4893. var internalTexture = texture.getInternalTexture();
  4894. this._gl.activeTexture(this._gl["TEXTURE" + channel]);
  4895. if (internalTexture.isCube) {
  4896. this._gl.bindTexture(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  4897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  4898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  4899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  4900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  4901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  4902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  4903. }
  4904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  4905. }
  4906. else {
  4907. this._gl.bindTexture(this._gl.TEXTURE_2D, internalTexture);
  4908. if (internalTexture._cachedWrapU !== texture.wrapU) {
  4909. internalTexture._cachedWrapU = texture.wrapU;
  4910. switch (texture.wrapU) {
  4911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  4913. break;
  4914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  4916. break;
  4917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  4919. break;
  4920. }
  4921. }
  4922. if (internalTexture._cachedWrapV !== texture.wrapV) {
  4923. internalTexture._cachedWrapV = texture.wrapV;
  4924. switch (texture.wrapV) {
  4925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  4926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  4927. break;
  4928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  4929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  4930. break;
  4931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  4932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  4933. break;
  4934. }
  4935. }
  4936. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  4937. }
  4938. };
  4939. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  4940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  4941. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== texture.anisotropicFilteringLevel) {
  4942. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(texture.anisotropicFilteringLevel, this._caps.maxAnisotropy));
  4943. texture._cachedAnisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  4944. }
  4945. };
  4946. Engine.prototype.readPixels = function (x, y, width, height) {
  4947. var data = new Uint8Array(height * width * 4);
  4948. this._gl.readPixels(0, 0, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  4949. return data;
  4950. };
  4951. // Dispose
  4952. Engine.prototype.dispose = function () {
  4953. this.hideLoadingUI();
  4954. this.stopRenderLoop();
  4955. while (this.scenes.length) {
  4956. this.scenes[0].dispose();
  4957. }
  4958. // Release audio engine
  4959. Engine.audioEngine.dispose();
  4960. for (var name in this._compiledEffects) {
  4961. this._gl.deleteProgram(this._compiledEffects[name]._program);
  4962. }
  4963. for (var i in this._vertexAttribArrays) {
  4964. if (i > this._gl.VERTEX_ATTRIB_ARRAY_ENABLED || !this._vertexAttribArrays[i]) {
  4965. continue;
  4966. }
  4967. this._gl.disableVertexAttribArray(i);
  4968. }
  4969. // Events
  4970. window.removeEventListener("blur", this._onBlur);
  4971. window.removeEventListener("focus", this._onFocus);
  4972. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  4973. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  4974. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  4975. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  4976. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  4977. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  4978. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  4979. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  4980. };
  4981. // Loading screen
  4982. Engine.prototype.displayLoadingUI = function () {
  4983. var _this = this;
  4984. this._loadingDiv = document.createElement("div");
  4985. this._loadingDiv.style.opacity = "0";
  4986. this._loadingDiv.style.transition = "opacity 1.5s ease";
  4987. // Loading text
  4988. this._loadingTextDiv = document.createElement("div");
  4989. this._loadingTextDiv.style.position = "absolute";
  4990. this._loadingTextDiv.style.left = "0";
  4991. this._loadingTextDiv.style.top = "50%";
  4992. this._loadingTextDiv.style.marginTop = "80px";
  4993. this._loadingTextDiv.style.width = "100%";
  4994. this._loadingTextDiv.style.height = "20px";
  4995. this._loadingTextDiv.style.fontFamily = "Arial";
  4996. this._loadingTextDiv.style.fontSize = "14px";
  4997. this._loadingTextDiv.style.color = "white";
  4998. this._loadingTextDiv.style.textAlign = "center";
  4999. this._loadingTextDiv.innerHTML = "Loading";
  5000. this._loadingDiv.appendChild(this._loadingTextDiv);
  5001. // Loading img
  5002. var imgBack = new Image();
  5003. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAARbSURBVHhe7Z09aFNRFMc716kuLrq4FdyLq4Wi4CAoRQcR0UJBUBdRiuLSIYMo6CA4FF2sgw6CFAdFUOpSQYcWO4hD26UQCfXrIQrx/JJzw1OSWq3NPeL/B4Fy+0jg/HO+7j3vpUcI8b/Q39+/49ihfWdPHT94Yf/e3Se3bd263f8lus218TPn6vV6Ya8Wi/MzNRNmj18iusX9W1evmP1/EKNEIVG6CMbG6E3bt+fT++pHha8NoHdT72bLE8NDg7tGU64gLLndV4Wc4m8j/pS+vr4tGB/DT16v3Fyr8dvBe/jbit8BL0AES9LX1iPAz+BR/hFiLVCynj95dPzNy6fv3IZ/k4L3948Sq7FzYGBg4vLFGxitabuOFCbWNKGrMnbiUuo18KaV6tIHv6YtvL9/nOgE31jCktmrY7k6+/zhE4yP4Vf7hiNqh/BWWEl8mzDol4p22Lf7cIdvdUMEvv0Y2S9fE5S1hLzpqTsPkiep//gFGPnR3Yl7GL5p/xYFBrTwM+iXio3GqpwDGL5p/xYNIX7XG8Q6IJRgdIzf1KBBgafII7oMidhyQtVFaMA2Bt7il4huQRhaXphbcR2g4RXqBzKAGHiCCwGFVUAj/m/RTRDj29cvn10I0PZ3LghH5f4CL1EFlQmqqXK3jDDKFxmhQ3Yt6oQseUZGKmMnTpsOqc8o1F9kBOMjQlOLeqEeIyOc6JV6jYLJD/+XyIFvnzdgl9aXRQ5I2qZDK1SpospMqaoqON/wZZGDciLnMMiXRS7IF4hhqMTNTdk7CFu+LHLhR7BQqBvPDJUUQqCGvCMATHUgBmhWNgApmdOda9YpM+VwRYfuyyIXDK8hBlilNerLIheMZCKGwlUAyru6GlwOgPUbRxADdJ9FAChxXY864viyyEXqPxhc0M2TAfAbatSdRyHtXymhByEdRnE3ky+JnHAIhSA0h74kckETmHoQbSgGwJrCIRMEPSRIBCRIMAhZaYhaggQhJXUJEoRU9mofKwh+F22dLRRfEjlJM7w6KQwCoQpBOKTyJZETjmwRxKqtGV8SOSkNOGjKPQppBEgDDkFgpxdBVGkFgaYQQXRIFQSObk0P5ZFIpAZRHXsQ0r0hCluBWKkuvVbYCkQaCdL5ehBScudJP4yY+rLISdps1NBDEJKXMMmoSfggWC4ZQRR17oFYXph7hSiquIKQ+hJGTX1J5MYSPD/GVdNzsgLBwZVCVyAQAkF0ohiI/c1fS6tNXq9UfEnkhudmIQolsS+J3Hh/UtNDzQLhj42VKJFInqLwFYiUU5ToA+HdfI0JevUpQUAIn+vSz2lHIuUV/dJOIHhOY/IWVWGBIHQtzs88s9zyWBuTgcBLzGOmeNnfF/QslSDgMeQW85i3DOQxuipxAkCyZ8SIm4Omp+7MMlCB59j6sKZcMoM4iIEoeI2J9AKxrFobZx0v4vYInuHFS4J1GQRCAGaLEYQXfyMML5XSQgghhBBCCCH+cXp6vgNhKpSKX/XdOAAAAABJRU5ErkJggg==";
  5004. imgBack.style.position = "absolute";
  5005. imgBack.style.left = "50%";
  5006. imgBack.style.top = "50%";
  5007. imgBack.style.marginLeft = "-50px";
  5008. imgBack.style.marginTop = "-50px";
  5009. imgBack.style.transition = "transform 1.0s ease";
  5010. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  5011. var deg = 360;
  5012. var onTransitionEnd = function () {
  5013. deg += 360;
  5014. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  5015. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  5016. };
  5017. imgBack.addEventListener("transitionend", onTransitionEnd);
  5018. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  5019. this._loadingDiv.appendChild(imgBack);
  5020. // front image
  5021. var imgFront = new Image();
  5022. imgFront.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuM4zml1AAAAYJSURBVHhe7Zy/qx1FFMff/2Av2Nvbi4WFiiAEY/OQ2IgQsbCJQoqkCAgpFLXyoZURLfwBIiIpgqZJoYQYlWelNsIrNOxDJcrzfHe+G97dnTl75u7euzv7zgcWHrlnZmfOmXPmzI/NjuM4juM4juM4juM4juM4juM4juM4juM45fPic08/uHf5/CvffH7lnT8PfrtxdHS0n3p+/fHGl5+89/prr5599iEWd8bg0rkXHoFyqehKnlxQpjYSDHTm9JMPsGrHylOPPXofvICKXMcIGtXdf/76AYbm6xyNW9e/eAtKC7rbKLXnvHHx5Sf4auc4Ek7OQkFU1Dap/vv37k/wSjblZANFiFIGzw98hhizwqBgs04mCBdQRNCHidoAEtY+lLIvtSdoGFeyql2ZH57HBH4sE7O+o/r9l+8/ZXUni68+2jsHBQQ9qNRGeP/tSxdSYQX/roUcpL4/f3vtM9TD+jTq92n1LQ7jxF1hhGPtwWL3gGccy8JuS1r8sVWBGXNVdSKMYjBGPUJjCzooiGuSpnwlnnOGP2dhHRSLNgpHp2oMKIriK8TmG4Qh/rwW8D6pps9b9im+LDDipXOqMVJrAngBfg9i98gevWKA+/nnCod3Dr5GfaHaDgidVym6HKRjGIkpqthcAVKGxNqBImbEo66kjCih8AOpNmkUmbMuUrR8kEqiU6FvHZLGAPJ71JCYSyhiBqmwFE2GoD6jLGIfDHtG6EzoU4dK21PCqIRMEF0FGRjFzGDtIkXVAdATvsqfT9CJ0JcOFdYiFIsiMlqYy1YOFpQo2OddqBtyEaq9y+efoVh5oPHoROjLKn0j3JIE5Ka8UqZRtGrMnneX6yVofOhDh94MSbznTcpqmDOt1vyQzOgaJAF4F3JBfIXesrNEGWWmjIX7UBZ6jRJbBMLg/DmJiKUGVHleIpnVNTa+jakzkAviJqLhi4MC9XQGBrZeKJZESSrKy7ik0VGFWhQBRDTHIACKQ5l9nAjy75gya4a2w+Jhs0FJdc0xX/GwUbAqFBkZi7QpJ2w16WUbjFyK9MJF3KaoEM74KhVtLrQOrsmRxkbdHEqmSC/c+EuGnIFkjW7Ih2Kr4CCMIvNG2hrrgLpCjiFloooYCjyYrzCRyvhyBthkIPuQtsZGdnbMTezyDiU71KTC5zr7aVsHbsz2tllrEkS5UHwU1tq1HbtPW4UbeB0O7xx8R5EsMJql+BheUmHjkNVmIRP7LutoM3+D4O4tG7vCkNO9ESZ4lL3J6rKRMPx4qKbD/A0icf8CG7tC7kTahnMTwleuYSrsS7GatRAvfZh1tTm5BmmQCdZ8a0Sefe28xUrRBkmFLKy8KTIKUDRX0Y1xagPgwbaIdeFnQULmKak3xvwNMkVGgok/N5XNoehJvejRlCDl9escI28dJU0tZ++nBTJE9mEF647x5Ehbo4s5hDOKFIU0PdofeA5F5k1q63zIWmQqNI/P3ZubjFTqKxQ3jyjHAOX0RdlgVO9hzRFpczRcjZ3Gbxxpc7Qj6+5pTYF2OFXawNI+yDGf1k2NcvOlzBQeDQ/t7zD7DsEDpJ2xATXaNtDWUS4IzP4DS2ljajAVu57SUkYw245ptxZxA5JiZaJ0DswudGn3kYUy54426EjoT4dZfYbccxC2nI92cDkZHQr96jD4AGkMDKeSy/COBsRe6VTSKFN6irLeaCh3IteQjt1E5+oudsG/b/2DfZ5AqsYo8vMDK9LB1HzSsLWvlGThdxXvC6+NsqyPPWP0pMINtbdsajfVeC6f/GZ+cdAofQoB1d+Hf9waY98I7+RXWab3Lt4zYkjHtTnlOLXHYMsCh1zWeQYehu1zfNPOOiys/d91LAKEBSgh6MJMbSA82AaHofDgAIwbgvVvlLNS11nModMm4UZergLHZBZrodmBuA3lBB1thdorSjkOmATMDwg/UBQVtglqQyx6fbEJ+H3IWIapjYAjAfeIgeCMHldueJvFaqDaAHhwf8qNsEEQ1iQbOoUUGIbCLRc8+Bvfp4jyd2FEijuO4ziO4ziO4ziO4ziO4ziO4ziO4ziOUzw7O/8D0P7rcZ/GEboAAAAASUVORK5CYII=";
  5023. imgFront.style.position = "absolute";
  5024. imgFront.style.left = "50%";
  5025. imgFront.style.top = "50%";
  5026. imgFront.style.marginLeft = "-50px";
  5027. imgFront.style.marginTop = "-50px";
  5028. this._loadingDiv.appendChild(imgFront);
  5029. // Resize
  5030. this._resizeLoadingUI = function () {
  5031. var canvasRect = _this.getRenderingCanvasClientRect();
  5032. _this._loadingDiv.style.position = "absolute";
  5033. _this._loadingDiv.style.left = canvasRect.left + "px";
  5034. _this._loadingDiv.style.top = canvasRect.top + "px";
  5035. _this._loadingDiv.style.width = canvasRect.width + "px";
  5036. _this._loadingDiv.style.height = canvasRect.height + "px";
  5037. };
  5038. this._resizeLoadingUI();
  5039. window.addEventListener("resize", this._resizeLoadingUI);
  5040. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5041. document.body.appendChild(this._loadingDiv);
  5042. setTimeout(function () {
  5043. _this._loadingDiv.style.opacity = "1";
  5044. imgBack.style.transform = "rotateZ(360deg)";
  5045. imgBack.style.webkitTransform = "rotateZ(360deg)";
  5046. }, 0);
  5047. };
  5048. Object.defineProperty(Engine.prototype, "loadingUIText", {
  5049. set: function (text) {
  5050. if (!this._loadingDiv) {
  5051. return;
  5052. }
  5053. this._loadingTextDiv.innerHTML = text;
  5054. },
  5055. enumerable: true,
  5056. configurable: true
  5057. });
  5058. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  5059. get: function () {
  5060. return this._loadingDivBackgroundColor;
  5061. },
  5062. set: function (color) {
  5063. this._loadingDivBackgroundColor = color;
  5064. if (!this._loadingDiv) {
  5065. return;
  5066. }
  5067. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  5068. },
  5069. enumerable: true,
  5070. configurable: true
  5071. });
  5072. Engine.prototype.hideLoadingUI = function () {
  5073. var _this = this;
  5074. if (!this._loadingDiv) {
  5075. return;
  5076. }
  5077. var onTransitionEnd = function () {
  5078. if (!_this._loadingDiv) {
  5079. return;
  5080. }
  5081. document.body.removeChild(_this._loadingDiv);
  5082. window.removeEventListener("resize", _this._resizeLoadingUI);
  5083. _this._loadingDiv = null;
  5084. };
  5085. this._loadingDiv.style.opacity = "0";
  5086. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  5087. };
  5088. // FPS
  5089. Engine.prototype.getFps = function () {
  5090. return this.fps;
  5091. };
  5092. Engine.prototype.getDeltaTime = function () {
  5093. return this.deltaTime;
  5094. };
  5095. Engine.prototype._measureFps = function () {
  5096. this.previousFramesDuration.push(BABYLON.Tools.Now);
  5097. var length = this.previousFramesDuration.length;
  5098. if (length >= 2) {
  5099. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  5100. }
  5101. if (length >= this.fpsRange) {
  5102. if (length > this.fpsRange) {
  5103. this.previousFramesDuration.splice(0, 1);
  5104. length = this.previousFramesDuration.length;
  5105. }
  5106. var sum = 0;
  5107. for (var id = 0; id < length - 1; id++) {
  5108. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  5109. }
  5110. this.fps = 1000.0 / (sum / (length - 1));
  5111. }
  5112. };
  5113. // Statics
  5114. Engine.isSupported = function () {
  5115. try {
  5116. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  5117. if (navigator.isCocoonJS) {
  5118. return true;
  5119. }
  5120. var tempcanvas = document.createElement("canvas");
  5121. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  5122. return gl != null && !!window.WebGLRenderingContext;
  5123. }
  5124. catch (e) {
  5125. return false;
  5126. }
  5127. };
  5128. // Const statics
  5129. Engine._ALPHA_DISABLE = 0;
  5130. Engine._ALPHA_ADD = 1;
  5131. Engine._ALPHA_COMBINE = 2;
  5132. Engine._DELAYLOADSTATE_NONE = 0;
  5133. Engine._DELAYLOADSTATE_LOADED = 1;
  5134. Engine._DELAYLOADSTATE_LOADING = 2;
  5135. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  5136. Engine._TEXTUREFORMAT_ALPHA = 0;
  5137. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  5138. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  5139. Engine._TEXTUREFORMAT_RGB = 4;
  5140. Engine._TEXTUREFORMAT_RGBA = 4;
  5141. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  5142. Engine._TEXTURETYPE_FLOAT = 1;
  5143. // Updatable statics so stick with vars here
  5144. Engine.Epsilon = 0.001;
  5145. Engine.CollisionsEpsilon = 0.001;
  5146. Engine.ShadersRepository = "Babylon/Shaders/";
  5147. return Engine;
  5148. })();
  5149. BABYLON.Engine = Engine;
  5150. })(BABYLON || (BABYLON = {}));
  5151. //# sourceMappingURL=babylon.engine.js.mapvar BABYLON;
  5152. (function (BABYLON) {
  5153. /**
  5154. * Node is the basic class for all scene objects (Mesh, Light Camera).
  5155. */
  5156. var Node = (function () {
  5157. /**
  5158. * @constructor
  5159. * @param {string} name - the name and id to be given to this node
  5160. * @param {BABYLON.Scene} the scene this node will be added to
  5161. */
  5162. function Node(name, scene) {
  5163. this.state = "";
  5164. this.animations = new Array();
  5165. this._childrenFlag = -1;
  5166. this._isEnabled = true;
  5167. this._isReady = true;
  5168. this._currentRenderId = -1;
  5169. this.name = name;
  5170. this.id = name;
  5171. this._scene = scene;
  5172. this._initCache();
  5173. }
  5174. Node.prototype.getScene = function () {
  5175. return this._scene;
  5176. };
  5177. Node.prototype.getEngine = function () {
  5178. return this._scene.getEngine();
  5179. };
  5180. // override it in derived class
  5181. Node.prototype.getWorldMatrix = function () {
  5182. return BABYLON.Matrix.Identity();
  5183. };
  5184. // override it in derived class if you add new variables to the cache
  5185. // and call the parent class method
  5186. Node.prototype._initCache = function () {
  5187. this._cache = {};
  5188. this._cache.parent = undefined;
  5189. };
  5190. Node.prototype.updateCache = function (force) {
  5191. if (!force && this.isSynchronized())
  5192. return;
  5193. this._cache.parent = this.parent;
  5194. this._updateCache();
  5195. };
  5196. // override it in derived class if you add new variables to the cache
  5197. // and call the parent class method if !ignoreParentClass
  5198. Node.prototype._updateCache = function (ignoreParentClass) {
  5199. };
  5200. // override it in derived class if you add new variables to the cache
  5201. Node.prototype._isSynchronized = function () {
  5202. return true;
  5203. };
  5204. Node.prototype.isSynchronizedWithParent = function () {
  5205. return this.parent ? this.parent._currentRenderId <= this._currentRenderId : true;
  5206. };
  5207. Node.prototype.isSynchronized = function (updateCache) {
  5208. var check = this.hasNewParent();
  5209. check = check || !this.isSynchronizedWithParent();
  5210. check = check || !this._isSynchronized();
  5211. if (updateCache)
  5212. this.updateCache(true);
  5213. return !check;
  5214. };
  5215. Node.prototype.hasNewParent = function (update) {
  5216. if (this._cache.parent === this.parent)
  5217. return false;
  5218. if (update)
  5219. this._cache.parent = this.parent;
  5220. return true;
  5221. };
  5222. /**
  5223. * Is this node ready to be used/rendered
  5224. * @return {boolean} is it ready
  5225. */
  5226. Node.prototype.isReady = function () {
  5227. return this._isReady;
  5228. };
  5229. /**
  5230. * Is this node enabled.
  5231. * If the node has a parent and is enabled, the parent will be inspected as well.
  5232. * @return {boolean} whether this node (and its parent) is enabled.
  5233. * @see setEnabled
  5234. */
  5235. Node.prototype.isEnabled = function () {
  5236. if (!this._isEnabled) {
  5237. return false;
  5238. }
  5239. if (this.parent) {
  5240. return this.parent.isEnabled();
  5241. }
  5242. return true;
  5243. };
  5244. /**
  5245. * Set the enabled state of this node.
  5246. * @param {boolean} value - the new enabled state
  5247. * @see isEnabled
  5248. */
  5249. Node.prototype.setEnabled = function (value) {
  5250. this._isEnabled = value;
  5251. };
  5252. /**
  5253. * Is this node a descendant of the given node.
  5254. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  5255. * @param {BABYLON.Node} ancestor - The parent node to inspect
  5256. * @see parent
  5257. */
  5258. Node.prototype.isDescendantOf = function (ancestor) {
  5259. if (this.parent) {
  5260. if (this.parent === ancestor) {
  5261. return true;
  5262. }
  5263. return this.parent.isDescendantOf(ancestor);
  5264. }
  5265. return false;
  5266. };
  5267. Node.prototype._getDescendants = function (list, results) {
  5268. for (var index = 0; index < list.length; index++) {
  5269. var item = list[index];
  5270. if (item.isDescendantOf(this)) {
  5271. results.push(item);
  5272. }
  5273. }
  5274. };
  5275. /**
  5276. * Will return all nodes that have this node as parent.
  5277. * @return {BABYLON.Node[]} all children nodes of all types.
  5278. */
  5279. Node.prototype.getDescendants = function () {
  5280. var results = [];
  5281. this._getDescendants(this._scene.meshes, results);
  5282. this._getDescendants(this._scene.lights, results);
  5283. this._getDescendants(this._scene.cameras, results);
  5284. return results;
  5285. };
  5286. Node.prototype._setReady = function (state) {
  5287. if (state == this._isReady) {
  5288. return;
  5289. }
  5290. if (!state) {
  5291. this._isReady = false;
  5292. return;
  5293. }
  5294. this._isReady = true;
  5295. if (this.onReady) {
  5296. this.onReady(this);
  5297. }
  5298. };
  5299. return Node;
  5300. })();
  5301. BABYLON.Node = Node;
  5302. })(BABYLON || (BABYLON = {}));
  5303. //# sourceMappingURL=babylon.node.js.mapvar BABYLON;
  5304. (function (BABYLON) {
  5305. var BoundingSphere = (function () {
  5306. function BoundingSphere(minimum, maximum) {
  5307. this.minimum = minimum;
  5308. this.maximum = maximum;
  5309. this._tempRadiusVector = BABYLON.Vector3.Zero();
  5310. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  5311. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  5312. this.radius = distance * 0.5;
  5313. this.centerWorld = BABYLON.Vector3.Zero();
  5314. this._update(BABYLON.Matrix.Identity());
  5315. }
  5316. // Methods
  5317. BoundingSphere.prototype._update = function (world) {
  5318. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  5319. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  5320. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  5321. };
  5322. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  5323. for (var i = 0; i < 6; i++) {
  5324. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  5325. return false;
  5326. }
  5327. return true;
  5328. };
  5329. BoundingSphere.prototype.intersectsPoint = function (point) {
  5330. var x = this.centerWorld.x - point.x;
  5331. var y = this.centerWorld.y - point.y;
  5332. var z = this.centerWorld.z - point.z;
  5333. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5334. if (Math.abs(this.radiusWorld - distance) < BABYLON.Engine.Epsilon)
  5335. return false;
  5336. return true;
  5337. };
  5338. // Statics
  5339. BoundingSphere.Intersects = function (sphere0, sphere1) {
  5340. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  5341. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  5342. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  5343. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  5344. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  5345. return false;
  5346. return true;
  5347. };
  5348. return BoundingSphere;
  5349. })();
  5350. BABYLON.BoundingSphere = BoundingSphere;
  5351. })(BABYLON || (BABYLON = {}));
  5352. //# sourceMappingURL=babylon.boundingSphere.js.mapvar BABYLON;
  5353. (function (BABYLON) {
  5354. var BoundingBox = (function () {
  5355. function BoundingBox(minimum, maximum) {
  5356. this.minimum = minimum;
  5357. this.maximum = maximum;
  5358. this.vectors = new Array();
  5359. this.vectorsWorld = new Array();
  5360. // Bounding vectors
  5361. this.vectors.push(this.minimum.clone());
  5362. this.vectors.push(this.maximum.clone());
  5363. this.vectors.push(this.minimum.clone());
  5364. this.vectors[2].x = this.maximum.x;
  5365. this.vectors.push(this.minimum.clone());
  5366. this.vectors[3].y = this.maximum.y;
  5367. this.vectors.push(this.minimum.clone());
  5368. this.vectors[4].z = this.maximum.z;
  5369. this.vectors.push(this.maximum.clone());
  5370. this.vectors[5].z = this.minimum.z;
  5371. this.vectors.push(this.maximum.clone());
  5372. this.vectors[6].x = this.minimum.x;
  5373. this.vectors.push(this.maximum.clone());
  5374. this.vectors[7].y = this.minimum.y;
  5375. // OBB
  5376. this.center = this.maximum.add(this.minimum).scale(0.5);
  5377. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  5378. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  5379. for (var index = 0; index < this.vectors.length; index++) {
  5380. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  5381. }
  5382. this.minimumWorld = BABYLON.Vector3.Zero();
  5383. this.maximumWorld = BABYLON.Vector3.Zero();
  5384. this._update(BABYLON.Matrix.Identity());
  5385. }
  5386. // Methods
  5387. BoundingBox.prototype.getWorldMatrix = function () {
  5388. return this._worldMatrix;
  5389. };
  5390. BoundingBox.prototype._update = function (world) {
  5391. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  5392. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  5393. for (var index = 0; index < this.vectors.length; index++) {
  5394. var v = this.vectorsWorld[index];
  5395. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  5396. if (v.x < this.minimumWorld.x)
  5397. this.minimumWorld.x = v.x;
  5398. if (v.y < this.minimumWorld.y)
  5399. this.minimumWorld.y = v.y;
  5400. if (v.z < this.minimumWorld.z)
  5401. this.minimumWorld.z = v.z;
  5402. if (v.x > this.maximumWorld.x)
  5403. this.maximumWorld.x = v.x;
  5404. if (v.y > this.maximumWorld.y)
  5405. this.maximumWorld.y = v.y;
  5406. if (v.z > this.maximumWorld.z)
  5407. this.maximumWorld.z = v.z;
  5408. }
  5409. // OBB
  5410. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  5411. this.center.scaleInPlace(0.5);
  5412. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  5413. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  5414. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  5415. this._worldMatrix = world;
  5416. };
  5417. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  5418. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  5419. };
  5420. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5421. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  5422. };
  5423. BoundingBox.prototype.intersectsPoint = function (point) {
  5424. var delta = BABYLON.Engine.Epsilon;
  5425. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  5426. return false;
  5427. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  5428. return false;
  5429. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  5430. return false;
  5431. return true;
  5432. };
  5433. BoundingBox.prototype.intersectsSphere = function (sphere) {
  5434. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  5435. };
  5436. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  5437. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  5438. return false;
  5439. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  5440. return false;
  5441. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  5442. return false;
  5443. return true;
  5444. };
  5445. // Statics
  5446. BoundingBox.Intersects = function (box0, box1) {
  5447. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  5448. return false;
  5449. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  5450. return false;
  5451. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  5452. return false;
  5453. return true;
  5454. };
  5455. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  5456. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  5457. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  5458. return (num <= (sphereRadius * sphereRadius));
  5459. };
  5460. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  5461. for (var p = 0; p < 6; p++) {
  5462. for (var i = 0; i < 8; i++) {
  5463. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5464. return false;
  5465. }
  5466. }
  5467. }
  5468. return true;
  5469. };
  5470. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  5471. for (var p = 0; p < 6; p++) {
  5472. var inCount = 8;
  5473. for (var i = 0; i < 8; i++) {
  5474. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  5475. --inCount;
  5476. }
  5477. else {
  5478. break;
  5479. }
  5480. }
  5481. if (inCount === 0)
  5482. return false;
  5483. }
  5484. return true;
  5485. };
  5486. return BoundingBox;
  5487. })();
  5488. BABYLON.BoundingBox = BoundingBox;
  5489. })(BABYLON || (BABYLON = {}));
  5490. //# sourceMappingURL=babylon.boundingBox.js.mapvar BABYLON;
  5491. (function (BABYLON) {
  5492. var computeBoxExtents = function (axis, box) {
  5493. var p = BABYLON.Vector3.Dot(box.center, axis);
  5494. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  5495. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  5496. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  5497. var r = r0 + r1 + r2;
  5498. return {
  5499. min: p - r,
  5500. max: p + r
  5501. };
  5502. };
  5503. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  5504. var axisOverlap = function (axis, box0, box1) {
  5505. var result0 = computeBoxExtents(axis, box0);
  5506. var result1 = computeBoxExtents(axis, box1);
  5507. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  5508. };
  5509. var BoundingInfo = (function () {
  5510. function BoundingInfo(minimum, maximum) {
  5511. this.minimum = minimum;
  5512. this.maximum = maximum;
  5513. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  5514. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  5515. }
  5516. // Methods
  5517. BoundingInfo.prototype._update = function (world) {
  5518. this.boundingBox._update(world);
  5519. this.boundingSphere._update(world);
  5520. };
  5521. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  5522. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  5523. return false;
  5524. return this.boundingBox.isInFrustum(frustumPlanes);
  5525. };
  5526. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  5527. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  5528. };
  5529. BoundingInfo.prototype._checkCollision = function (collider) {
  5530. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  5531. };
  5532. BoundingInfo.prototype.intersectsPoint = function (point) {
  5533. if (!this.boundingSphere.centerWorld) {
  5534. return false;
  5535. }
  5536. if (!this.boundingSphere.intersectsPoint(point)) {
  5537. return false;
  5538. }
  5539. if (!this.boundingBox.intersectsPoint(point)) {
  5540. return false;
  5541. }
  5542. return true;
  5543. };
  5544. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  5545. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  5546. return false;
  5547. }
  5548. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  5549. return false;
  5550. }
  5551. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  5552. return false;
  5553. }
  5554. if (!precise) {
  5555. return true;
  5556. }
  5557. var box0 = this.boundingBox;
  5558. var box1 = boundingInfo.boundingBox;
  5559. if (!axisOverlap(box0.directions[0], box0, box1))
  5560. return false;
  5561. if (!axisOverlap(box0.directions[1], box0, box1))
  5562. return false;
  5563. if (!axisOverlap(box0.directions[2], box0, box1))
  5564. return false;
  5565. if (!axisOverlap(box1.directions[0], box0, box1))
  5566. return false;
  5567. if (!axisOverlap(box1.directions[1], box0, box1))
  5568. return false;
  5569. if (!axisOverlap(box1.directions[2], box0, box1))
  5570. return false;
  5571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  5572. return false;
  5573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  5574. return false;
  5575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  5576. return false;
  5577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  5578. return false;
  5579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  5580. return false;
  5581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  5582. return false;
  5583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  5584. return false;
  5585. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  5586. return false;
  5587. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  5588. return false;
  5589. return true;
  5590. };
  5591. return BoundingInfo;
  5592. })();
  5593. BABYLON.BoundingInfo = BoundingInfo;
  5594. })(BABYLON || (BABYLON = {}));
  5595. //# sourceMappingURL=babylon.boundingInfo.js.map
  5596. var BABYLON;
  5597. (function (BABYLON) {
  5598. var Light = (function (_super) {
  5599. __extends(Light, _super);
  5600. function Light(name, scene) {
  5601. _super.call(this, name, scene);
  5602. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  5603. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  5604. this.intensity = 1.0;
  5605. this.range = Number.MAX_VALUE;
  5606. this.includedOnlyMeshes = new Array();
  5607. this.excludedMeshes = new Array();
  5608. this._excludedMeshesIds = new Array();
  5609. this._includedOnlyMeshesIds = new Array();
  5610. scene.lights.push(this);
  5611. }
  5612. Light.prototype.getShadowGenerator = function () {
  5613. return this._shadowGenerator;
  5614. };
  5615. Light.prototype.getAbsolutePosition = function () {
  5616. return BABYLON.Vector3.Zero();
  5617. };
  5618. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  5619. };
  5620. Light.prototype._getWorldMatrix = function () {
  5621. return BABYLON.Matrix.Identity();
  5622. };
  5623. Light.prototype.canAffectMesh = function (mesh) {
  5624. if (!mesh) {
  5625. return true;
  5626. }
  5627. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  5628. return false;
  5629. }
  5630. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  5631. return false;
  5632. }
  5633. return true;
  5634. };
  5635. Light.prototype.getWorldMatrix = function () {
  5636. this._currentRenderId = this.getScene().getRenderId();
  5637. var worldMatrix = this._getWorldMatrix();
  5638. if (this.parent && this.parent.getWorldMatrix) {
  5639. if (!this._parentedWorldMatrix) {
  5640. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  5641. }
  5642. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  5643. return this._parentedWorldMatrix;
  5644. }
  5645. return worldMatrix;
  5646. };
  5647. Light.prototype.dispose = function () {
  5648. if (this._shadowGenerator) {
  5649. this._shadowGenerator.dispose();
  5650. this._shadowGenerator = null;
  5651. }
  5652. // Remove from scene
  5653. var index = this.getScene().lights.indexOf(this);
  5654. this.getScene().lights.splice(index, 1);
  5655. };
  5656. return Light;
  5657. })(BABYLON.Node);
  5658. BABYLON.Light = Light;
  5659. })(BABYLON || (BABYLON = {}));
  5660. //# sourceMappingURL=babylon.light.js.map
  5661. var BABYLON;
  5662. (function (BABYLON) {
  5663. var PointLight = (function (_super) {
  5664. __extends(PointLight, _super);
  5665. function PointLight(name, position, scene) {
  5666. _super.call(this, name, scene);
  5667. this.position = position;
  5668. }
  5669. PointLight.prototype.getAbsolutePosition = function () {
  5670. return this._transformedPosition ? this._transformedPosition : this.position;
  5671. };
  5672. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  5673. if (this.parent && this.parent.getWorldMatrix) {
  5674. if (!this._transformedPosition) {
  5675. this._transformedPosition = BABYLON.Vector3.Zero();
  5676. }
  5677. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this._transformedPosition);
  5678. effect.setFloat4(positionUniformName, this._transformedPosition.x, this._transformedPosition.y, this._transformedPosition.z, 0);
  5679. return;
  5680. }
  5681. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  5682. };
  5683. PointLight.prototype.getShadowGenerator = function () {
  5684. return null;
  5685. };
  5686. PointLight.prototype._getWorldMatrix = function () {
  5687. if (!this._worldMatrix) {
  5688. this._worldMatrix = BABYLON.Matrix.Identity();
  5689. }
  5690. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5691. return this._worldMatrix;
  5692. };
  5693. return PointLight;
  5694. })(BABYLON.Light);
  5695. BABYLON.PointLight = PointLight;
  5696. })(BABYLON || (BABYLON = {}));
  5697. //# sourceMappingURL=babylon.pointLight.js.map
  5698. var BABYLON;
  5699. (function (BABYLON) {
  5700. var SpotLight = (function (_super) {
  5701. __extends(SpotLight, _super);
  5702. function SpotLight(name, position, direction, angle, exponent, scene) {
  5703. _super.call(this, name, scene);
  5704. this.position = position;
  5705. this.direction = direction;
  5706. this.angle = angle;
  5707. this.exponent = exponent;
  5708. }
  5709. SpotLight.prototype.getAbsolutePosition = function () {
  5710. return this.transformedPosition ? this.transformedPosition : this.position;
  5711. };
  5712. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5713. var activeCamera = this.getScene().activeCamera;
  5714. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  5715. };
  5716. SpotLight.prototype.supportsVSM = function () {
  5717. return true;
  5718. };
  5719. SpotLight.prototype.needRefreshPerFrame = function () {
  5720. return false;
  5721. };
  5722. SpotLight.prototype.setDirectionToTarget = function (target) {
  5723. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5724. return this.direction;
  5725. };
  5726. SpotLight.prototype.computeTransformedPosition = function () {
  5727. if (this.parent && this.parent.getWorldMatrix) {
  5728. if (!this.transformedPosition) {
  5729. this.transformedPosition = BABYLON.Vector3.Zero();
  5730. }
  5731. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5732. return true;
  5733. }
  5734. return false;
  5735. };
  5736. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  5737. var normalizeDirection;
  5738. if (this.parent && this.parent.getWorldMatrix) {
  5739. if (!this._transformedDirection) {
  5740. this._transformedDirection = BABYLON.Vector3.Zero();
  5741. }
  5742. this.computeTransformedPosition();
  5743. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5744. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  5745. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  5746. }
  5747. else {
  5748. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  5749. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  5750. }
  5751. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  5752. };
  5753. SpotLight.prototype._getWorldMatrix = function () {
  5754. if (!this._worldMatrix) {
  5755. this._worldMatrix = BABYLON.Matrix.Identity();
  5756. }
  5757. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5758. return this._worldMatrix;
  5759. };
  5760. return SpotLight;
  5761. })(BABYLON.Light);
  5762. BABYLON.SpotLight = SpotLight;
  5763. })(BABYLON || (BABYLON = {}));
  5764. //# sourceMappingURL=babylon.spotLight.js.map
  5765. var BABYLON;
  5766. (function (BABYLON) {
  5767. var DirectionalLight = (function (_super) {
  5768. __extends(DirectionalLight, _super);
  5769. function DirectionalLight(name, direction, scene) {
  5770. _super.call(this, name, scene);
  5771. this.direction = direction;
  5772. this.position = direction.scale(-1);
  5773. }
  5774. DirectionalLight.prototype.getAbsolutePosition = function () {
  5775. return this.transformedPosition ? this.transformedPosition : this.position;
  5776. };
  5777. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  5778. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  5779. return this.direction;
  5780. };
  5781. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  5782. var orthoLeft = Number.MAX_VALUE;
  5783. var orthoRight = Number.MIN_VALUE;
  5784. var orthoTop = Number.MIN_VALUE;
  5785. var orthoBottom = Number.MAX_VALUE;
  5786. var tempVector3 = BABYLON.Vector3.Zero();
  5787. var activeCamera = this.getScene().activeCamera;
  5788. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  5789. var boundingBox = renderList[meshIndex].getBoundingInfo().boundingBox;
  5790. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  5791. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  5792. if (tempVector3.x < orthoLeft)
  5793. orthoLeft = tempVector3.x;
  5794. if (tempVector3.y < orthoBottom)
  5795. orthoBottom = tempVector3.y;
  5796. if (tempVector3.x > orthoRight)
  5797. orthoRight = tempVector3.x;
  5798. if (tempVector3.y > orthoTop)
  5799. orthoTop = tempVector3.y;
  5800. }
  5801. }
  5802. var orthoWidth = Math.max(Math.abs(orthoRight), Math.abs(orthoLeft)) * 1.1;
  5803. var orthoHeight = Math.max(Math.abs(orthoTop), Math.abs(orthoBottom)) * 1.1;
  5804. BABYLON.Matrix.OrthoOffCenterLHToRef(-orthoWidth, orthoWidth, -orthoHeight, orthoHeight, activeCamera.minZ, activeCamera.maxZ, matrix);
  5805. };
  5806. DirectionalLight.prototype.supportsVSM = function () {
  5807. return false;
  5808. };
  5809. DirectionalLight.prototype.needRefreshPerFrame = function () {
  5810. return true;
  5811. };
  5812. DirectionalLight.prototype.computeTransformedPosition = function () {
  5813. if (this.parent && this.parent.getWorldMatrix) {
  5814. if (!this.transformedPosition) {
  5815. this.transformedPosition = BABYLON.Vector3.Zero();
  5816. }
  5817. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  5818. return true;
  5819. }
  5820. return false;
  5821. };
  5822. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  5823. if (this.parent && this.parent.getWorldMatrix) {
  5824. if (!this._transformedDirection) {
  5825. this._transformedDirection = BABYLON.Vector3.Zero();
  5826. }
  5827. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  5828. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  5829. return;
  5830. }
  5831. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  5832. };
  5833. DirectionalLight.prototype._getWorldMatrix = function () {
  5834. if (!this._worldMatrix) {
  5835. this._worldMatrix = BABYLON.Matrix.Identity();
  5836. }
  5837. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  5838. return this._worldMatrix;
  5839. };
  5840. return DirectionalLight;
  5841. })(BABYLON.Light);
  5842. BABYLON.DirectionalLight = DirectionalLight;
  5843. })(BABYLON || (BABYLON = {}));
  5844. //# sourceMappingURL=babylon.directionalLight.js.mapvar BABYLON;
  5845. (function (BABYLON) {
  5846. var ShadowGenerator = (function () {
  5847. function ShadowGenerator(mapSize, light) {
  5848. var _this = this;
  5849. // Members
  5850. this.filter = ShadowGenerator.FILTER_NONE;
  5851. this._darkness = 0;
  5852. this._bias = 0.0001;
  5853. this._transparencyShadow = false;
  5854. this._viewMatrix = BABYLON.Matrix.Zero();
  5855. this._projectionMatrix = BABYLON.Matrix.Zero();
  5856. this._transformMatrix = BABYLON.Matrix.Zero();
  5857. this._worldViewProjection = BABYLON.Matrix.Zero();
  5858. this._light = light;
  5859. this._scene = light.getScene();
  5860. light._shadowGenerator = this;
  5861. // Render target
  5862. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false);
  5863. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5864. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  5865. this._shadowMap.renderParticles = false;
  5866. // Custom render function
  5867. var renderSubMesh = function (subMesh) {
  5868. var mesh = subMesh.getRenderingMesh();
  5869. var scene = _this._scene;
  5870. var engine = scene.getEngine();
  5871. // Culling
  5872. engine.setState(subMesh.getMaterial().backFaceCulling);
  5873. // Managing instances
  5874. var batch = mesh._getInstancesRenderList(subMesh._id);
  5875. if (batch.mustReturn) {
  5876. return;
  5877. }
  5878. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  5879. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  5880. engine.enableEffect(_this._effect);
  5881. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  5882. var material = subMesh.getMaterial();
  5883. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  5884. // Alpha test
  5885. if (material && material.needAlphaTesting()) {
  5886. var alphaTexture = material.getAlphaTestTexture();
  5887. _this._effect.setTexture("diffuseSampler", alphaTexture);
  5888. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  5889. }
  5890. // Bones
  5891. if (mesh.useBones) {
  5892. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  5893. }
  5894. // Draw
  5895. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  5896. }
  5897. else {
  5898. // Need to reset refresh rate of the shadowMap
  5899. _this._shadowMap.resetRefreshCounter();
  5900. }
  5901. };
  5902. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  5903. var index;
  5904. for (index = 0; index < opaqueSubMeshes.length; index++) {
  5905. renderSubMesh(opaqueSubMeshes.data[index]);
  5906. }
  5907. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  5908. renderSubMesh(alphaTestSubMeshes.data[index]);
  5909. }
  5910. if (_this._transparencyShadow) {
  5911. for (index = 0; index < transparentSubMeshes.length; index++) {
  5912. renderSubMesh(transparentSubMeshes.data[index]);
  5913. }
  5914. }
  5915. };
  5916. }
  5917. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  5918. // Static
  5919. get: function () {
  5920. return ShadowGenerator._FILTER_NONE;
  5921. },
  5922. enumerable: true,
  5923. configurable: true
  5924. });
  5925. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  5926. get: function () {
  5927. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  5933. get: function () {
  5934. return ShadowGenerator._FILTER_POISSONSAMPLING;
  5935. },
  5936. enumerable: true,
  5937. configurable: true
  5938. });
  5939. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  5940. get: function () {
  5941. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  5942. },
  5943. set: function (value) {
  5944. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  5945. },
  5946. enumerable: true,
  5947. configurable: true
  5948. });
  5949. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  5950. get: function () {
  5951. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING || (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && !this._light.supportsVSM());
  5952. },
  5953. set: function (value) {
  5954. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  5955. },
  5956. enumerable: true,
  5957. configurable: true
  5958. });
  5959. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  5960. var defines = [];
  5961. if (this.useVarianceShadowMap) {
  5962. defines.push("#define VSM");
  5963. }
  5964. var attribs = [BABYLON.VertexBuffer.PositionKind];
  5965. var mesh = subMesh.getMesh();
  5966. var material = subMesh.getMaterial();
  5967. // Alpha test
  5968. if (material && material.needAlphaTesting()) {
  5969. defines.push("#define ALPHATEST");
  5970. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  5971. attribs.push(BABYLON.VertexBuffer.UVKind);
  5972. defines.push("#define UV1");
  5973. }
  5974. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  5975. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  5976. defines.push("#define UV2");
  5977. }
  5978. }
  5979. // Bones
  5980. if (mesh.useBones) {
  5981. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  5982. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  5983. defines.push("#define BONES");
  5984. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  5985. }
  5986. // Instances
  5987. if (useInstances) {
  5988. defines.push("#define INSTANCES");
  5989. attribs.push("world0");
  5990. attribs.push("world1");
  5991. attribs.push("world2");
  5992. attribs.push("world3");
  5993. }
  5994. // Get correct effect
  5995. var join = defines.join("\n");
  5996. if (this._cachedDefines !== join) {
  5997. this._cachedDefines = join;
  5998. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  5999. }
  6000. return this._effect.isReady();
  6001. };
  6002. ShadowGenerator.prototype.getShadowMap = function () {
  6003. return this._shadowMap;
  6004. };
  6005. ShadowGenerator.prototype.getLight = function () {
  6006. return this._light;
  6007. };
  6008. // Methods
  6009. ShadowGenerator.prototype.getTransformMatrix = function () {
  6010. var scene = this._scene;
  6011. if (this._currentRenderID === scene.getRenderId()) {
  6012. return this._transformMatrix;
  6013. }
  6014. this._currentRenderID = scene.getRenderId();
  6015. var lightPosition = this._light.position;
  6016. var lightDirection = this._light.direction;
  6017. if (this._light.computeTransformedPosition()) {
  6018. lightPosition = this._light.transformedPosition;
  6019. }
  6020. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !lightDirection.equals(this._cachedDirection)) {
  6021. this._cachedPosition = lightPosition.clone();
  6022. this._cachedDirection = lightDirection.clone();
  6023. BABYLON.Matrix.LookAtLHToRef(lightPosition, this._light.position.add(lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  6024. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  6025. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  6026. }
  6027. return this._transformMatrix;
  6028. };
  6029. ShadowGenerator.prototype.getDarkness = function () {
  6030. return this._darkness;
  6031. };
  6032. ShadowGenerator.prototype.setDarkness = function (darkness) {
  6033. if (darkness >= 1.0)
  6034. this._darkness = 1.0;
  6035. else if (darkness <= 0.0)
  6036. this._darkness = 0.0;
  6037. else
  6038. this._darkness = darkness;
  6039. };
  6040. ShadowGenerator.prototype.getBias = function () {
  6041. return this._bias;
  6042. };
  6043. ShadowGenerator.prototype.setBias = function (bias) {
  6044. this._bias = bias;
  6045. };
  6046. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  6047. this._transparencyShadow = hasShadow;
  6048. };
  6049. ShadowGenerator.prototype.dispose = function () {
  6050. this._shadowMap.dispose();
  6051. };
  6052. ShadowGenerator._FILTER_NONE = 0;
  6053. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  6054. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  6055. return ShadowGenerator;
  6056. })();
  6057. BABYLON.ShadowGenerator = ShadowGenerator;
  6058. })(BABYLON || (BABYLON = {}));
  6059. //# sourceMappingURL=babylon.shadowGenerator.js.map
  6060. var BABYLON;
  6061. (function (BABYLON) {
  6062. var HemisphericLight = (function (_super) {
  6063. __extends(HemisphericLight, _super);
  6064. function HemisphericLight(name, direction, scene) {
  6065. _super.call(this, name, scene);
  6066. this.direction = direction;
  6067. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  6068. }
  6069. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  6070. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  6071. return this.direction;
  6072. };
  6073. HemisphericLight.prototype.getShadowGenerator = function () {
  6074. return null;
  6075. };
  6076. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  6077. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  6078. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  6079. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  6080. };
  6081. HemisphericLight.prototype._getWorldMatrix = function () {
  6082. if (!this._worldMatrix) {
  6083. this._worldMatrix = BABYLON.Matrix.Identity();
  6084. }
  6085. return this._worldMatrix;
  6086. };
  6087. return HemisphericLight;
  6088. })(BABYLON.Light);
  6089. BABYLON.HemisphericLight = HemisphericLight;
  6090. })(BABYLON || (BABYLON = {}));
  6091. //# sourceMappingURL=babylon.hemisphericLight.js.mapvar BABYLON;
  6092. (function (BABYLON) {
  6093. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  6094. if (boxMin.x > sphereCenter.x + sphereRadius)
  6095. return false;
  6096. if (sphereCenter.x - sphereRadius > boxMax.x)
  6097. return false;
  6098. if (boxMin.y > sphereCenter.y + sphereRadius)
  6099. return false;
  6100. if (sphereCenter.y - sphereRadius > boxMax.y)
  6101. return false;
  6102. if (boxMin.z > sphereCenter.z + sphereRadius)
  6103. return false;
  6104. if (sphereCenter.z - sphereRadius > boxMax.z)
  6105. return false;
  6106. return true;
  6107. };
  6108. var getLowestRoot = function (a, b, c, maxR) {
  6109. var determinant = b * b - 4.0 * a * c;
  6110. var result = { root: 0, found: false };
  6111. if (determinant < 0)
  6112. return result;
  6113. var sqrtD = Math.sqrt(determinant);
  6114. var r1 = (-b - sqrtD) / (2.0 * a);
  6115. var r2 = (-b + sqrtD) / (2.0 * a);
  6116. if (r1 > r2) {
  6117. var temp = r2;
  6118. r2 = r1;
  6119. r1 = temp;
  6120. }
  6121. if (r1 > 0 && r1 < maxR) {
  6122. result.root = r1;
  6123. result.found = true;
  6124. return result;
  6125. }
  6126. if (r2 > 0 && r2 < maxR) {
  6127. result.root = r2;
  6128. result.found = true;
  6129. return result;
  6130. }
  6131. return result;
  6132. };
  6133. var Collider = (function () {
  6134. function Collider() {
  6135. this.radius = new BABYLON.Vector3(1, 1, 1);
  6136. this.retry = 0;
  6137. this.basePointWorld = BABYLON.Vector3.Zero();
  6138. this.velocityWorld = BABYLON.Vector3.Zero();
  6139. this.normalizedVelocity = BABYLON.Vector3.Zero();
  6140. this._collisionPoint = BABYLON.Vector3.Zero();
  6141. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  6142. this._tempVector = BABYLON.Vector3.Zero();
  6143. this._tempVector2 = BABYLON.Vector3.Zero();
  6144. this._tempVector3 = BABYLON.Vector3.Zero();
  6145. this._tempVector4 = BABYLON.Vector3.Zero();
  6146. this._edge = BABYLON.Vector3.Zero();
  6147. this._baseToVertex = BABYLON.Vector3.Zero();
  6148. this._destinationPoint = BABYLON.Vector3.Zero();
  6149. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  6150. this._displacementVector = BABYLON.Vector3.Zero();
  6151. }
  6152. // Methods
  6153. Collider.prototype._initialize = function (source, dir, e) {
  6154. this.velocity = dir;
  6155. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  6156. this.basePoint = source;
  6157. source.multiplyToRef(this.radius, this.basePointWorld);
  6158. dir.multiplyToRef(this.radius, this.velocityWorld);
  6159. this.velocityWorldLength = this.velocityWorld.length();
  6160. this.epsilon = e;
  6161. this.collisionFound = false;
  6162. };
  6163. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  6164. pa.subtractToRef(point, this._tempVector);
  6165. pb.subtractToRef(point, this._tempVector2);
  6166. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  6167. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6168. if (d < 0)
  6169. return false;
  6170. pc.subtractToRef(point, this._tempVector3);
  6171. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  6172. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6173. if (d < 0)
  6174. return false;
  6175. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  6176. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  6177. return d >= 0;
  6178. };
  6179. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  6180. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  6181. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  6182. if (distance > this.velocityWorldLength + max + sphereRadius) {
  6183. return false;
  6184. }
  6185. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  6186. return false;
  6187. return true;
  6188. };
  6189. Collider.prototype._testTriangle = function (faceIndex, subMesh, p1, p2, p3) {
  6190. var t0;
  6191. var embeddedInPlane = false;
  6192. if (!subMesh._trianglePlanes) {
  6193. subMesh._trianglePlanes = [];
  6194. }
  6195. if (!subMesh._trianglePlanes[faceIndex]) {
  6196. subMesh._trianglePlanes[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  6197. subMesh._trianglePlanes[faceIndex].copyFromPoints(p1, p2, p3);
  6198. }
  6199. var trianglePlane = subMesh._trianglePlanes[faceIndex];
  6200. if ((!subMesh.getMaterial()) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  6201. return;
  6202. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  6203. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  6204. if (normalDotVelocity == 0) {
  6205. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  6206. return;
  6207. embeddedInPlane = true;
  6208. t0 = 0;
  6209. }
  6210. else {
  6211. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6212. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  6213. if (t0 > t1) {
  6214. var temp = t1;
  6215. t1 = t0;
  6216. t0 = temp;
  6217. }
  6218. if (t0 > 1.0 || t1 < 0.0)
  6219. return;
  6220. if (t0 < 0)
  6221. t0 = 0;
  6222. if (t0 > 1.0)
  6223. t0 = 1.0;
  6224. }
  6225. this._collisionPoint.copyFromFloats(0, 0, 0);
  6226. var found = false;
  6227. var t = 1.0;
  6228. if (!embeddedInPlane) {
  6229. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  6230. this.velocity.scaleToRef(t0, this._tempVector);
  6231. this._planeIntersectionPoint.addInPlace(this._tempVector);
  6232. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  6233. found = true;
  6234. t = t0;
  6235. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  6236. }
  6237. }
  6238. if (!found) {
  6239. var velocitySquaredLength = this.velocity.lengthSquared();
  6240. var a = velocitySquaredLength;
  6241. this.basePoint.subtractToRef(p1, this._tempVector);
  6242. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6243. var c = this._tempVector.lengthSquared() - 1.0;
  6244. var lowestRoot = getLowestRoot(a, b, c, t);
  6245. if (lowestRoot.found) {
  6246. t = lowestRoot.root;
  6247. found = true;
  6248. this._collisionPoint.copyFrom(p1);
  6249. }
  6250. this.basePoint.subtractToRef(p2, this._tempVector);
  6251. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6252. c = this._tempVector.lengthSquared() - 1.0;
  6253. lowestRoot = getLowestRoot(a, b, c, t);
  6254. if (lowestRoot.found) {
  6255. t = lowestRoot.root;
  6256. found = true;
  6257. this._collisionPoint.copyFrom(p2);
  6258. }
  6259. this.basePoint.subtractToRef(p3, this._tempVector);
  6260. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  6261. c = this._tempVector.lengthSquared() - 1.0;
  6262. lowestRoot = getLowestRoot(a, b, c, t);
  6263. if (lowestRoot.found) {
  6264. t = lowestRoot.root;
  6265. found = true;
  6266. this._collisionPoint.copyFrom(p3);
  6267. }
  6268. p2.subtractToRef(p1, this._edge);
  6269. p1.subtractToRef(this.basePoint, this._baseToVertex);
  6270. var edgeSquaredLength = this._edge.lengthSquared();
  6271. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6272. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6273. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6274. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6275. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6276. lowestRoot = getLowestRoot(a, b, c, t);
  6277. if (lowestRoot.found) {
  6278. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6279. if (f >= 0.0 && f <= 1.0) {
  6280. t = lowestRoot.root;
  6281. found = true;
  6282. this._edge.scaleInPlace(f);
  6283. p1.addToRef(this._edge, this._collisionPoint);
  6284. }
  6285. }
  6286. p3.subtractToRef(p2, this._edge);
  6287. p2.subtractToRef(this.basePoint, this._baseToVertex);
  6288. edgeSquaredLength = this._edge.lengthSquared();
  6289. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6290. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6291. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6292. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6293. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6294. lowestRoot = getLowestRoot(a, b, c, t);
  6295. if (lowestRoot.found) {
  6296. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6297. if (f >= 0.0 && f <= 1.0) {
  6298. t = lowestRoot.root;
  6299. found = true;
  6300. this._edge.scaleInPlace(f);
  6301. p2.addToRef(this._edge, this._collisionPoint);
  6302. }
  6303. }
  6304. p1.subtractToRef(p3, this._edge);
  6305. p3.subtractToRef(this.basePoint, this._baseToVertex);
  6306. edgeSquaredLength = this._edge.lengthSquared();
  6307. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  6308. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  6309. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  6310. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  6311. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  6312. lowestRoot = getLowestRoot(a, b, c, t);
  6313. if (lowestRoot.found) {
  6314. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  6315. if (f >= 0.0 && f <= 1.0) {
  6316. t = lowestRoot.root;
  6317. found = true;
  6318. this._edge.scaleInPlace(f);
  6319. p3.addToRef(this._edge, this._collisionPoint);
  6320. }
  6321. }
  6322. }
  6323. if (found) {
  6324. var distToCollision = t * this.velocity.length();
  6325. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  6326. if (!this.intersectionPoint) {
  6327. this.intersectionPoint = this._collisionPoint.clone();
  6328. }
  6329. else {
  6330. this.intersectionPoint.copyFrom(this._collisionPoint);
  6331. }
  6332. this.nearestDistance = distToCollision;
  6333. this.collisionFound = true;
  6334. this.collidedMesh = subMesh.getMesh();
  6335. }
  6336. }
  6337. };
  6338. Collider.prototype._collide = function (subMesh, pts, indices, indexStart, indexEnd, decal) {
  6339. for (var i = indexStart; i < indexEnd; i += 3) {
  6340. var p1 = pts[indices[i] - decal];
  6341. var p2 = pts[indices[i + 1] - decal];
  6342. var p3 = pts[indices[i + 2] - decal];
  6343. this._testTriangle(i, subMesh, p3, p2, p1);
  6344. }
  6345. };
  6346. Collider.prototype._getResponse = function (pos, vel) {
  6347. pos.addToRef(vel, this._destinationPoint);
  6348. vel.scaleInPlace((this.nearestDistance / vel.length()));
  6349. this.basePoint.addToRef(vel, pos);
  6350. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  6351. this._slidePlaneNormal.normalize();
  6352. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  6353. pos.addInPlace(this._displacementVector);
  6354. this.intersectionPoint.addInPlace(this._displacementVector);
  6355. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  6356. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  6357. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  6358. };
  6359. return Collider;
  6360. })();
  6361. BABYLON.Collider = Collider;
  6362. })(BABYLON || (BABYLON = {}));
  6363. //# sourceMappingURL=babylon.collider.js.map
  6364. var BABYLON;
  6365. (function (BABYLON) {
  6366. var Camera = (function (_super) {
  6367. __extends(Camera, _super);
  6368. function Camera(name, position, scene) {
  6369. _super.call(this, name, scene);
  6370. this.position = position;
  6371. // Members
  6372. this.upVector = BABYLON.Vector3.Up();
  6373. this.orthoLeft = null;
  6374. this.orthoRight = null;
  6375. this.orthoBottom = null;
  6376. this.orthoTop = null;
  6377. this.fov = 0.8;
  6378. this.minZ = 1.0;
  6379. this.maxZ = 10000.0;
  6380. this.inertia = 0.9;
  6381. this.mode = Camera.PERSPECTIVE_CAMERA;
  6382. this.isIntermediate = false;
  6383. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  6384. this.subCameras = [];
  6385. this.layerMask = 0xFFFFFFFF;
  6386. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  6387. this._computedViewMatrix = BABYLON.Matrix.Identity();
  6388. this._projectionMatrix = new BABYLON.Matrix();
  6389. this._postProcesses = new Array();
  6390. this._postProcessesTakenIndices = [];
  6391. this._activeMeshes = new BABYLON.SmartArray(256);
  6392. scene.cameras.push(this);
  6393. if (!scene.activeCamera) {
  6394. scene.activeCamera = this;
  6395. }
  6396. }
  6397. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  6398. get: function () {
  6399. return Camera._PERSPECTIVE_CAMERA;
  6400. },
  6401. enumerable: true,
  6402. configurable: true
  6403. });
  6404. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  6405. get: function () {
  6406. return Camera._ORTHOGRAPHIC_CAMERA;
  6407. },
  6408. enumerable: true,
  6409. configurable: true
  6410. });
  6411. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  6412. get: function () {
  6413. return Camera._FOVMODE_VERTICAL_FIXED;
  6414. },
  6415. enumerable: true,
  6416. configurable: true
  6417. });
  6418. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  6419. get: function () {
  6420. return Camera._FOVMODE_HORIZONTAL_FIXED;
  6421. },
  6422. enumerable: true,
  6423. configurable: true
  6424. });
  6425. Camera.prototype.getActiveMeshes = function () {
  6426. return this._activeMeshes;
  6427. };
  6428. Camera.prototype.isActiveMesh = function (mesh) {
  6429. return (this._activeMeshes.indexOf(mesh) !== -1);
  6430. };
  6431. //Cache
  6432. Camera.prototype._initCache = function () {
  6433. _super.prototype._initCache.call(this);
  6434. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6435. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6436. this._cache.mode = undefined;
  6437. this._cache.minZ = undefined;
  6438. this._cache.maxZ = undefined;
  6439. this._cache.fov = undefined;
  6440. this._cache.aspectRatio = undefined;
  6441. this._cache.orthoLeft = undefined;
  6442. this._cache.orthoRight = undefined;
  6443. this._cache.orthoBottom = undefined;
  6444. this._cache.orthoTop = undefined;
  6445. this._cache.renderWidth = undefined;
  6446. this._cache.renderHeight = undefined;
  6447. };
  6448. Camera.prototype._updateCache = function (ignoreParentClass) {
  6449. if (!ignoreParentClass) {
  6450. _super.prototype._updateCache.call(this);
  6451. }
  6452. var engine = this.getEngine();
  6453. this._cache.position.copyFrom(this.position);
  6454. this._cache.upVector.copyFrom(this.upVector);
  6455. this._cache.mode = this.mode;
  6456. this._cache.minZ = this.minZ;
  6457. this._cache.maxZ = this.maxZ;
  6458. this._cache.fov = this.fov;
  6459. this._cache.aspectRatio = engine.getAspectRatio(this);
  6460. this._cache.orthoLeft = this.orthoLeft;
  6461. this._cache.orthoRight = this.orthoRight;
  6462. this._cache.orthoBottom = this.orthoBottom;
  6463. this._cache.orthoTop = this.orthoTop;
  6464. this._cache.renderWidth = engine.getRenderWidth();
  6465. this._cache.renderHeight = engine.getRenderHeight();
  6466. };
  6467. Camera.prototype._updateFromScene = function () {
  6468. this.updateCache();
  6469. this._update();
  6470. };
  6471. // Synchronized
  6472. Camera.prototype._isSynchronized = function () {
  6473. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  6474. };
  6475. Camera.prototype._isSynchronizedViewMatrix = function () {
  6476. if (!_super.prototype._isSynchronized.call(this))
  6477. return false;
  6478. return this._cache.position.equals(this.position) && this._cache.upVector.equals(this.upVector) && this.isSynchronizedWithParent();
  6479. };
  6480. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  6481. var check = this._cache.mode === this.mode && this._cache.minZ === this.minZ && this._cache.maxZ === this.maxZ;
  6482. if (!check) {
  6483. return false;
  6484. }
  6485. var engine = this.getEngine();
  6486. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6487. check = this._cache.fov === this.fov && this._cache.aspectRatio === engine.getAspectRatio(this);
  6488. }
  6489. else {
  6490. 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();
  6491. }
  6492. return check;
  6493. };
  6494. // Controls
  6495. Camera.prototype.attachControl = function (element) {
  6496. };
  6497. Camera.prototype.detachControl = function (element) {
  6498. };
  6499. Camera.prototype._update = function () {
  6500. };
  6501. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  6502. if (insertAt === void 0) { insertAt = null; }
  6503. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  6504. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  6505. return 0;
  6506. }
  6507. if (insertAt == null || insertAt < 0) {
  6508. this._postProcesses.push(postProcess);
  6509. this._postProcessesTakenIndices.push(this._postProcesses.length - 1);
  6510. return this._postProcesses.length - 1;
  6511. }
  6512. var add = 0;
  6513. if (this._postProcesses[insertAt]) {
  6514. var start = this._postProcesses.length - 1;
  6515. for (var i = start; i >= insertAt + 1; --i) {
  6516. this._postProcesses[i + 1] = this._postProcesses[i];
  6517. }
  6518. add = 1;
  6519. }
  6520. for (i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6521. if (this._postProcessesTakenIndices[i] < insertAt) {
  6522. continue;
  6523. }
  6524. start = this._postProcessesTakenIndices.length - 1;
  6525. for (var j = start; j >= i; --j) {
  6526. this._postProcessesTakenIndices[j + 1] = this._postProcessesTakenIndices[j] + add;
  6527. }
  6528. this._postProcessesTakenIndices[i] = insertAt;
  6529. break;
  6530. }
  6531. if (!add && this._postProcessesTakenIndices.indexOf(insertAt) == -1) {
  6532. this._postProcessesTakenIndices.push(insertAt);
  6533. }
  6534. var result = insertAt + add;
  6535. this._postProcesses[result] = postProcess;
  6536. return result;
  6537. };
  6538. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  6539. if (atIndices === void 0) { atIndices = null; }
  6540. var result = [];
  6541. if (!atIndices) {
  6542. var length = this._postProcesses.length;
  6543. for (var i = 0; i < length; i++) {
  6544. if (this._postProcesses[i] !== postProcess) {
  6545. continue;
  6546. }
  6547. delete this._postProcesses[i];
  6548. var index = this._postProcessesTakenIndices.indexOf(i);
  6549. this._postProcessesTakenIndices.splice(index, 1);
  6550. }
  6551. }
  6552. else {
  6553. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  6554. for (i = 0; i < atIndices.length; i++) {
  6555. var foundPostProcess = this._postProcesses[atIndices[i]];
  6556. if (foundPostProcess !== postProcess) {
  6557. result.push(i);
  6558. continue;
  6559. }
  6560. delete this._postProcesses[atIndices[i]];
  6561. index = this._postProcessesTakenIndices.indexOf(atIndices[i]);
  6562. this._postProcessesTakenIndices.splice(index, 1);
  6563. }
  6564. }
  6565. return result;
  6566. };
  6567. Camera.prototype.getWorldMatrix = function () {
  6568. if (!this._worldMatrix) {
  6569. this._worldMatrix = BABYLON.Matrix.Identity();
  6570. }
  6571. var viewMatrix = this.getViewMatrix();
  6572. viewMatrix.invertToRef(this._worldMatrix);
  6573. return this._worldMatrix;
  6574. };
  6575. Camera.prototype._getViewMatrix = function () {
  6576. return BABYLON.Matrix.Identity();
  6577. };
  6578. Camera.prototype.getViewMatrix = function () {
  6579. this._computedViewMatrix = this._computeViewMatrix();
  6580. if (!this.parent || !this.parent.getWorldMatrix || this.isSynchronized()) {
  6581. return this._computedViewMatrix;
  6582. }
  6583. if (!this._worldMatrix) {
  6584. this._worldMatrix = BABYLON.Matrix.Identity();
  6585. }
  6586. this._computedViewMatrix.invertToRef(this._worldMatrix);
  6587. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  6588. this._computedViewMatrix.invert();
  6589. this._currentRenderId = this.getScene().getRenderId();
  6590. return this._computedViewMatrix;
  6591. };
  6592. Camera.prototype._computeViewMatrix = function (force) {
  6593. if (!force && this._isSynchronizedViewMatrix()) {
  6594. return this._computedViewMatrix;
  6595. }
  6596. this._computedViewMatrix = this._getViewMatrix();
  6597. if (!this.parent || !this.parent.getWorldMatrix) {
  6598. this._currentRenderId = this.getScene().getRenderId();
  6599. }
  6600. return this._computedViewMatrix;
  6601. };
  6602. Camera.prototype.getProjectionMatrix = function (force) {
  6603. if (!force && this._isSynchronizedProjectionMatrix()) {
  6604. return this._projectionMatrix;
  6605. }
  6606. var engine = this.getEngine();
  6607. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  6608. if (this.minZ <= 0) {
  6609. this.minZ = 0.1;
  6610. }
  6611. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode);
  6612. return this._projectionMatrix;
  6613. }
  6614. var halfWidth = engine.getRenderWidth() / 2.0;
  6615. var halfHeight = engine.getRenderHeight() / 2.0;
  6616. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  6617. return this._projectionMatrix;
  6618. };
  6619. Camera.prototype.dispose = function () {
  6620. // Remove from scene
  6621. var index = this.getScene().cameras.indexOf(this);
  6622. this.getScene().cameras.splice(index, 1);
  6623. for (var i = 0; i < this._postProcessesTakenIndices.length; ++i) {
  6624. this._postProcesses[this._postProcessesTakenIndices[i]].dispose(this);
  6625. }
  6626. };
  6627. // Statics
  6628. Camera._PERSPECTIVE_CAMERA = 0;
  6629. Camera._ORTHOGRAPHIC_CAMERA = 1;
  6630. Camera._FOVMODE_VERTICAL_FIXED = 0;
  6631. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  6632. return Camera;
  6633. })(BABYLON.Node);
  6634. BABYLON.Camera = Camera;
  6635. })(BABYLON || (BABYLON = {}));
  6636. //# sourceMappingURL=babylon.camera.js.map
  6637. var BABYLON;
  6638. (function (BABYLON) {
  6639. var TargetCamera = (function (_super) {
  6640. __extends(TargetCamera, _super);
  6641. function TargetCamera(name, position, scene) {
  6642. _super.call(this, name, position, scene);
  6643. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6644. this.cameraRotation = new BABYLON.Vector2(0, 0);
  6645. this.rotation = new BABYLON.Vector3(0, 0, 0);
  6646. this.speed = 2.0;
  6647. this.noRotationConstraint = false;
  6648. this.lockedTarget = null;
  6649. this._currentTarget = BABYLON.Vector3.Zero();
  6650. this._viewMatrix = BABYLON.Matrix.Zero();
  6651. this._camMatrix = BABYLON.Matrix.Zero();
  6652. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  6653. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  6654. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  6655. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  6656. this._lookAtTemp = BABYLON.Matrix.Zero();
  6657. this._tempMatrix = BABYLON.Matrix.Zero();
  6658. }
  6659. TargetCamera.prototype._getLockedTargetPosition = function () {
  6660. if (!this.lockedTarget) {
  6661. return null;
  6662. }
  6663. return this.lockedTarget.position || this.lockedTarget;
  6664. };
  6665. // Cache
  6666. TargetCamera.prototype._initCache = function () {
  6667. _super.prototype._initCache.call(this);
  6668. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6669. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  6670. };
  6671. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  6672. if (!ignoreParentClass) {
  6673. _super.prototype._updateCache.call(this);
  6674. }
  6675. var lockedTargetPosition = this._getLockedTargetPosition();
  6676. if (!lockedTargetPosition) {
  6677. this._cache.lockedTarget = null;
  6678. }
  6679. else {
  6680. if (!this._cache.lockedTarget) {
  6681. this._cache.lockedTarget = lockedTargetPosition.clone();
  6682. }
  6683. else {
  6684. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  6685. }
  6686. }
  6687. this._cache.rotation.copyFrom(this.rotation);
  6688. };
  6689. // Synchronized
  6690. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  6691. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  6692. return false;
  6693. }
  6694. var lockedTargetPosition = this._getLockedTargetPosition();
  6695. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition) && this._cache.rotation.equals(this.rotation);
  6696. };
  6697. // Methods
  6698. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  6699. var engine = this.getEngine();
  6700. return this.speed * ((engine.getDeltaTime() / (engine.getFps() * 10.0)));
  6701. };
  6702. // Target
  6703. TargetCamera.prototype.setTarget = function (target) {
  6704. this.upVector.normalize();
  6705. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  6706. this._camMatrix.invert();
  6707. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  6708. var vDir = target.subtract(this.position);
  6709. if (vDir.x >= 0.0) {
  6710. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  6711. }
  6712. else {
  6713. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  6714. }
  6715. this.rotation.z = -Math.acos(BABYLON.Vector3.Dot(new BABYLON.Vector3(0, 1.0, 0), this.upVector));
  6716. if (isNaN(this.rotation.x)) {
  6717. this.rotation.x = 0;
  6718. }
  6719. if (isNaN(this.rotation.y)) {
  6720. this.rotation.y = 0;
  6721. }
  6722. if (isNaN(this.rotation.z)) {
  6723. this.rotation.z = 0;
  6724. }
  6725. };
  6726. TargetCamera.prototype.getTarget = function () {
  6727. return this._currentTarget;
  6728. };
  6729. TargetCamera.prototype._decideIfNeedsToMove = function () {
  6730. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  6731. };
  6732. TargetCamera.prototype._updatePosition = function () {
  6733. this.position.addInPlace(this.cameraDirection);
  6734. };
  6735. TargetCamera.prototype._update = function () {
  6736. var needToMove = this._decideIfNeedsToMove();
  6737. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  6738. // Move
  6739. if (needToMove) {
  6740. this._updatePosition();
  6741. }
  6742. // Rotate
  6743. if (needToRotate) {
  6744. this.rotation.x += this.cameraRotation.x;
  6745. this.rotation.y += this.cameraRotation.y;
  6746. if (!this.noRotationConstraint) {
  6747. var limit = (Math.PI / 2) * 0.95;
  6748. if (this.rotation.x > limit)
  6749. this.rotation.x = limit;
  6750. if (this.rotation.x < -limit)
  6751. this.rotation.x = -limit;
  6752. }
  6753. }
  6754. // Inertia
  6755. if (needToMove) {
  6756. if (Math.abs(this.cameraDirection.x) < BABYLON.Engine.Epsilon) {
  6757. this.cameraDirection.x = 0;
  6758. }
  6759. if (Math.abs(this.cameraDirection.y) < BABYLON.Engine.Epsilon) {
  6760. this.cameraDirection.y = 0;
  6761. }
  6762. if (Math.abs(this.cameraDirection.z) < BABYLON.Engine.Epsilon) {
  6763. this.cameraDirection.z = 0;
  6764. }
  6765. this.cameraDirection.scaleInPlace(this.inertia);
  6766. }
  6767. if (needToRotate) {
  6768. if (Math.abs(this.cameraRotation.x) < BABYLON.Engine.Epsilon) {
  6769. this.cameraRotation.x = 0;
  6770. }
  6771. if (Math.abs(this.cameraRotation.y) < BABYLON.Engine.Epsilon) {
  6772. this.cameraRotation.y = 0;
  6773. }
  6774. this.cameraRotation.scaleInPlace(this.inertia);
  6775. }
  6776. };
  6777. TargetCamera.prototype._getViewMatrix = function () {
  6778. if (!this.lockedTarget) {
  6779. // Compute
  6780. if (this.upVector.x != 0 || this.upVector.y != 1.0 || this.upVector.z != 0) {
  6781. BABYLON.Matrix.LookAtLHToRef(BABYLON.Vector3.Zero(), this._referencePoint, this.upVector, this._lookAtTemp);
  6782. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6783. this._lookAtTemp.multiplyToRef(this._cameraRotationMatrix, this._tempMatrix);
  6784. this._lookAtTemp.invert();
  6785. this._tempMatrix.multiplyToRef(this._lookAtTemp, this._cameraRotationMatrix);
  6786. }
  6787. else {
  6788. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  6789. }
  6790. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  6791. // Computing target and final matrix
  6792. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  6793. }
  6794. else {
  6795. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  6796. }
  6797. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  6798. return this._viewMatrix;
  6799. };
  6800. return TargetCamera;
  6801. })(BABYLON.Camera);
  6802. BABYLON.TargetCamera = TargetCamera;
  6803. })(BABYLON || (BABYLON = {}));
  6804. //# sourceMappingURL=babylon.targetCamera.js.map
  6805. var BABYLON;
  6806. (function (BABYLON) {
  6807. var FollowCamera = (function (_super) {
  6808. __extends(FollowCamera, _super);
  6809. function FollowCamera(name, position, scene) {
  6810. _super.call(this, name, position, scene);
  6811. this.radius = 12;
  6812. this.rotationOffset = 0;
  6813. this.heightOffset = 4;
  6814. this.cameraAcceleration = 0.05;
  6815. this.maxCameraSpeed = 20;
  6816. }
  6817. FollowCamera.prototype.getRadians = function (degrees) {
  6818. return degrees * Math.PI / 180;
  6819. };
  6820. FollowCamera.prototype.follow = function (cameraTarget) {
  6821. if (!cameraTarget)
  6822. return;
  6823. var radians = this.getRadians(this.rotationOffset) + cameraTarget.rotation.y;
  6824. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  6825. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  6826. var dx = targetX - this.position.x;
  6827. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  6828. var dz = (targetZ) - this.position.z;
  6829. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  6830. var vy = dy * this.cameraAcceleration;
  6831. var vz = dz * this.cameraAcceleration * 2;
  6832. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  6833. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6834. }
  6835. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  6836. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6837. }
  6838. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  6839. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  6840. }
  6841. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  6842. this.setTarget(cameraTarget.position);
  6843. };
  6844. FollowCamera.prototype._update = function () {
  6845. _super.prototype._update.call(this);
  6846. this.follow(this.target);
  6847. };
  6848. return FollowCamera;
  6849. })(BABYLON.TargetCamera);
  6850. BABYLON.FollowCamera = FollowCamera;
  6851. })(BABYLON || (BABYLON = {}));
  6852. //# sourceMappingURL=babylon.followCamera.js.map
  6853. var BABYLON;
  6854. (function (BABYLON) {
  6855. var FreeCamera = (function (_super) {
  6856. __extends(FreeCamera, _super);
  6857. function FreeCamera(name, position, scene) {
  6858. _super.call(this, name, position, scene);
  6859. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  6860. this.keysUp = [38];
  6861. this.keysDown = [40];
  6862. this.keysLeft = [37];
  6863. this.keysRight = [39];
  6864. this.checkCollisions = false;
  6865. this.applyGravity = false;
  6866. this.angularSensibility = 2000.0;
  6867. this._keys = [];
  6868. this._collider = new BABYLON.Collider();
  6869. this._needMoveForGravity = true;
  6870. this._oldPosition = BABYLON.Vector3.Zero();
  6871. this._diffPosition = BABYLON.Vector3.Zero();
  6872. this._newPosition = BABYLON.Vector3.Zero();
  6873. }
  6874. // Controls
  6875. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  6876. var _this = this;
  6877. var previousPosition;
  6878. var engine = this.getEngine();
  6879. if (this._attachedElement) {
  6880. return;
  6881. }
  6882. this._attachedElement = element;
  6883. if (this._onMouseDown === undefined) {
  6884. this._onMouseDown = function (evt) {
  6885. previousPosition = {
  6886. x: evt.clientX,
  6887. y: evt.clientY
  6888. };
  6889. if (!noPreventDefault) {
  6890. evt.preventDefault();
  6891. }
  6892. };
  6893. this._onMouseUp = function (evt) {
  6894. previousPosition = null;
  6895. if (!noPreventDefault) {
  6896. evt.preventDefault();
  6897. }
  6898. };
  6899. this._onMouseOut = function (evt) {
  6900. previousPosition = null;
  6901. _this._keys = [];
  6902. if (!noPreventDefault) {
  6903. evt.preventDefault();
  6904. }
  6905. };
  6906. this._onMouseMove = function (evt) {
  6907. if (!previousPosition && !engine.isPointerLock) {
  6908. return;
  6909. }
  6910. var offsetX;
  6911. var offsetY;
  6912. if (!engine.isPointerLock) {
  6913. offsetX = evt.clientX - previousPosition.x;
  6914. offsetY = evt.clientY - previousPosition.y;
  6915. }
  6916. else {
  6917. offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  6918. offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  6919. }
  6920. _this.cameraRotation.y += offsetX / _this.angularSensibility;
  6921. _this.cameraRotation.x += offsetY / _this.angularSensibility;
  6922. previousPosition = {
  6923. x: evt.clientX,
  6924. y: evt.clientY
  6925. };
  6926. if (!noPreventDefault) {
  6927. evt.preventDefault();
  6928. }
  6929. };
  6930. this._onKeyDown = function (evt) {
  6931. 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) {
  6932. var index = _this._keys.indexOf(evt.keyCode);
  6933. if (index === -1) {
  6934. _this._keys.push(evt.keyCode);
  6935. }
  6936. if (!noPreventDefault) {
  6937. evt.preventDefault();
  6938. }
  6939. }
  6940. };
  6941. this._onKeyUp = function (evt) {
  6942. 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) {
  6943. var index = _this._keys.indexOf(evt.keyCode);
  6944. if (index >= 0) {
  6945. _this._keys.splice(index, 1);
  6946. }
  6947. if (!noPreventDefault) {
  6948. evt.preventDefault();
  6949. }
  6950. }
  6951. };
  6952. this._onLostFocus = function () {
  6953. _this._keys = [];
  6954. };
  6955. this._reset = function () {
  6956. _this._keys = [];
  6957. previousPosition = null;
  6958. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  6959. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  6960. };
  6961. }
  6962. element.addEventListener("mousedown", this._onMouseDown, false);
  6963. element.addEventListener("mouseup", this._onMouseUp, false);
  6964. element.addEventListener("mouseout", this._onMouseOut, false);
  6965. element.addEventListener("mousemove", this._onMouseMove, false);
  6966. BABYLON.Tools.RegisterTopRootEvents([
  6967. { name: "keydown", handler: this._onKeyDown },
  6968. { name: "keyup", handler: this._onKeyUp },
  6969. { name: "blur", handler: this._onLostFocus }
  6970. ]);
  6971. };
  6972. FreeCamera.prototype.detachControl = function (element) {
  6973. if (this._attachedElement != element) {
  6974. return;
  6975. }
  6976. element.removeEventListener("mousedown", this._onMouseDown);
  6977. element.removeEventListener("mouseup", this._onMouseUp);
  6978. element.removeEventListener("mouseout", this._onMouseOut);
  6979. element.removeEventListener("mousemove", this._onMouseMove);
  6980. BABYLON.Tools.UnregisterTopRootEvents([
  6981. { name: "keydown", handler: this._onKeyDown },
  6982. { name: "keyup", handler: this._onKeyUp },
  6983. { name: "blur", handler: this._onLostFocus }
  6984. ]);
  6985. this._attachedElement = null;
  6986. if (this._reset) {
  6987. this._reset();
  6988. }
  6989. };
  6990. FreeCamera.prototype._collideWithWorld = function (velocity) {
  6991. var globalPosition;
  6992. if (this.parent) {
  6993. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  6994. }
  6995. else {
  6996. globalPosition = this.position;
  6997. }
  6998. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  6999. this._collider.radius = this.ellipsoid;
  7000. this.getScene()._getNewPosition(this._oldPosition, velocity, this._collider, 3, this._newPosition);
  7001. this._newPosition.subtractToRef(this._oldPosition, this._diffPosition);
  7002. if (this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  7003. this.position.addInPlace(this._diffPosition);
  7004. if (this.onCollide) {
  7005. this.onCollide(this._collider.collidedMesh);
  7006. }
  7007. }
  7008. };
  7009. FreeCamera.prototype._checkInputs = function () {
  7010. if (!this._localDirection) {
  7011. this._localDirection = BABYLON.Vector3.Zero();
  7012. this._transformedDirection = BABYLON.Vector3.Zero();
  7013. }
  7014. for (var index = 0; index < this._keys.length; index++) {
  7015. var keyCode = this._keys[index];
  7016. var speed = this._computeLocalCameraSpeed();
  7017. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7018. this._localDirection.copyFromFloats(-speed, 0, 0);
  7019. }
  7020. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7021. this._localDirection.copyFromFloats(0, 0, speed);
  7022. }
  7023. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7024. this._localDirection.copyFromFloats(speed, 0, 0);
  7025. }
  7026. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7027. this._localDirection.copyFromFloats(0, 0, -speed);
  7028. }
  7029. this.getViewMatrix().invertToRef(this._cameraTransformMatrix);
  7030. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  7031. this.cameraDirection.addInPlace(this._transformedDirection);
  7032. }
  7033. };
  7034. FreeCamera.prototype._decideIfNeedsToMove = function () {
  7035. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  7036. };
  7037. FreeCamera.prototype._updatePosition = function () {
  7038. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  7039. this._collideWithWorld(this.cameraDirection);
  7040. if (this.applyGravity) {
  7041. var oldPosition = this.position;
  7042. this._collideWithWorld(this.getScene().gravity);
  7043. this._needMoveForGravity = (BABYLON.Vector3.DistanceSquared(oldPosition, this.position) != 0);
  7044. }
  7045. }
  7046. else {
  7047. this.position.addInPlace(this.cameraDirection);
  7048. }
  7049. };
  7050. FreeCamera.prototype._update = function () {
  7051. this._checkInputs();
  7052. _super.prototype._update.call(this);
  7053. };
  7054. return FreeCamera;
  7055. })(BABYLON.TargetCamera);
  7056. BABYLON.FreeCamera = FreeCamera;
  7057. })(BABYLON || (BABYLON = {}));
  7058. //# sourceMappingURL=babylon.freeCamera.js.map
  7059. var BABYLON;
  7060. (function (BABYLON) {
  7061. // We're mainly based on the logic defined into the FreeCamera code
  7062. var TouchCamera = (function (_super) {
  7063. __extends(TouchCamera, _super);
  7064. function TouchCamera(name, position, scene) {
  7065. _super.call(this, name, position, scene);
  7066. this._offsetX = null;
  7067. this._offsetY = null;
  7068. this._pointerCount = 0;
  7069. this._pointerPressed = [];
  7070. this.angularSensibility = 200000.0;
  7071. this.moveSensibility = 500.0;
  7072. }
  7073. TouchCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7074. var _this = this;
  7075. var previousPosition;
  7076. if (this._attachedCanvas) {
  7077. return;
  7078. }
  7079. this._attachedCanvas = canvas;
  7080. if (this._onPointerDown === undefined) {
  7081. this._onPointerDown = function (evt) {
  7082. if (!noPreventDefault) {
  7083. evt.preventDefault();
  7084. }
  7085. _this._pointerPressed.push(evt.pointerId);
  7086. if (_this._pointerPressed.length !== 1) {
  7087. return;
  7088. }
  7089. previousPosition = {
  7090. x: evt.clientX,
  7091. y: evt.clientY
  7092. };
  7093. };
  7094. this._onPointerUp = function (evt) {
  7095. if (!noPreventDefault) {
  7096. evt.preventDefault();
  7097. }
  7098. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7099. if (index === -1) {
  7100. return;
  7101. }
  7102. _this._pointerPressed.splice(index, 1);
  7103. if (index != 0) {
  7104. return;
  7105. }
  7106. previousPosition = null;
  7107. _this._offsetX = null;
  7108. _this._offsetY = null;
  7109. };
  7110. this._onPointerMove = function (evt) {
  7111. if (!noPreventDefault) {
  7112. evt.preventDefault();
  7113. }
  7114. if (!previousPosition) {
  7115. return;
  7116. }
  7117. var index = _this._pointerPressed.indexOf(evt.pointerId);
  7118. if (index != 0) {
  7119. return;
  7120. }
  7121. _this._offsetX = evt.clientX - previousPosition.x;
  7122. _this._offsetY = -(evt.clientY - previousPosition.y);
  7123. };
  7124. this._onLostFocus = function () {
  7125. _this._offsetX = null;
  7126. _this._offsetY = null;
  7127. };
  7128. }
  7129. canvas.addEventListener("pointerdown", this._onPointerDown);
  7130. canvas.addEventListener("pointerup", this._onPointerUp);
  7131. canvas.addEventListener("pointerout", this._onPointerUp);
  7132. canvas.addEventListener("pointermove", this._onPointerMove);
  7133. BABYLON.Tools.RegisterTopRootEvents([
  7134. { name: "blur", handler: this._onLostFocus }
  7135. ]);
  7136. };
  7137. TouchCamera.prototype.detachControl = function (canvas) {
  7138. if (this._attachedCanvas != canvas) {
  7139. return;
  7140. }
  7141. canvas.removeEventListener("pointerdown", this._onPointerDown);
  7142. canvas.removeEventListener("pointerup", this._onPointerUp);
  7143. canvas.removeEventListener("pointerout", this._onPointerUp);
  7144. canvas.removeEventListener("pointermove", this._onPointerMove);
  7145. BABYLON.Tools.UnregisterTopRootEvents([
  7146. { name: "blur", handler: this._onLostFocus }
  7147. ]);
  7148. this._attachedCanvas = null;
  7149. };
  7150. TouchCamera.prototype._checkInputs = function () {
  7151. if (!this._offsetX) {
  7152. return;
  7153. }
  7154. this.cameraRotation.y += this._offsetX / this.angularSensibility;
  7155. if (this._pointerPressed.length > 1) {
  7156. this.cameraRotation.x += -this._offsetY / this.angularSensibility;
  7157. }
  7158. else {
  7159. var speed = this._computeLocalCameraSpeed();
  7160. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7161. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7162. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7163. }
  7164. };
  7165. return TouchCamera;
  7166. })(BABYLON.FreeCamera);
  7167. BABYLON.TouchCamera = TouchCamera;
  7168. })(BABYLON || (BABYLON = {}));
  7169. //# sourceMappingURL=babylon.touchCamera.js.map
  7170. var BABYLON;
  7171. (function (BABYLON) {
  7172. // We're mainly based on the logic defined into the FreeCamera code
  7173. var DeviceOrientationCamera = (function (_super) {
  7174. __extends(DeviceOrientationCamera, _super);
  7175. function DeviceOrientationCamera(name, position, scene) {
  7176. var _this = this;
  7177. _super.call(this, name, position, scene);
  7178. this._offsetX = null;
  7179. this._offsetY = null;
  7180. this._orientationGamma = 0;
  7181. this._orientationBeta = 0;
  7182. this._initialOrientationGamma = 0;
  7183. this._initialOrientationBeta = 0;
  7184. this.angularSensibility = 10000.0;
  7185. this.moveSensibility = 50.0;
  7186. window.addEventListener("resize", function () {
  7187. _this._initialOrientationGamma = null;
  7188. }, false);
  7189. }
  7190. DeviceOrientationCamera.prototype.attachControl = function (canvas, noPreventDefault) {
  7191. var _this = this;
  7192. if (this._attachedCanvas) {
  7193. return;
  7194. }
  7195. this._attachedCanvas = canvas;
  7196. if (!this._orientationChanged) {
  7197. this._orientationChanged = function (evt) {
  7198. if (!_this._initialOrientationGamma) {
  7199. _this._initialOrientationGamma = evt.gamma;
  7200. _this._initialOrientationBeta = evt.beta;
  7201. }
  7202. _this._orientationGamma = evt.gamma;
  7203. _this._orientationBeta = evt.beta;
  7204. _this._offsetY = (_this._initialOrientationBeta - _this._orientationBeta);
  7205. _this._offsetX = (_this._initialOrientationGamma - _this._orientationGamma);
  7206. };
  7207. }
  7208. window.addEventListener("deviceorientation", this._orientationChanged);
  7209. };
  7210. DeviceOrientationCamera.prototype.detachControl = function (canvas) {
  7211. if (this._attachedCanvas != canvas) {
  7212. return;
  7213. }
  7214. window.removeEventListener("deviceorientation", this._orientationChanged);
  7215. this._attachedCanvas = null;
  7216. this._orientationGamma = 0;
  7217. this._orientationBeta = 0;
  7218. this._initialOrientationGamma = 0;
  7219. this._initialOrientationBeta = 0;
  7220. };
  7221. DeviceOrientationCamera.prototype._checkInputs = function () {
  7222. if (!this._offsetX) {
  7223. return;
  7224. }
  7225. this.cameraRotation.y -= this._offsetX / this.angularSensibility;
  7226. var speed = this._computeLocalCameraSpeed();
  7227. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.moveSensibility);
  7228. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, 0, this._cameraRotationMatrix);
  7229. this.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, this._cameraRotationMatrix));
  7230. };
  7231. return DeviceOrientationCamera;
  7232. })(BABYLON.FreeCamera);
  7233. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  7234. })(BABYLON || (BABYLON = {}));
  7235. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  7236. var BABYLON;
  7237. (function (BABYLON) {
  7238. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  7239. var ArcRotateCamera = (function (_super) {
  7240. __extends(ArcRotateCamera, _super);
  7241. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  7242. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  7243. this.alpha = alpha;
  7244. this.beta = beta;
  7245. this.radius = radius;
  7246. this.target = target;
  7247. this.inertialAlphaOffset = 0;
  7248. this.inertialBetaOffset = 0;
  7249. this.inertialRadiusOffset = 0;
  7250. this.lowerAlphaLimit = null;
  7251. this.upperAlphaLimit = null;
  7252. this.lowerBetaLimit = 0.01;
  7253. this.upperBetaLimit = Math.PI;
  7254. this.lowerRadiusLimit = null;
  7255. this.upperRadiusLimit = null;
  7256. this.angularSensibility = 1000.0;
  7257. this.wheelPrecision = 3.0;
  7258. this.keysUp = [38];
  7259. this.keysDown = [40];
  7260. this.keysLeft = [37];
  7261. this.keysRight = [39];
  7262. this.zoomOnFactor = 1;
  7263. this.targetScreenOffset = BABYLON.Vector2.Zero();
  7264. this._keys = [];
  7265. this._viewMatrix = new BABYLON.Matrix();
  7266. this.checkCollisions = false;
  7267. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  7268. this._collider = new BABYLON.Collider();
  7269. this._previousPosition = BABYLON.Vector3.Zero();
  7270. this._collisionVelocity = BABYLON.Vector3.Zero();
  7271. this._newPosition = BABYLON.Vector3.Zero();
  7272. // Pinch
  7273. // value for pinch step scaling
  7274. // set to 20 by default
  7275. this.pinchPrecision = 20;
  7276. this.getViewMatrix();
  7277. }
  7278. ArcRotateCamera.prototype._getTargetPosition = function () {
  7279. return this.target.position || this.target;
  7280. };
  7281. // Cache
  7282. ArcRotateCamera.prototype._initCache = function () {
  7283. _super.prototype._initCache.call(this);
  7284. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  7285. this._cache.alpha = undefined;
  7286. this._cache.beta = undefined;
  7287. this._cache.radius = undefined;
  7288. this._cache.targetScreenOffset = undefined;
  7289. };
  7290. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  7291. if (!ignoreParentClass) {
  7292. _super.prototype._updateCache.call(this);
  7293. }
  7294. this._cache.target.copyFrom(this._getTargetPosition());
  7295. this._cache.alpha = this.alpha;
  7296. this._cache.beta = this.beta;
  7297. this._cache.radius = this.radius;
  7298. this._cache.targetScreenOffset = this.targetScreenOffset.clone();
  7299. };
  7300. // Synchronized
  7301. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  7302. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  7303. return false;
  7304. 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);
  7305. };
  7306. // Methods
  7307. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault) {
  7308. var _this = this;
  7309. var previousPosition;
  7310. var pointerId;
  7311. // to know if pinch started
  7312. var pinchStarted = false;
  7313. // two pinch point on X
  7314. // that will use for find if user action is pinch open or pinch close
  7315. var pinchPointX1, pinchPointX2;
  7316. if (this._attachedElement) {
  7317. return;
  7318. }
  7319. this._attachedElement = element;
  7320. var engine = this.getEngine();
  7321. if (this._onPointerDown === undefined) {
  7322. this._onPointerDown = function (evt) {
  7323. if (pointerId) {
  7324. return;
  7325. }
  7326. pointerId = evt.pointerId;
  7327. previousPosition = {
  7328. x: evt.clientX,
  7329. y: evt.clientY
  7330. };
  7331. if (!noPreventDefault) {
  7332. evt.preventDefault();
  7333. }
  7334. };
  7335. this._onPointerUp = function (evt) {
  7336. previousPosition = null;
  7337. pointerId = null;
  7338. if (!noPreventDefault) {
  7339. evt.preventDefault();
  7340. }
  7341. };
  7342. this._onPointerMove = function (evt) {
  7343. if (!previousPosition) {
  7344. return;
  7345. }
  7346. if (pointerId !== evt.pointerId) {
  7347. return;
  7348. }
  7349. // return pinch is started
  7350. if (pinchStarted) {
  7351. return;
  7352. }
  7353. var offsetX = evt.clientX - previousPosition.x;
  7354. var offsetY = evt.clientY - previousPosition.y;
  7355. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7356. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7357. previousPosition = {
  7358. x: evt.clientX,
  7359. y: evt.clientY
  7360. };
  7361. if (!noPreventDefault) {
  7362. evt.preventDefault();
  7363. }
  7364. };
  7365. this._onMouseMove = function (evt) {
  7366. if (!engine.isPointerLock) {
  7367. return;
  7368. }
  7369. // return pinch is started
  7370. if (pinchStarted) {
  7371. return;
  7372. }
  7373. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  7374. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  7375. _this.inertialAlphaOffset -= offsetX / _this.angularSensibility;
  7376. _this.inertialBetaOffset -= offsetY / _this.angularSensibility;
  7377. if (!noPreventDefault) {
  7378. evt.preventDefault();
  7379. }
  7380. };
  7381. this._wheel = function (event) {
  7382. var delta = 0;
  7383. if (event.wheelDelta) {
  7384. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  7385. }
  7386. else if (event.detail) {
  7387. delta = -event.detail / _this.wheelPrecision;
  7388. }
  7389. if (delta)
  7390. _this.inertialRadiusOffset += delta;
  7391. if (event.preventDefault) {
  7392. if (!noPreventDefault) {
  7393. event.preventDefault();
  7394. }
  7395. }
  7396. };
  7397. this._onKeyDown = function (evt) {
  7398. 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) {
  7399. var index = _this._keys.indexOf(evt.keyCode);
  7400. if (index === -1) {
  7401. _this._keys.push(evt.keyCode);
  7402. }
  7403. if (evt.preventDefault) {
  7404. if (!noPreventDefault) {
  7405. evt.preventDefault();
  7406. }
  7407. }
  7408. }
  7409. };
  7410. this._onKeyUp = function (evt) {
  7411. 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) {
  7412. var index = _this._keys.indexOf(evt.keyCode);
  7413. if (index >= 0) {
  7414. _this._keys.splice(index, 1);
  7415. }
  7416. if (evt.preventDefault) {
  7417. if (!noPreventDefault) {
  7418. evt.preventDefault();
  7419. }
  7420. }
  7421. }
  7422. };
  7423. this._onLostFocus = function () {
  7424. _this._keys = [];
  7425. pointerId = null;
  7426. };
  7427. this._onGestureStart = function (e) {
  7428. if (window.MSGesture === undefined) {
  7429. return;
  7430. }
  7431. if (!_this._MSGestureHandler) {
  7432. _this._MSGestureHandler = new MSGesture();
  7433. _this._MSGestureHandler.target = element;
  7434. }
  7435. _this._MSGestureHandler.addPointer(e.pointerId);
  7436. };
  7437. this._onGesture = function (e) {
  7438. _this.radius *= e.scale;
  7439. if (e.preventDefault) {
  7440. if (!noPreventDefault) {
  7441. e.stopPropagation();
  7442. e.preventDefault();
  7443. }
  7444. }
  7445. };
  7446. this._reset = function () {
  7447. _this._keys = [];
  7448. _this.inertialAlphaOffset = 0;
  7449. _this.inertialBetaOffset = 0;
  7450. _this.inertialRadiusOffset = 0;
  7451. previousPosition = null;
  7452. pointerId = null;
  7453. };
  7454. this._touchStart = function (event) {
  7455. if (event.touches.length === 2) {
  7456. //-- start pinch if two fingers on the screen
  7457. pinchStarted = true;
  7458. _this._pinchStart(event);
  7459. }
  7460. };
  7461. this._touchMove = function (event) {
  7462. if (pinchStarted) {
  7463. //-- make scaling
  7464. _this._pinchMove(event);
  7465. }
  7466. };
  7467. this._touchEnd = function (event) {
  7468. if (pinchStarted) {
  7469. //-- end of pinch
  7470. _this._pinchEnd(event);
  7471. }
  7472. };
  7473. this._pinchStart = function (event) {
  7474. // save origin touch point
  7475. pinchPointX1 = event.touches[0].clientX;
  7476. pinchPointX2 = event.touches[1].clientX;
  7477. // block the camera
  7478. // if not it rotate around target during pinch
  7479. pinchStarted = true;
  7480. };
  7481. this._pinchMove = function (event) {
  7482. // variable for new camera's radius
  7483. var delta = 0;
  7484. // variables to know if pinch open or pinch close
  7485. var direction = 1;
  7486. var distanceXOrigine, distanceXNow;
  7487. if (event.touches.length !== 2)
  7488. return;
  7489. // calculate absolute distances of the two fingers
  7490. distanceXOrigine = Math.abs(pinchPointX1 - pinchPointX2);
  7491. distanceXNow = Math.abs(event.touches[0].clientX - event.touches[1].clientX);
  7492. // if distanceXNow < distanceXOrigine -> pinch close so direction = -1
  7493. if (distanceXNow < distanceXOrigine) {
  7494. direction = -1;
  7495. }
  7496. // calculate new radius
  7497. delta = (_this.pinchPrecision / (_this.wheelPrecision * 40)) * direction;
  7498. // set new radius
  7499. _this.inertialRadiusOffset -= delta;
  7500. // save origin touch point
  7501. pinchPointX1 = event.touches[0].clientX;
  7502. pinchPointX2 = event.touches[1].clientX;
  7503. };
  7504. this._pinchEnd = function (event) {
  7505. // cancel pinch and deblock camera rotation
  7506. pinchStarted = false;
  7507. };
  7508. }
  7509. element.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  7510. element.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  7511. element.addEventListener(eventPrefix + "out", this._onPointerUp, false);
  7512. element.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  7513. element.addEventListener("mousemove", this._onMouseMove, false);
  7514. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  7515. element.addEventListener("MSGestureChange", this._onGesture, false);
  7516. element.addEventListener('mousewheel', this._wheel, false);
  7517. element.addEventListener('DOMMouseScroll', this._wheel, false);
  7518. // pinch
  7519. element.addEventListener('touchstart', this._touchStart, false);
  7520. element.addEventListener('touchmove', this._touchMove, false);
  7521. element.addEventListener('touchend', this._touchEnd, false);
  7522. BABYLON.Tools.RegisterTopRootEvents([
  7523. { name: "keydown", handler: this._onKeyDown },
  7524. { name: "keyup", handler: this._onKeyUp },
  7525. { name: "blur", handler: this._onLostFocus }
  7526. ]);
  7527. };
  7528. ArcRotateCamera.prototype.detachControl = function (element) {
  7529. if (this._attachedElement != element) {
  7530. return;
  7531. }
  7532. element.removeEventListener(eventPrefix + "down", this._onPointerDown);
  7533. element.removeEventListener(eventPrefix + "up", this._onPointerUp);
  7534. element.removeEventListener(eventPrefix + "out", this._onPointerUp);
  7535. element.removeEventListener(eventPrefix + "move", this._onPointerMove);
  7536. element.removeEventListener("mousemove", this._onMouseMove);
  7537. element.removeEventListener("MSPointerDown", this._onGestureStart);
  7538. element.removeEventListener("MSGestureChange", this._onGesture);
  7539. element.removeEventListener('mousewheel', this._wheel);
  7540. element.removeEventListener('DOMMouseScroll', this._wheel);
  7541. // pinch
  7542. element.removeEventListener('touchstart', this._touchStart);
  7543. element.removeEventListener('touchmove', this._touchMove);
  7544. element.removeEventListener('touchend', this._touchEnd);
  7545. BABYLON.Tools.UnregisterTopRootEvents([
  7546. { name: "keydown", handler: this._onKeyDown },
  7547. { name: "keyup", handler: this._onKeyUp },
  7548. { name: "blur", handler: this._onLostFocus }
  7549. ]);
  7550. this._MSGestureHandler = null;
  7551. this._attachedElement = null;
  7552. if (this._reset) {
  7553. this._reset();
  7554. }
  7555. };
  7556. ArcRotateCamera.prototype._update = function () {
  7557. for (var index = 0; index < this._keys.length; index++) {
  7558. var keyCode = this._keys[index];
  7559. if (this.keysLeft.indexOf(keyCode) !== -1) {
  7560. this.inertialAlphaOffset -= 0.01;
  7561. }
  7562. else if (this.keysUp.indexOf(keyCode) !== -1) {
  7563. this.inertialBetaOffset -= 0.01;
  7564. }
  7565. else if (this.keysRight.indexOf(keyCode) !== -1) {
  7566. this.inertialAlphaOffset += 0.01;
  7567. }
  7568. else if (this.keysDown.indexOf(keyCode) !== -1) {
  7569. this.inertialBetaOffset += 0.01;
  7570. }
  7571. }
  7572. // Inertia
  7573. if (this.inertialAlphaOffset != 0 || this.inertialBetaOffset != 0 || this.inertialRadiusOffset != 0) {
  7574. this.alpha += this.inertialAlphaOffset;
  7575. this.beta += this.inertialBetaOffset;
  7576. this.radius -= this.inertialRadiusOffset;
  7577. this.inertialAlphaOffset *= this.inertia;
  7578. this.inertialBetaOffset *= this.inertia;
  7579. this.inertialRadiusOffset *= this.inertia;
  7580. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Engine.Epsilon)
  7581. this.inertialAlphaOffset = 0;
  7582. if (Math.abs(this.inertialBetaOffset) < BABYLON.Engine.Epsilon)
  7583. this.inertialBetaOffset = 0;
  7584. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Engine.Epsilon)
  7585. this.inertialRadiusOffset = 0;
  7586. }
  7587. // Limits
  7588. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  7589. this.alpha = this.lowerAlphaLimit;
  7590. }
  7591. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  7592. this.alpha = this.upperAlphaLimit;
  7593. }
  7594. if (this.lowerBetaLimit && this.beta < this.lowerBetaLimit) {
  7595. this.beta = this.lowerBetaLimit;
  7596. }
  7597. if (this.upperBetaLimit && this.beta > this.upperBetaLimit) {
  7598. this.beta = this.upperBetaLimit;
  7599. }
  7600. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  7601. this.radius = this.lowerRadiusLimit;
  7602. }
  7603. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  7604. this.radius = this.upperRadiusLimit;
  7605. }
  7606. };
  7607. ArcRotateCamera.prototype.setPosition = function (position) {
  7608. var radiusv3 = position.subtract(this._getTargetPosition());
  7609. this.radius = radiusv3.length();
  7610. // Alpha
  7611. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  7612. if (radiusv3.z < 0) {
  7613. this.alpha = 2 * Math.PI - this.alpha;
  7614. }
  7615. // Beta
  7616. this.beta = Math.acos(radiusv3.y / this.radius);
  7617. };
  7618. ArcRotateCamera.prototype._getViewMatrix = function () {
  7619. // Compute
  7620. var cosa = Math.cos(this.alpha);
  7621. var sina = Math.sin(this.alpha);
  7622. var cosb = Math.cos(this.beta);
  7623. var sinb = Math.sin(this.beta);
  7624. var target = this._getTargetPosition();
  7625. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this.position);
  7626. if (this.checkCollisions) {
  7627. this._collider.radius = this.collisionRadius;
  7628. this.position.subtractToRef(this._previousPosition, this._collisionVelocity);
  7629. this.getScene()._getNewPosition(this._previousPosition, this._collisionVelocity, this._collider, 3, this._newPosition);
  7630. if (!this._newPosition.equalsWithEpsilon(this.position)) {
  7631. this.position.copyFrom(this._previousPosition);
  7632. this.alpha = this._previousAlpha;
  7633. this.beta = this._previousBeta;
  7634. this.radius = this._previousRadius;
  7635. if (this.onCollide) {
  7636. this.onCollide(this._collider.collidedMesh);
  7637. }
  7638. }
  7639. }
  7640. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._viewMatrix);
  7641. this._previousAlpha = this.alpha;
  7642. this._previousBeta = this.beta;
  7643. this._previousRadius = this.radius;
  7644. this._previousPosition.copyFrom(this.position);
  7645. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  7646. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  7647. return this._viewMatrix;
  7648. };
  7649. ArcRotateCamera.prototype.zoomOn = function (meshes) {
  7650. meshes = meshes || this.getScene().meshes;
  7651. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  7652. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  7653. this.radius = distance * this.zoomOnFactor;
  7654. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance });
  7655. };
  7656. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance) {
  7657. var meshesOrMinMaxVector;
  7658. var distance;
  7659. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  7660. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  7661. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  7662. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  7663. }
  7664. else {
  7665. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  7666. distance = meshesOrMinMaxVectorAndDistance.distance;
  7667. }
  7668. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  7669. this.maxZ = distance * 2;
  7670. };
  7671. return ArcRotateCamera;
  7672. })(BABYLON.Camera);
  7673. BABYLON.ArcRotateCamera = ArcRotateCamera;
  7674. })(BABYLON || (BABYLON = {}));
  7675. //# sourceMappingURL=babylon.arcRotateCamera.js.mapvar BABYLON;
  7676. (function (BABYLON) {
  7677. /**
  7678. * Represents a scene to be rendered by the engine.
  7679. * @see http://doc.babylonjs.com/page.php?p=21911
  7680. */
  7681. var Scene = (function () {
  7682. /**
  7683. * @constructor
  7684. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  7685. */
  7686. function Scene(engine) {
  7687. // Members
  7688. this.autoClear = true;
  7689. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7690. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  7691. this.forceWireframe = false;
  7692. this.forcePointsCloud = false;
  7693. this.forceShowBoundingBoxes = false;
  7694. this.animationsEnabled = true;
  7695. 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
  7696. // Fog
  7697. /**
  7698. * is fog enabled on this scene.
  7699. * @type {boolean}
  7700. */
  7701. this.fogEnabled = true;
  7702. this.fogMode = Scene.FOGMODE_NONE;
  7703. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  7704. this.fogDensity = 0.1;
  7705. this.fogStart = 0;
  7706. this.fogEnd = 1000.0;
  7707. // Lights
  7708. /**
  7709. * is shadow enabled on this scene.
  7710. * @type {boolean}
  7711. */
  7712. this.shadowsEnabled = true;
  7713. /**
  7714. * is light enabled on this scene.
  7715. * @type {boolean}
  7716. */
  7717. this.lightsEnabled = true;
  7718. /**
  7719. * All of the lights added to this scene.
  7720. * @see BABYLON.Light
  7721. * @type {BABYLON.Light[]}
  7722. */
  7723. this.lights = new Array();
  7724. // Cameras
  7725. /**
  7726. * All of the cameras added to this scene.
  7727. * @see BABYLON.Camera
  7728. * @type {BABYLON.Camera[]}
  7729. */
  7730. this.cameras = new Array();
  7731. this.activeCameras = new Array();
  7732. // Meshes
  7733. /**
  7734. * All of the (abstract) meshes added to this scene.
  7735. * @see BABYLON.AbstractMesh
  7736. * @type {BABYLON.AbstractMesh[]}
  7737. */
  7738. this.meshes = new Array();
  7739. // Geometries
  7740. this._geometries = new Array();
  7741. this.materials = new Array();
  7742. this.multiMaterials = new Array();
  7743. this.defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  7744. // Textures
  7745. this.texturesEnabled = true;
  7746. this.textures = new Array();
  7747. // Particles
  7748. this.particlesEnabled = true;
  7749. this.particleSystems = new Array();
  7750. // Sprites
  7751. this.spritesEnabled = true;
  7752. this.spriteManagers = new Array();
  7753. // Layers
  7754. this.layers = new Array();
  7755. // Skeletons
  7756. this.skeletonsEnabled = true;
  7757. this.skeletons = new Array();
  7758. // Lens flares
  7759. this.lensFlaresEnabled = true;
  7760. this.lensFlareSystems = new Array();
  7761. // Collisions
  7762. this.collisionsEnabled = true;
  7763. this.gravity = new BABYLON.Vector3(0, -9.0, 0);
  7764. // Postprocesses
  7765. this.postProcessesEnabled = true;
  7766. // Customs render targets
  7767. this.renderTargetsEnabled = true;
  7768. this.dumpNextRenderTargets = false;
  7769. this.customRenderTargets = new Array();
  7770. // Imported meshes
  7771. this.importedMeshesFiles = new Array();
  7772. this._actionManagers = new Array();
  7773. this._meshesForIntersections = new BABYLON.SmartArray(256);
  7774. // Procedural textures
  7775. this.proceduralTexturesEnabled = true;
  7776. this._proceduralTextures = new Array();
  7777. this.soundTracks = new Array();
  7778. this._audioEnabled = true;
  7779. this._totalVertices = 0;
  7780. this._activeVertices = 0;
  7781. this._activeParticles = 0;
  7782. this._lastFrameDuration = 0;
  7783. this._evaluateActiveMeshesDuration = 0;
  7784. this._renderTargetsDuration = 0;
  7785. this._particlesDuration = 0;
  7786. this._renderDuration = 0;
  7787. this._spritesDuration = 0;
  7788. this._animationRatio = 0;
  7789. this._renderId = 0;
  7790. this._executeWhenReadyTimeoutId = -1;
  7791. this._toBeDisposed = new BABYLON.SmartArray(256);
  7792. this._onReadyCallbacks = new Array();
  7793. this._pendingData = []; //ANY
  7794. this._onBeforeRenderCallbacks = new Array();
  7795. this._onAfterRenderCallbacks = new Array();
  7796. this._activeMeshes = new BABYLON.SmartArray(256);
  7797. this._processedMaterials = new BABYLON.SmartArray(256);
  7798. this._renderTargets = new BABYLON.SmartArray(256);
  7799. this._activeParticleSystems = new BABYLON.SmartArray(256);
  7800. this._activeSkeletons = new BABYLON.SmartArray(32);
  7801. this._activeBones = 0;
  7802. this._activeAnimatables = new Array();
  7803. this._transformMatrix = BABYLON.Matrix.Zero();
  7804. this._scaledPosition = BABYLON.Vector3.Zero();
  7805. this._scaledVelocity = BABYLON.Vector3.Zero();
  7806. this._engine = engine;
  7807. engine.scenes.push(this);
  7808. this._renderingManager = new BABYLON.RenderingManager(this);
  7809. this.postProcessManager = new BABYLON.PostProcessManager(this);
  7810. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  7811. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  7812. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  7813. this.attachControl();
  7814. this._debugLayer = new BABYLON.DebugLayer(this);
  7815. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  7816. }
  7817. Object.defineProperty(Scene, "FOGMODE_NONE", {
  7818. get: function () {
  7819. return Scene._FOGMODE_NONE;
  7820. },
  7821. enumerable: true,
  7822. configurable: true
  7823. });
  7824. Object.defineProperty(Scene, "FOGMODE_EXP", {
  7825. get: function () {
  7826. return Scene._FOGMODE_EXP;
  7827. },
  7828. enumerable: true,
  7829. configurable: true
  7830. });
  7831. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  7832. get: function () {
  7833. return Scene._FOGMODE_EXP2;
  7834. },
  7835. enumerable: true,
  7836. configurable: true
  7837. });
  7838. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  7839. get: function () {
  7840. return Scene._FOGMODE_LINEAR;
  7841. },
  7842. enumerable: true,
  7843. configurable: true
  7844. });
  7845. Object.defineProperty(Scene.prototype, "debugLayer", {
  7846. // Properties
  7847. get: function () {
  7848. return this._debugLayer;
  7849. },
  7850. enumerable: true,
  7851. configurable: true
  7852. });
  7853. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  7854. /**
  7855. * The mesh that is currently under the pointer.
  7856. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  7857. */
  7858. get: function () {
  7859. return this._meshUnderPointer;
  7860. },
  7861. enumerable: true,
  7862. configurable: true
  7863. });
  7864. Object.defineProperty(Scene.prototype, "pointerX", {
  7865. /**
  7866. * Current on-screen X position of the pointer
  7867. * @return {number} X position of the pointer
  7868. */
  7869. get: function () {
  7870. return this._pointerX;
  7871. },
  7872. enumerable: true,
  7873. configurable: true
  7874. });
  7875. Object.defineProperty(Scene.prototype, "pointerY", {
  7876. /**
  7877. * Current on-screen Y position of the pointer
  7878. * @return {number} Y position of the pointer
  7879. */
  7880. get: function () {
  7881. return this._pointerY;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Scene.prototype.getCachedMaterial = function () {
  7887. return this._cachedMaterial;
  7888. };
  7889. Scene.prototype.getBoundingBoxRenderer = function () {
  7890. return this._boundingBoxRenderer;
  7891. };
  7892. Scene.prototype.getOutlineRenderer = function () {
  7893. return this._outlineRenderer;
  7894. };
  7895. Scene.prototype.getEngine = function () {
  7896. return this._engine;
  7897. };
  7898. Scene.prototype.getTotalVertices = function () {
  7899. return this._totalVertices;
  7900. };
  7901. Scene.prototype.getActiveVertices = function () {
  7902. return this._activeVertices;
  7903. };
  7904. Scene.prototype.getActiveParticles = function () {
  7905. return this._activeParticles;
  7906. };
  7907. Scene.prototype.getActiveBones = function () {
  7908. return this._activeBones;
  7909. };
  7910. // Stats
  7911. Scene.prototype.getLastFrameDuration = function () {
  7912. return this._lastFrameDuration;
  7913. };
  7914. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  7915. return this._evaluateActiveMeshesDuration;
  7916. };
  7917. Scene.prototype.getActiveMeshes = function () {
  7918. return this._activeMeshes;
  7919. };
  7920. Scene.prototype.getRenderTargetsDuration = function () {
  7921. return this._renderTargetsDuration;
  7922. };
  7923. Scene.prototype.getRenderDuration = function () {
  7924. return this._renderDuration;
  7925. };
  7926. Scene.prototype.getParticlesDuration = function () {
  7927. return this._particlesDuration;
  7928. };
  7929. Scene.prototype.getSpritesDuration = function () {
  7930. return this._spritesDuration;
  7931. };
  7932. Scene.prototype.getAnimationRatio = function () {
  7933. return this._animationRatio;
  7934. };
  7935. Scene.prototype.getRenderId = function () {
  7936. return this._renderId;
  7937. };
  7938. Scene.prototype.incrementRenderId = function () {
  7939. this._renderId++;
  7940. };
  7941. Scene.prototype._updatePointerPosition = function (evt) {
  7942. var canvasRect = this._engine.getRenderingCanvasClientRect();
  7943. this._pointerX = evt.clientX - canvasRect.left;
  7944. this._pointerY = evt.clientY - canvasRect.top;
  7945. if (this.cameraToUseForPointers) {
  7946. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  7947. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  7948. }
  7949. };
  7950. // Pointers handling
  7951. Scene.prototype.attachControl = function () {
  7952. var _this = this;
  7953. this._onPointerMove = function (evt) {
  7954. var canvas = _this._engine.getRenderingCanvas();
  7955. _this._updatePointerPosition(evt);
  7956. 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);
  7957. if (pickResult.hit) {
  7958. _this._meshUnderPointer = pickResult.pickedMesh;
  7959. _this.setPointerOverMesh(pickResult.pickedMesh);
  7960. canvas.style.cursor = "pointer";
  7961. }
  7962. else {
  7963. _this.setPointerOverMesh(null);
  7964. canvas.style.cursor = "";
  7965. _this._meshUnderPointer = null;
  7966. }
  7967. };
  7968. this._onPointerDown = function (evt) {
  7969. var predicate = null;
  7970. if (!_this.onPointerDown) {
  7971. predicate = function (mesh) {
  7972. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasPickTriggers;
  7973. };
  7974. }
  7975. _this._updatePointerPosition(evt);
  7976. var pickResult = _this.pick(_this._pointerX, _this._pointerY, predicate, false, _this.cameraToUseForPointers);
  7977. if (pickResult.hit) {
  7978. if (pickResult.pickedMesh.actionManager) {
  7979. switch (evt.button) {
  7980. case 0:
  7981. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7982. break;
  7983. case 1:
  7984. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7985. break;
  7986. case 2:
  7987. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7988. break;
  7989. }
  7990. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  7991. }
  7992. }
  7993. if (_this.onPointerDown) {
  7994. _this.onPointerDown(evt, pickResult);
  7995. }
  7996. };
  7997. this._onKeyDown = function (evt) {
  7998. if (_this.actionManager) {
  7999. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8000. }
  8001. };
  8002. this._onKeyUp = function (evt) {
  8003. if (_this.actionManager) {
  8004. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  8005. }
  8006. };
  8007. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8008. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "move", this._onPointerMove, false);
  8009. this._engine.getRenderingCanvas().addEventListener(eventPrefix + "down", this._onPointerDown, false);
  8010. BABYLON.Tools.RegisterTopRootEvents([
  8011. { name: "keydown", handler: this._onKeyDown },
  8012. { name: "keyup", handler: this._onKeyUp }
  8013. ]);
  8014. };
  8015. Scene.prototype.detachControl = function () {
  8016. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  8017. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "move", this._onPointerMove);
  8018. this._engine.getRenderingCanvas().removeEventListener(eventPrefix + "down", this._onPointerDown);
  8019. BABYLON.Tools.UnregisterTopRootEvents([
  8020. { name: "keydown", handler: this._onKeyDown },
  8021. { name: "keyup", handler: this._onKeyUp }
  8022. ]);
  8023. };
  8024. // Ready
  8025. Scene.prototype.isReady = function () {
  8026. if (this._pendingData.length > 0) {
  8027. return false;
  8028. }
  8029. for (var index = 0; index < this._geometries.length; index++) {
  8030. var geometry = this._geometries[index];
  8031. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  8032. return false;
  8033. }
  8034. }
  8035. for (index = 0; index < this.meshes.length; index++) {
  8036. var mesh = this.meshes[index];
  8037. if (!mesh.isReady()) {
  8038. return false;
  8039. }
  8040. var mat = mesh.material;
  8041. if (mat) {
  8042. if (!mat.isReady(mesh)) {
  8043. return false;
  8044. }
  8045. }
  8046. }
  8047. return true;
  8048. };
  8049. Scene.prototype.resetCachedMaterial = function () {
  8050. this._cachedMaterial = null;
  8051. };
  8052. Scene.prototype.registerBeforeRender = function (func) {
  8053. this._onBeforeRenderCallbacks.push(func);
  8054. };
  8055. Scene.prototype.unregisterBeforeRender = function (func) {
  8056. var index = this._onBeforeRenderCallbacks.indexOf(func);
  8057. if (index > -1) {
  8058. this._onBeforeRenderCallbacks.splice(index, 1);
  8059. }
  8060. };
  8061. Scene.prototype.registerAfterRender = function (func) {
  8062. this._onAfterRenderCallbacks.push(func);
  8063. };
  8064. Scene.prototype.unregisterAfterRender = function (func) {
  8065. var index = this._onAfterRenderCallbacks.indexOf(func);
  8066. if (index > -1) {
  8067. this._onAfterRenderCallbacks.splice(index, 1);
  8068. }
  8069. };
  8070. Scene.prototype._addPendingData = function (data) {
  8071. this._pendingData.push(data);
  8072. };
  8073. Scene.prototype._removePendingData = function (data) {
  8074. var index = this._pendingData.indexOf(data);
  8075. if (index !== -1) {
  8076. this._pendingData.splice(index, 1);
  8077. }
  8078. };
  8079. Scene.prototype.getWaitingItemsCount = function () {
  8080. return this._pendingData.length;
  8081. };
  8082. /**
  8083. * Registers a function to be executed when the scene is ready.
  8084. * @param {Function} func - the function to be executed.
  8085. */
  8086. Scene.prototype.executeWhenReady = function (func) {
  8087. var _this = this;
  8088. this._onReadyCallbacks.push(func);
  8089. if (this._executeWhenReadyTimeoutId !== -1) {
  8090. return;
  8091. }
  8092. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8093. _this._checkIsReady();
  8094. }, 150);
  8095. };
  8096. Scene.prototype._checkIsReady = function () {
  8097. var _this = this;
  8098. if (this.isReady()) {
  8099. this._onReadyCallbacks.forEach(function (func) {
  8100. func();
  8101. });
  8102. this._onReadyCallbacks = [];
  8103. this._executeWhenReadyTimeoutId = -1;
  8104. return;
  8105. }
  8106. this._executeWhenReadyTimeoutId = setTimeout(function () {
  8107. _this._checkIsReady();
  8108. }, 150);
  8109. };
  8110. // Animations
  8111. /**
  8112. * Will start the animation sequence of a given target
  8113. * @param target - the target
  8114. * @param {number} from - from which frame should animation start
  8115. * @param {number} to - till which frame should animation run.
  8116. * @param {boolean} [loop] - should the animation loop
  8117. * @param {number} [speedRatio] - the speed in which to run the animation
  8118. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  8119. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  8120. * @return {BABYLON.Animatable} the animatable object created for this animation
  8121. * @see BABYLON.Animatable
  8122. * @see http://doc.babylonjs.com/page.php?p=22081
  8123. */
  8124. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  8125. if (speedRatio === undefined) {
  8126. speedRatio = 1.0;
  8127. }
  8128. this.stopAnimation(target);
  8129. if (!animatable) {
  8130. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  8131. }
  8132. // Local animations
  8133. if (target.animations) {
  8134. animatable.appendAnimations(target, target.animations);
  8135. }
  8136. // Children animations
  8137. if (target.getAnimatables) {
  8138. var animatables = target.getAnimatables();
  8139. for (var index = 0; index < animatables.length; index++) {
  8140. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  8141. }
  8142. }
  8143. return animatable;
  8144. };
  8145. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  8146. if (speedRatio === undefined) {
  8147. speedRatio = 1.0;
  8148. }
  8149. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  8150. return animatable;
  8151. };
  8152. Scene.prototype.getAnimatableByTarget = function (target) {
  8153. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8154. if (this._activeAnimatables[index].target === target) {
  8155. return this._activeAnimatables[index];
  8156. }
  8157. }
  8158. return null;
  8159. };
  8160. /**
  8161. * Will stop the animation of the given target
  8162. * @param target - the target
  8163. * @see beginAnimation
  8164. */
  8165. Scene.prototype.stopAnimation = function (target) {
  8166. var animatable = this.getAnimatableByTarget(target);
  8167. if (animatable) {
  8168. animatable.stop();
  8169. }
  8170. };
  8171. Scene.prototype._animate = function () {
  8172. if (!this.animationsEnabled) {
  8173. return;
  8174. }
  8175. if (!this._animationStartDate) {
  8176. this._animationStartDate = BABYLON.Tools.Now;
  8177. }
  8178. // Getting time
  8179. var now = BABYLON.Tools.Now;
  8180. var delay = now - this._animationStartDate;
  8181. for (var index = 0; index < this._activeAnimatables.length; index++) {
  8182. if (!this._activeAnimatables[index]._animate(delay)) {
  8183. this._activeAnimatables.splice(index, 1);
  8184. index--;
  8185. }
  8186. }
  8187. };
  8188. // Matrix
  8189. Scene.prototype.getViewMatrix = function () {
  8190. return this._viewMatrix;
  8191. };
  8192. Scene.prototype.getProjectionMatrix = function () {
  8193. return this._projectionMatrix;
  8194. };
  8195. Scene.prototype.getTransformMatrix = function () {
  8196. return this._transformMatrix;
  8197. };
  8198. Scene.prototype.setTransformMatrix = function (view, projection) {
  8199. this._viewMatrix = view;
  8200. this._projectionMatrix = projection;
  8201. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  8202. };
  8203. // Methods
  8204. /**
  8205. * sets the active camera of the scene using its ID
  8206. * @param {string} id - the camera's ID
  8207. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8208. * @see activeCamera
  8209. */
  8210. Scene.prototype.setActiveCameraByID = function (id) {
  8211. var camera = this.getCameraByID(id);
  8212. if (camera) {
  8213. this.activeCamera = camera;
  8214. return camera;
  8215. }
  8216. return null;
  8217. };
  8218. /**
  8219. * sets the active camera of the scene using its name
  8220. * @param {string} name - the camera's name
  8221. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  8222. * @see activeCamera
  8223. */
  8224. Scene.prototype.setActiveCameraByName = function (name) {
  8225. var camera = this.getCameraByName(name);
  8226. if (camera) {
  8227. this.activeCamera = camera;
  8228. return camera;
  8229. }
  8230. return null;
  8231. };
  8232. /**
  8233. * get a material using its id
  8234. * @param {string} the material's ID
  8235. * @return {BABYLON.Material|null} the material or null if none found.
  8236. */
  8237. Scene.prototype.getMaterialByID = function (id) {
  8238. for (var index = 0; index < this.materials.length; index++) {
  8239. if (this.materials[index].id === id) {
  8240. return this.materials[index];
  8241. }
  8242. }
  8243. return null;
  8244. };
  8245. /**
  8246. * get a material using its name
  8247. * @param {string} the material's name
  8248. * @return {BABYLON.Material|null} the material or null if none found.
  8249. */
  8250. Scene.prototype.getMaterialByName = function (name) {
  8251. for (var index = 0; index < this.materials.length; index++) {
  8252. if (this.materials[index].name === name) {
  8253. return this.materials[index];
  8254. }
  8255. }
  8256. return null;
  8257. };
  8258. Scene.prototype.getCameraByID = function (id) {
  8259. for (var index = 0; index < this.cameras.length; index++) {
  8260. if (this.cameras[index].id === id) {
  8261. return this.cameras[index];
  8262. }
  8263. }
  8264. return null;
  8265. };
  8266. /**
  8267. * get a camera using its name
  8268. * @param {string} the camera's name
  8269. * @return {BABYLON.Camera|null} the camera or null if none found.
  8270. */
  8271. Scene.prototype.getCameraByName = function (name) {
  8272. for (var index = 0; index < this.cameras.length; index++) {
  8273. if (this.cameras[index].name === name) {
  8274. return this.cameras[index];
  8275. }
  8276. }
  8277. return null;
  8278. };
  8279. /**
  8280. * get a light node using its name
  8281. * @param {string} the light's name
  8282. * @return {BABYLON.Light|null} the light or null if none found.
  8283. */
  8284. Scene.prototype.getLightByName = function (name) {
  8285. for (var index = 0; index < this.lights.length; index++) {
  8286. if (this.lights[index].name === name) {
  8287. return this.lights[index];
  8288. }
  8289. }
  8290. return null;
  8291. };
  8292. /**
  8293. * get a light node using its ID
  8294. * @param {string} the light's id
  8295. * @return {BABYLON.Light|null} the light or null if none found.
  8296. */
  8297. Scene.prototype.getLightByID = function (id) {
  8298. for (var index = 0; index < this.lights.length; index++) {
  8299. if (this.lights[index].id === id) {
  8300. return this.lights[index];
  8301. }
  8302. }
  8303. return null;
  8304. };
  8305. /**
  8306. * get a geometry using its ID
  8307. * @param {string} the geometry's id
  8308. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  8309. */
  8310. Scene.prototype.getGeometryByID = function (id) {
  8311. for (var index = 0; index < this._geometries.length; index++) {
  8312. if (this._geometries[index].id === id) {
  8313. return this._geometries[index];
  8314. }
  8315. }
  8316. return null;
  8317. };
  8318. /**
  8319. * add a new geometry to this scene.
  8320. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  8321. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  8322. * @return {boolean} was the geometry added or not
  8323. */
  8324. Scene.prototype.pushGeometry = function (geometry, force) {
  8325. if (!force && this.getGeometryByID(geometry.id)) {
  8326. return false;
  8327. }
  8328. this._geometries.push(geometry);
  8329. return true;
  8330. };
  8331. Scene.prototype.getGeometries = function () {
  8332. return this._geometries;
  8333. };
  8334. /**
  8335. * Get a the first added mesh found of a given ID
  8336. * @param {string} id - the id to search for
  8337. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8338. */
  8339. Scene.prototype.getMeshByID = function (id) {
  8340. for (var index = 0; index < this.meshes.length; index++) {
  8341. if (this.meshes[index].id === id) {
  8342. return this.meshes[index];
  8343. }
  8344. }
  8345. return null;
  8346. };
  8347. /**
  8348. * Get a the last added mesh found of a given ID
  8349. * @param {string} id - the id to search for
  8350. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  8351. */
  8352. Scene.prototype.getLastMeshByID = function (id) {
  8353. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8354. if (this.meshes[index].id === id) {
  8355. return this.meshes[index];
  8356. }
  8357. }
  8358. return null;
  8359. };
  8360. /**
  8361. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  8362. * @param {string} id - the id to search for
  8363. * @return {BABYLON.Node|null} the node found or null if not found at all.
  8364. */
  8365. Scene.prototype.getLastEntryByID = function (id) {
  8366. for (var index = this.meshes.length - 1; index >= 0; index--) {
  8367. if (this.meshes[index].id === id) {
  8368. return this.meshes[index];
  8369. }
  8370. }
  8371. for (index = this.cameras.length - 1; index >= 0; index--) {
  8372. if (this.cameras[index].id === id) {
  8373. return this.cameras[index];
  8374. }
  8375. }
  8376. for (index = this.lights.length - 1; index >= 0; index--) {
  8377. if (this.lights[index].id === id) {
  8378. return this.lights[index];
  8379. }
  8380. }
  8381. return null;
  8382. };
  8383. Scene.prototype.getNodeByName = function (name) {
  8384. var mesh = this.getMeshByName(name);
  8385. if (mesh) {
  8386. return mesh;
  8387. }
  8388. var light = this.getLightByName(name);
  8389. if (light) {
  8390. return light;
  8391. }
  8392. return this.getCameraByName(name);
  8393. };
  8394. Scene.prototype.getMeshByName = function (name) {
  8395. for (var index = 0; index < this.meshes.length; index++) {
  8396. if (this.meshes[index].name === name) {
  8397. return this.meshes[index];
  8398. }
  8399. }
  8400. return null;
  8401. };
  8402. Scene.prototype.getSoundByName = function (name) {
  8403. for (var index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  8404. if (this.mainSoundTrack.soundCollection[index].name === name) {
  8405. return this.mainSoundTrack.soundCollection[index];
  8406. }
  8407. }
  8408. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  8409. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  8410. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  8411. return this.soundTracks[sdIndex].soundCollection[index];
  8412. }
  8413. }
  8414. }
  8415. return null;
  8416. };
  8417. Scene.prototype.getLastSkeletonByID = function (id) {
  8418. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  8419. if (this.skeletons[index].id === id) {
  8420. return this.skeletons[index];
  8421. }
  8422. }
  8423. return null;
  8424. };
  8425. Scene.prototype.getSkeletonById = function (id) {
  8426. for (var index = 0; index < this.skeletons.length; index++) {
  8427. if (this.skeletons[index].id === id) {
  8428. return this.skeletons[index];
  8429. }
  8430. }
  8431. return null;
  8432. };
  8433. Scene.prototype.getSkeletonByName = function (name) {
  8434. for (var index = 0; index < this.skeletons.length; index++) {
  8435. if (this.skeletons[index].name === name) {
  8436. return this.skeletons[index];
  8437. }
  8438. }
  8439. return null;
  8440. };
  8441. Scene.prototype.isActiveMesh = function (mesh) {
  8442. return (this._activeMeshes.indexOf(mesh) !== -1);
  8443. };
  8444. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  8445. if (mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  8446. var material = subMesh.getMaterial();
  8447. if (mesh.showSubMeshesBoundingBox) {
  8448. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  8449. }
  8450. if (material) {
  8451. // Render targets
  8452. if (material.getRenderTargetTextures) {
  8453. if (this._processedMaterials.indexOf(material) === -1) {
  8454. this._processedMaterials.push(material);
  8455. this._renderTargets.concat(material.getRenderTargetTextures());
  8456. }
  8457. }
  8458. // Dispatch
  8459. this._activeVertices += subMesh.indexCount;
  8460. this._renderingManager.dispatch(subMesh);
  8461. }
  8462. }
  8463. };
  8464. Scene.prototype._evaluateActiveMeshes = function () {
  8465. this.activeCamera._activeMeshes.reset();
  8466. this._activeMeshes.reset();
  8467. this._renderingManager.reset();
  8468. this._processedMaterials.reset();
  8469. this._activeParticleSystems.reset();
  8470. this._activeSkeletons.reset();
  8471. this._boundingBoxRenderer.reset();
  8472. if (!this._frustumPlanes) {
  8473. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  8474. }
  8475. else {
  8476. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  8477. }
  8478. // Meshes
  8479. var meshes;
  8480. var len;
  8481. if (this._selectionOctree) {
  8482. var selection = this._selectionOctree.select(this._frustumPlanes);
  8483. meshes = selection.data;
  8484. len = selection.length;
  8485. }
  8486. else {
  8487. len = this.meshes.length;
  8488. meshes = this.meshes;
  8489. }
  8490. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  8491. var mesh = meshes[meshIndex];
  8492. if (mesh.isBlocked) {
  8493. continue;
  8494. }
  8495. this._totalVertices += mesh.getTotalVertices();
  8496. if (!mesh.isReady()) {
  8497. continue;
  8498. }
  8499. mesh.computeWorldMatrix();
  8500. // Intersections
  8501. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  8502. this._meshesForIntersections.pushNoDuplicate(mesh);
  8503. }
  8504. // Switch to current LOD
  8505. var meshLOD = mesh.getLOD(this.activeCamera);
  8506. if (!meshLOD) {
  8507. continue;
  8508. }
  8509. mesh._preActivate();
  8510. if (mesh.isEnabled() && mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  8511. this._activeMeshes.push(mesh);
  8512. this.activeCamera._activeMeshes.push(mesh);
  8513. mesh._activate(this._renderId);
  8514. this._activeMesh(meshLOD);
  8515. }
  8516. }
  8517. // Particle systems
  8518. var beforeParticlesDate = BABYLON.Tools.Now;
  8519. if (this.particlesEnabled) {
  8520. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  8521. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  8522. var particleSystem = this.particleSystems[particleIndex];
  8523. if (!particleSystem.isStarted()) {
  8524. continue;
  8525. }
  8526. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  8527. this._activeParticleSystems.push(particleSystem);
  8528. particleSystem.animate();
  8529. }
  8530. }
  8531. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  8532. }
  8533. this._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  8534. };
  8535. Scene.prototype._activeMesh = function (mesh) {
  8536. if (mesh.skeleton && this.skeletonsEnabled) {
  8537. this._activeSkeletons.pushNoDuplicate(mesh.skeleton);
  8538. }
  8539. if (mesh.showBoundingBox || this.forceShowBoundingBoxes) {
  8540. this._boundingBoxRenderer.renderList.push(mesh.getBoundingInfo().boundingBox);
  8541. }
  8542. if (mesh && mesh.subMeshes) {
  8543. // Submeshes Octrees
  8544. var len;
  8545. var subMeshes;
  8546. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  8547. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  8548. len = intersections.length;
  8549. subMeshes = intersections.data;
  8550. }
  8551. else {
  8552. subMeshes = mesh.subMeshes;
  8553. len = subMeshes.length;
  8554. }
  8555. for (var subIndex = 0; subIndex < len; subIndex++) {
  8556. var subMesh = subMeshes[subIndex];
  8557. this._evaluateSubMesh(subMesh, mesh);
  8558. }
  8559. }
  8560. };
  8561. Scene.prototype.updateTransformMatrix = function (force) {
  8562. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  8563. };
  8564. Scene.prototype._renderForCamera = function (camera) {
  8565. var engine = this._engine;
  8566. this.activeCamera = camera;
  8567. if (!this.activeCamera)
  8568. throw new Error("Active camera not set");
  8569. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8570. // Viewport
  8571. engine.setViewport(this.activeCamera.viewport);
  8572. // Camera
  8573. this._renderId++;
  8574. this.updateTransformMatrix();
  8575. if (this.beforeCameraRender) {
  8576. this.beforeCameraRender(this.activeCamera);
  8577. }
  8578. // Meshes
  8579. var beforeEvaluateActiveMeshesDate = BABYLON.Tools.Now;
  8580. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  8581. this._evaluateActiveMeshes();
  8582. this._evaluateActiveMeshesDuration += BABYLON.Tools.Now - beforeEvaluateActiveMeshesDate;
  8583. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  8584. for (var skeletonIndex = 0; skeletonIndex < this._activeSkeletons.length; skeletonIndex++) {
  8585. var skeleton = this._activeSkeletons.data[skeletonIndex];
  8586. skeleton.prepare();
  8587. }
  8588. // Render targets
  8589. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8590. if (this.renderTargetsEnabled) {
  8591. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8592. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  8593. var renderTarget = this._renderTargets.data[renderIndex];
  8594. if (renderTarget._shouldRender()) {
  8595. this._renderId++;
  8596. renderTarget.render(false, this.dumpNextRenderTargets);
  8597. }
  8598. }
  8599. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  8600. this._renderId++;
  8601. }
  8602. if (this._renderTargets.length > 0) {
  8603. engine.restoreDefaultFramebuffer();
  8604. }
  8605. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8606. // Prepare Frame
  8607. this.postProcessManager._prepareFrame();
  8608. var beforeRenderDate = BABYLON.Tools.Now;
  8609. // Backgrounds
  8610. if (this.layers.length) {
  8611. engine.setDepthBuffer(false);
  8612. var layerIndex;
  8613. var layer;
  8614. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8615. layer = this.layers[layerIndex];
  8616. if (layer.isBackground) {
  8617. layer.render();
  8618. }
  8619. }
  8620. engine.setDepthBuffer(true);
  8621. }
  8622. // Render
  8623. BABYLON.Tools.StartPerformanceCounter("Main render");
  8624. this._renderingManager.render(null, null, true, true);
  8625. BABYLON.Tools.EndPerformanceCounter("Main render");
  8626. // Bounding boxes
  8627. this._boundingBoxRenderer.render();
  8628. // Lens flares
  8629. if (this.lensFlaresEnabled) {
  8630. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8631. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  8632. this.lensFlareSystems[lensFlareSystemIndex].render();
  8633. }
  8634. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  8635. }
  8636. // Foregrounds
  8637. if (this.layers.length) {
  8638. engine.setDepthBuffer(false);
  8639. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  8640. layer = this.layers[layerIndex];
  8641. if (!layer.isBackground) {
  8642. layer.render();
  8643. }
  8644. }
  8645. engine.setDepthBuffer(true);
  8646. }
  8647. this._renderDuration += BABYLON.Tools.Now - beforeRenderDate;
  8648. // Finalize frame
  8649. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  8650. // Update camera
  8651. this.activeCamera._updateFromScene();
  8652. // Reset some special arrays
  8653. this._renderTargets.reset();
  8654. if (this.afterCameraRender) {
  8655. this.afterCameraRender(this.activeCamera);
  8656. }
  8657. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  8658. };
  8659. Scene.prototype._processSubCameras = function (camera) {
  8660. if (camera.subCameras.length === 0) {
  8661. this._renderForCamera(camera);
  8662. return;
  8663. }
  8664. for (var index = 0; index < camera.subCameras.length; index++) {
  8665. this._renderForCamera(camera.subCameras[index]);
  8666. }
  8667. this.activeCamera = camera;
  8668. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  8669. // Update camera
  8670. this.activeCamera._updateFromScene();
  8671. };
  8672. Scene.prototype._checkIntersections = function () {
  8673. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  8674. var sourceMesh = this._meshesForIntersections.data[index];
  8675. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  8676. var action = sourceMesh.actionManager.actions[actionIndex];
  8677. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8678. var parameters = action.getTriggerParameter();
  8679. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  8680. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  8681. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8682. if (areIntersecting && currentIntersectionInProgress === -1) {
  8683. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  8684. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8685. sourceMesh._intersectionsInProgress.push(otherMesh);
  8686. }
  8687. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8688. sourceMesh._intersectionsInProgress.push(otherMesh);
  8689. }
  8690. }
  8691. else if (!areIntersecting && currentIntersectionInProgress > -1 && action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  8692. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh));
  8693. var indexOfOther = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  8694. if (indexOfOther > -1) {
  8695. sourceMesh._intersectionsInProgress.splice(indexOfOther, 1);
  8696. }
  8697. }
  8698. }
  8699. }
  8700. }
  8701. };
  8702. Scene.prototype.render = function () {
  8703. var startDate = BABYLON.Tools.Now;
  8704. this._particlesDuration = 0;
  8705. this._spritesDuration = 0;
  8706. this._activeParticles = 0;
  8707. this._renderDuration = 0;
  8708. this._renderTargetsDuration = 0;
  8709. this._evaluateActiveMeshesDuration = 0;
  8710. this._totalVertices = 0;
  8711. this._activeVertices = 0;
  8712. this._activeBones = 0;
  8713. this.getEngine().resetDrawCalls();
  8714. this._meshesForIntersections.reset();
  8715. this.resetCachedMaterial();
  8716. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  8717. // Actions
  8718. if (this.actionManager) {
  8719. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  8720. }
  8721. // Before render
  8722. if (this.beforeRender) {
  8723. this.beforeRender();
  8724. }
  8725. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  8726. this._onBeforeRenderCallbacks[callbackIndex]();
  8727. }
  8728. // Animations
  8729. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  8730. this._animationRatio = deltaTime * (60.0 / 1000.0);
  8731. this._animate();
  8732. // Physics
  8733. if (this._physicsEngine) {
  8734. BABYLON.Tools.StartPerformanceCounter("Physics");
  8735. this._physicsEngine._runOneStep(deltaTime / 1000.0);
  8736. BABYLON.Tools.EndPerformanceCounter("Physics");
  8737. }
  8738. // Customs render targets
  8739. var beforeRenderTargetDate = BABYLON.Tools.Now;
  8740. var engine = this.getEngine();
  8741. var currentActiveCamera = this.activeCamera;
  8742. if (this.renderTargetsEnabled) {
  8743. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8744. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  8745. var renderTarget = this.customRenderTargets[customIndex];
  8746. if (renderTarget._shouldRender()) {
  8747. this._renderId++;
  8748. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  8749. if (!this.activeCamera)
  8750. throw new Error("Active camera not set");
  8751. // Viewport
  8752. engine.setViewport(this.activeCamera.viewport);
  8753. // Camera
  8754. this.updateTransformMatrix();
  8755. renderTarget.render(false, this.dumpNextRenderTargets);
  8756. }
  8757. }
  8758. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  8759. this._renderId++;
  8760. }
  8761. if (this.customRenderTargets.length > 0) {
  8762. engine.restoreDefaultFramebuffer();
  8763. }
  8764. this._renderTargetsDuration += BABYLON.Tools.Now - beforeRenderTargetDate;
  8765. this.activeCamera = currentActiveCamera;
  8766. // Procedural textures
  8767. if (this.proceduralTexturesEnabled) {
  8768. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8769. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  8770. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  8771. if (proceduralTexture._shouldRender()) {
  8772. proceduralTexture.render();
  8773. }
  8774. }
  8775. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  8776. }
  8777. // Clear
  8778. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true);
  8779. // Shadows
  8780. if (this.shadowsEnabled) {
  8781. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  8782. var light = this.lights[lightIndex];
  8783. var shadowGenerator = light.getShadowGenerator();
  8784. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  8785. this._renderTargets.push(shadowGenerator.getShadowMap());
  8786. }
  8787. }
  8788. }
  8789. // Depth renderer
  8790. if (this._depthRenderer) {
  8791. this._renderTargets.push(this._depthRenderer.getDepthMap());
  8792. }
  8793. // RenderPipeline
  8794. this.postProcessRenderPipelineManager.update();
  8795. // Multi-cameras?
  8796. if (this.activeCameras.length > 0) {
  8797. var currentRenderId = this._renderId;
  8798. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  8799. this._renderId = currentRenderId;
  8800. this._processSubCameras(this.activeCameras[cameraIndex]);
  8801. }
  8802. }
  8803. else {
  8804. if (!this.activeCamera) {
  8805. throw new Error("No camera defined");
  8806. }
  8807. this._processSubCameras(this.activeCamera);
  8808. }
  8809. // Intersection checks
  8810. this._checkIntersections();
  8811. // Update the audio listener attached to the camera
  8812. this._updateAudioParameters();
  8813. // After render
  8814. if (this.afterRender) {
  8815. this.afterRender();
  8816. }
  8817. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  8818. this._onAfterRenderCallbacks[callbackIndex]();
  8819. }
  8820. for (var index = 0; index < this._toBeDisposed.length; index++) {
  8821. this._toBeDisposed.data[index].dispose();
  8822. this._toBeDisposed[index] = null;
  8823. }
  8824. this._toBeDisposed.reset();
  8825. if (this.dumpNextRenderTargets) {
  8826. this.dumpNextRenderTargets = false;
  8827. }
  8828. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  8829. this._lastFrameDuration = BABYLON.Tools.Now - startDate;
  8830. };
  8831. Scene.prototype._updateAudioParameters = function () {
  8832. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 0)) {
  8833. return;
  8834. }
  8835. var listeningCamera;
  8836. var audioEngine = BABYLON.Engine.audioEngine;
  8837. if (this.activeCameras.length > 0) {
  8838. listeningCamera = this.activeCameras[0];
  8839. }
  8840. else {
  8841. listeningCamera = this.activeCamera;
  8842. }
  8843. if (listeningCamera && audioEngine.canUseWebAudio) {
  8844. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  8845. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  8846. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  8847. cameraDirection.normalize();
  8848. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  8849. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8850. var sound = this.mainSoundTrack.soundCollection[i];
  8851. if (sound.useCustomAttenuation) {
  8852. sound.updateDistanceFromListener();
  8853. }
  8854. }
  8855. for (i = 0; i < this.soundTracks.length; i++) {
  8856. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8857. sound = this.soundTracks[i].soundCollection[j];
  8858. if (sound.useCustomAttenuation) {
  8859. sound.updateDistanceFromListener();
  8860. }
  8861. }
  8862. }
  8863. }
  8864. };
  8865. Object.defineProperty(Scene.prototype, "audioEnabled", {
  8866. get: function () {
  8867. return this._audioEnabled;
  8868. },
  8869. set: function (value) {
  8870. this._audioEnabled = value;
  8871. if (this._audioEnabled) {
  8872. this._enableAudio();
  8873. }
  8874. else {
  8875. this._disableAudio();
  8876. }
  8877. },
  8878. enumerable: true,
  8879. configurable: true
  8880. });
  8881. Scene.prototype._disableAudio = function () {
  8882. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8883. this.mainSoundTrack.soundCollection[i].pause();
  8884. }
  8885. for (i = 0; i < this.soundTracks.length; i++) {
  8886. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8887. this.soundTracks[i].soundCollection[j].pause();
  8888. }
  8889. }
  8890. };
  8891. Scene.prototype._enableAudio = function () {
  8892. for (var i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  8893. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  8894. this.mainSoundTrack.soundCollection[i].play();
  8895. }
  8896. }
  8897. for (i = 0; i < this.soundTracks.length; i++) {
  8898. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  8899. if (this.soundTracks[i].soundCollection[j].isPaused) {
  8900. this.soundTracks[i].soundCollection[j].play();
  8901. }
  8902. }
  8903. }
  8904. };
  8905. Scene.prototype.enableDepthRenderer = function () {
  8906. if (this._depthRenderer) {
  8907. return this._depthRenderer;
  8908. }
  8909. this._depthRenderer = new BABYLON.DepthRenderer(this);
  8910. return this._depthRenderer;
  8911. };
  8912. Scene.prototype.disableDepthRenderer = function () {
  8913. if (!this._depthRenderer) {
  8914. return;
  8915. }
  8916. this._depthRenderer.dispose();
  8917. this._depthRenderer = null;
  8918. };
  8919. Scene.prototype.dispose = function () {
  8920. this.beforeRender = null;
  8921. this.afterRender = null;
  8922. this.skeletons = [];
  8923. this._boundingBoxRenderer.dispose();
  8924. if (this._depthRenderer) {
  8925. this._depthRenderer.dispose();
  8926. }
  8927. // Debug layer
  8928. this.debugLayer.hide();
  8929. // Events
  8930. if (this.onDispose) {
  8931. this.onDispose();
  8932. }
  8933. this._onBeforeRenderCallbacks = [];
  8934. this._onAfterRenderCallbacks = [];
  8935. this.detachControl();
  8936. // Release sounds & sounds tracks
  8937. this.disposeSounds();
  8938. // Detach cameras
  8939. var canvas = this._engine.getRenderingCanvas();
  8940. var index;
  8941. for (index = 0; index < this.cameras.length; index++) {
  8942. this.cameras[index].detachControl(canvas);
  8943. }
  8944. while (this.lights.length) {
  8945. this.lights[0].dispose();
  8946. }
  8947. while (this.meshes.length) {
  8948. this.meshes[0].dispose(true);
  8949. }
  8950. while (this.cameras.length) {
  8951. this.cameras[0].dispose();
  8952. }
  8953. while (this.materials.length) {
  8954. this.materials[0].dispose();
  8955. }
  8956. while (this.particleSystems.length) {
  8957. this.particleSystems[0].dispose();
  8958. }
  8959. while (this.spriteManagers.length) {
  8960. this.spriteManagers[0].dispose();
  8961. }
  8962. while (this.layers.length) {
  8963. this.layers[0].dispose();
  8964. }
  8965. while (this.textures.length) {
  8966. this.textures[0].dispose();
  8967. }
  8968. // Post-processes
  8969. this.postProcessManager.dispose();
  8970. // Physics
  8971. if (this._physicsEngine) {
  8972. this.disablePhysicsEngine();
  8973. }
  8974. // Remove from engine
  8975. index = this._engine.scenes.indexOf(this);
  8976. if (index > -1) {
  8977. this._engine.scenes.splice(index, 1);
  8978. }
  8979. this._engine.wipeCaches();
  8980. };
  8981. // Release sounds & sounds tracks
  8982. Scene.prototype.disposeSounds = function () {
  8983. this.mainSoundTrack.dispose();
  8984. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  8985. this.soundTracks[scIndex].dispose();
  8986. }
  8987. };
  8988. // Collisions
  8989. Scene.prototype._getNewPosition = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  8990. if (excludedMesh === void 0) { excludedMesh = null; }
  8991. position.divideToRef(collider.radius, this._scaledPosition);
  8992. velocity.divideToRef(collider.radius, this._scaledVelocity);
  8993. collider.retry = 0;
  8994. collider.initialVelocity = this._scaledVelocity;
  8995. collider.initialPosition = this._scaledPosition;
  8996. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, finalPosition, excludedMesh);
  8997. finalPosition.multiplyInPlace(collider.radius);
  8998. };
  8999. Scene.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  9000. if (excludedMesh === void 0) { excludedMesh = null; }
  9001. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  9002. if (collider.retry >= maximumRetry) {
  9003. finalPosition.copyFrom(position);
  9004. return;
  9005. }
  9006. collider._initialize(position, velocity, closeDistance);
  9007. for (var index = 0; index < this.meshes.length; index++) {
  9008. var mesh = this.meshes[index];
  9009. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  9010. mesh._checkCollision(collider);
  9011. }
  9012. }
  9013. if (!collider.collisionFound) {
  9014. position.addToRef(velocity, finalPosition);
  9015. return;
  9016. }
  9017. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  9018. collider._getResponse(position, velocity);
  9019. }
  9020. if (velocity.length() <= closeDistance) {
  9021. finalPosition.copyFrom(position);
  9022. return;
  9023. }
  9024. collider.retry++;
  9025. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  9026. };
  9027. // Octrees
  9028. Scene.prototype.getWorldExtends = function () {
  9029. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9030. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9031. for (var index = 0; index < this.meshes.length; index++) {
  9032. var mesh = this.meshes[index];
  9033. mesh.computeWorldMatrix(true);
  9034. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  9035. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  9036. BABYLON.Tools.CheckExtends(minBox, min, max);
  9037. BABYLON.Tools.CheckExtends(maxBox, min, max);
  9038. }
  9039. return {
  9040. min: min,
  9041. max: max
  9042. };
  9043. };
  9044. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  9045. if (maxCapacity === void 0) { maxCapacity = 64; }
  9046. if (maxDepth === void 0) { maxDepth = 2; }
  9047. if (!this._selectionOctree) {
  9048. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  9049. }
  9050. var worldExtends = this.getWorldExtends();
  9051. // Update octree
  9052. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  9053. return this._selectionOctree;
  9054. };
  9055. // Picking
  9056. Scene.prototype.createPickingRay = function (x, y, world, camera) {
  9057. var engine = this._engine;
  9058. if (!camera) {
  9059. if (!this.activeCamera)
  9060. throw new Error("Active camera not set");
  9061. camera = this.activeCamera;
  9062. }
  9063. var cameraViewport = camera.viewport;
  9064. var viewport = cameraViewport.toGlobal(engine);
  9065. // Moving coordinates to local viewport world
  9066. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  9067. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  9068. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9069. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  9070. };
  9071. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  9072. var pickingInfo = null;
  9073. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  9074. var mesh = this.meshes[meshIndex];
  9075. if (predicate) {
  9076. if (!predicate(mesh)) {
  9077. continue;
  9078. }
  9079. }
  9080. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  9081. continue;
  9082. }
  9083. var world = mesh.getWorldMatrix();
  9084. var ray = rayFunction(world);
  9085. var result = mesh.intersects(ray, fastCheck);
  9086. if (!result || !result.hit)
  9087. continue;
  9088. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  9089. continue;
  9090. pickingInfo = result;
  9091. if (fastCheck) {
  9092. break;
  9093. }
  9094. }
  9095. return pickingInfo || new BABYLON.PickingInfo();
  9096. };
  9097. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  9098. var _this = this;
  9099. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  9100. /// <param name="x">X position on screen</param>
  9101. /// <param name="y">Y position on screen</param>
  9102. /// <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>
  9103. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  9104. /// <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>
  9105. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  9106. };
  9107. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  9108. var _this = this;
  9109. return this._internalPick(function (world) {
  9110. if (!_this._pickWithRayInverseMatrix) {
  9111. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  9112. }
  9113. world.invertToRef(_this._pickWithRayInverseMatrix);
  9114. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  9115. }, predicate, fastCheck);
  9116. };
  9117. Scene.prototype.setPointerOverMesh = function (mesh) {
  9118. if (this._pointerOverMesh === mesh) {
  9119. return;
  9120. }
  9121. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9122. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9123. }
  9124. this._pointerOverMesh = mesh;
  9125. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  9126. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  9127. }
  9128. };
  9129. Scene.prototype.getPointerOverMesh = function () {
  9130. return this._pointerOverMesh;
  9131. };
  9132. // Physics
  9133. Scene.prototype.getPhysicsEngine = function () {
  9134. return this._physicsEngine;
  9135. };
  9136. Scene.prototype.enablePhysics = function (gravity, plugin) {
  9137. if (this._physicsEngine) {
  9138. return true;
  9139. }
  9140. this._physicsEngine = new BABYLON.PhysicsEngine(plugin);
  9141. if (!this._physicsEngine.isSupported()) {
  9142. this._physicsEngine = null;
  9143. return false;
  9144. }
  9145. this._physicsEngine._initialize(gravity);
  9146. return true;
  9147. };
  9148. Scene.prototype.disablePhysicsEngine = function () {
  9149. if (!this._physicsEngine) {
  9150. return;
  9151. }
  9152. this._physicsEngine.dispose();
  9153. this._physicsEngine = undefined;
  9154. };
  9155. Scene.prototype.isPhysicsEnabled = function () {
  9156. return this._physicsEngine !== undefined;
  9157. };
  9158. Scene.prototype.setGravity = function (gravity) {
  9159. if (!this._physicsEngine) {
  9160. return;
  9161. }
  9162. this._physicsEngine._setGravity(gravity);
  9163. };
  9164. Scene.prototype.createCompoundImpostor = function (parts, options) {
  9165. if (parts.parts) {
  9166. options = parts;
  9167. parts = parts.parts;
  9168. }
  9169. if (!this._physicsEngine) {
  9170. return null;
  9171. }
  9172. for (var index = 0; index < parts.length; index++) {
  9173. var mesh = parts[index].mesh;
  9174. mesh._physicImpostor = parts[index].impostor;
  9175. mesh._physicsMass = options.mass / parts.length;
  9176. mesh._physicsFriction = options.friction;
  9177. mesh._physicRestitution = options.restitution;
  9178. }
  9179. return this._physicsEngine._registerMeshesAsCompound(parts, options);
  9180. };
  9181. Scene.prototype.deleteCompoundImpostor = function (compound) {
  9182. for (var index = 0; index < compound.parts.length; index++) {
  9183. var mesh = compound.parts[index].mesh;
  9184. mesh._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9185. this._physicsEngine._unregisterMesh(mesh);
  9186. }
  9187. };
  9188. // Misc.
  9189. Scene.prototype.createDefaultCameraOrLight = function () {
  9190. // Light
  9191. if (this.lights.length === 0) {
  9192. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  9193. }
  9194. // Camera
  9195. if (!this.activeCamera) {
  9196. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  9197. // Compute position
  9198. var worldExtends = this.getWorldExtends();
  9199. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  9200. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  9201. camera.setTarget(worldCenter);
  9202. this.activeCamera = camera;
  9203. }
  9204. };
  9205. // Tags
  9206. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  9207. if (tagsQuery === undefined) {
  9208. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  9209. return list;
  9210. }
  9211. var listByTags = [];
  9212. forEach = forEach || (function (item) {
  9213. return;
  9214. });
  9215. for (var i in list) {
  9216. var item = list[i];
  9217. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  9218. listByTags.push(item);
  9219. forEach(item);
  9220. }
  9221. }
  9222. return listByTags;
  9223. };
  9224. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  9225. return this._getByTags(this.meshes, tagsQuery, forEach);
  9226. };
  9227. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  9228. return this._getByTags(this.cameras, tagsQuery, forEach);
  9229. };
  9230. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  9231. return this._getByTags(this.lights, tagsQuery, forEach);
  9232. };
  9233. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  9234. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  9235. };
  9236. // Audio
  9237. Scene.prototype.switchAudioModeForHeadphones = function () {
  9238. this.mainSoundTrack.switchPanningModelToHRTF();
  9239. for (var i = 0; i < this.soundTracks.length; i++) {
  9240. this.soundTracks[i].switchPanningModelToHRTF();
  9241. }
  9242. };
  9243. Scene.prototype.switchAudioModeForNormalSpeakers = function () {
  9244. this.mainSoundTrack.switchPanningModelToEqualPower();
  9245. for (var i = 0; i < this.soundTracks.length; i++) {
  9246. this.soundTracks[i].switchPanningModelToEqualPower();
  9247. }
  9248. };
  9249. // Statics
  9250. Scene._FOGMODE_NONE = 0;
  9251. Scene._FOGMODE_EXP = 1;
  9252. Scene._FOGMODE_EXP2 = 2;
  9253. Scene._FOGMODE_LINEAR = 3;
  9254. Scene.MinDeltaTime = 1.0;
  9255. Scene.MaxDeltaTime = 1000.0;
  9256. return Scene;
  9257. })();
  9258. BABYLON.Scene = Scene;
  9259. })(BABYLON || (BABYLON = {}));
  9260. //# sourceMappingURL=babylon.scene.js.mapvar BABYLON;
  9261. (function (BABYLON) {
  9262. var VertexBuffer = (function () {
  9263. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride) {
  9264. if (engine instanceof BABYLON.Mesh) {
  9265. this._engine = engine.getScene().getEngine();
  9266. }
  9267. else {
  9268. this._engine = engine;
  9269. }
  9270. this._updatable = updatable;
  9271. this._data = data;
  9272. if (!postponeInternalCreation) {
  9273. this.create();
  9274. }
  9275. this._kind = kind;
  9276. if (stride) {
  9277. this._strideSize = stride;
  9278. return;
  9279. }
  9280. switch (kind) {
  9281. case VertexBuffer.PositionKind:
  9282. this._strideSize = 3;
  9283. break;
  9284. case VertexBuffer.NormalKind:
  9285. this._strideSize = 3;
  9286. break;
  9287. case VertexBuffer.UVKind:
  9288. this._strideSize = 2;
  9289. break;
  9290. case VertexBuffer.UV2Kind:
  9291. this._strideSize = 2;
  9292. break;
  9293. case VertexBuffer.ColorKind:
  9294. this._strideSize = 4;
  9295. break;
  9296. case VertexBuffer.MatricesIndicesKind:
  9297. this._strideSize = 4;
  9298. break;
  9299. case VertexBuffer.MatricesWeightsKind:
  9300. this._strideSize = 4;
  9301. break;
  9302. }
  9303. }
  9304. // Properties
  9305. VertexBuffer.prototype.isUpdatable = function () {
  9306. return this._updatable;
  9307. };
  9308. VertexBuffer.prototype.getData = function () {
  9309. return this._data;
  9310. };
  9311. VertexBuffer.prototype.getBuffer = function () {
  9312. return this._buffer;
  9313. };
  9314. VertexBuffer.prototype.getStrideSize = function () {
  9315. return this._strideSize;
  9316. };
  9317. // Methods
  9318. VertexBuffer.prototype.create = function (data) {
  9319. if (!data && this._buffer) {
  9320. return; // nothing to do
  9321. }
  9322. data = data || this._data;
  9323. if (!this._buffer) {
  9324. if (this._updatable) {
  9325. this._buffer = this._engine.createDynamicVertexBuffer(data.length * 4);
  9326. }
  9327. else {
  9328. this._buffer = this._engine.createVertexBuffer(data);
  9329. }
  9330. }
  9331. if (this._updatable) {
  9332. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  9333. this._data = data;
  9334. }
  9335. };
  9336. VertexBuffer.prototype.update = function (data) {
  9337. this.create(data);
  9338. };
  9339. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  9340. if (!this._buffer) {
  9341. return;
  9342. }
  9343. if (this._updatable) {
  9344. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset);
  9345. this._data = null;
  9346. }
  9347. };
  9348. VertexBuffer.prototype.dispose = function () {
  9349. if (!this._buffer) {
  9350. return;
  9351. }
  9352. if (this._engine._releaseBuffer(this._buffer)) {
  9353. this._buffer = null;
  9354. }
  9355. };
  9356. Object.defineProperty(VertexBuffer, "PositionKind", {
  9357. get: function () {
  9358. return VertexBuffer._PositionKind;
  9359. },
  9360. enumerable: true,
  9361. configurable: true
  9362. });
  9363. Object.defineProperty(VertexBuffer, "NormalKind", {
  9364. get: function () {
  9365. return VertexBuffer._NormalKind;
  9366. },
  9367. enumerable: true,
  9368. configurable: true
  9369. });
  9370. Object.defineProperty(VertexBuffer, "UVKind", {
  9371. get: function () {
  9372. return VertexBuffer._UVKind;
  9373. },
  9374. enumerable: true,
  9375. configurable: true
  9376. });
  9377. Object.defineProperty(VertexBuffer, "UV2Kind", {
  9378. get: function () {
  9379. return VertexBuffer._UV2Kind;
  9380. },
  9381. enumerable: true,
  9382. configurable: true
  9383. });
  9384. Object.defineProperty(VertexBuffer, "ColorKind", {
  9385. get: function () {
  9386. return VertexBuffer._ColorKind;
  9387. },
  9388. enumerable: true,
  9389. configurable: true
  9390. });
  9391. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  9392. get: function () {
  9393. return VertexBuffer._MatricesIndicesKind;
  9394. },
  9395. enumerable: true,
  9396. configurable: true
  9397. });
  9398. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  9399. get: function () {
  9400. return VertexBuffer._MatricesWeightsKind;
  9401. },
  9402. enumerable: true,
  9403. configurable: true
  9404. });
  9405. // Enums
  9406. VertexBuffer._PositionKind = "position";
  9407. VertexBuffer._NormalKind = "normal";
  9408. VertexBuffer._UVKind = "uv";
  9409. VertexBuffer._UV2Kind = "uv2";
  9410. VertexBuffer._ColorKind = "color";
  9411. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  9412. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  9413. return VertexBuffer;
  9414. })();
  9415. BABYLON.VertexBuffer = VertexBuffer;
  9416. })(BABYLON || (BABYLON = {}));
  9417. //# sourceMappingURL=babylon.vertexBuffer.js.map
  9418. var BABYLON;
  9419. (function (BABYLON) {
  9420. var AbstractMesh = (function (_super) {
  9421. __extends(AbstractMesh, _super);
  9422. function AbstractMesh(name, scene) {
  9423. _super.call(this, name, scene);
  9424. // Properties
  9425. this.definedFacingForward = true; // orientation for POV movement & rotation
  9426. this.position = new BABYLON.Vector3(0, 0, 0);
  9427. this.rotation = new BABYLON.Vector3(0, 0, 0);
  9428. this.scaling = new BABYLON.Vector3(1, 1, 1);
  9429. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  9430. this.visibility = 1.0;
  9431. this.alphaIndex = Number.MAX_VALUE;
  9432. this.infiniteDistance = false;
  9433. this.isVisible = true;
  9434. this.isPickable = true;
  9435. this.showBoundingBox = false;
  9436. this.showSubMeshesBoundingBox = false;
  9437. this.onDispose = null;
  9438. this.checkCollisions = false;
  9439. this.isBlocker = false;
  9440. this.renderingGroupId = 0;
  9441. this.receiveShadows = false;
  9442. this.renderOutline = false;
  9443. this.outlineColor = BABYLON.Color3.Red();
  9444. this.outlineWidth = 0.02;
  9445. this.renderOverlay = false;
  9446. this.overlayColor = BABYLON.Color3.Red();
  9447. this.overlayAlpha = 0.5;
  9448. this.hasVertexAlpha = false;
  9449. this.useVertexColors = true;
  9450. this.applyFog = true;
  9451. this.useOctreeForRenderingSelection = true;
  9452. this.useOctreeForPicking = true;
  9453. this.useOctreeForCollisions = true;
  9454. this.layerMask = 0xFFFFFFFF;
  9455. // Physics
  9456. this._physicImpostor = BABYLON.PhysicsEngine.NoImpostor;
  9457. // Collisions
  9458. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  9459. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  9460. this._collider = new BABYLON.Collider();
  9461. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9462. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9463. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  9464. // Cache
  9465. this._localScaling = BABYLON.Matrix.Zero();
  9466. this._localRotation = BABYLON.Matrix.Zero();
  9467. this._localTranslation = BABYLON.Matrix.Zero();
  9468. this._localBillboard = BABYLON.Matrix.Zero();
  9469. this._localPivotScaling = BABYLON.Matrix.Zero();
  9470. this._localPivotScalingRotation = BABYLON.Matrix.Zero();
  9471. this._localWorld = BABYLON.Matrix.Zero();
  9472. this._worldMatrix = BABYLON.Matrix.Zero();
  9473. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  9474. this._absolutePosition = BABYLON.Vector3.Zero();
  9475. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  9476. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  9477. this._isDirty = false;
  9478. this._pivotMatrix = BABYLON.Matrix.Identity();
  9479. this._isDisposed = false;
  9480. this._renderId = 0;
  9481. this._intersectionsInProgress = new Array();
  9482. this._onAfterWorldMatrixUpdate = new Array();
  9483. scene.meshes.push(this);
  9484. }
  9485. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  9486. get: function () {
  9487. return AbstractMesh._BILLBOARDMODE_NONE;
  9488. },
  9489. enumerable: true,
  9490. configurable: true
  9491. });
  9492. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  9493. get: function () {
  9494. return AbstractMesh._BILLBOARDMODE_X;
  9495. },
  9496. enumerable: true,
  9497. configurable: true
  9498. });
  9499. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  9500. get: function () {
  9501. return AbstractMesh._BILLBOARDMODE_Y;
  9502. },
  9503. enumerable: true,
  9504. configurable: true
  9505. });
  9506. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  9507. get: function () {
  9508. return AbstractMesh._BILLBOARDMODE_Z;
  9509. },
  9510. enumerable: true,
  9511. configurable: true
  9512. });
  9513. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  9514. get: function () {
  9515. return AbstractMesh._BILLBOARDMODE_ALL;
  9516. },
  9517. enumerable: true,
  9518. configurable: true
  9519. });
  9520. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  9521. // Methods
  9522. get: function () {
  9523. return false;
  9524. },
  9525. enumerable: true,
  9526. configurable: true
  9527. });
  9528. AbstractMesh.prototype.getLOD = function (camera) {
  9529. return this;
  9530. };
  9531. AbstractMesh.prototype.getTotalVertices = function () {
  9532. return 0;
  9533. };
  9534. AbstractMesh.prototype.getIndices = function () {
  9535. return null;
  9536. };
  9537. AbstractMesh.prototype.getVerticesData = function (kind) {
  9538. return null;
  9539. };
  9540. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  9541. return false;
  9542. };
  9543. AbstractMesh.prototype.getBoundingInfo = function () {
  9544. if (this._masterMesh) {
  9545. return this._masterMesh.getBoundingInfo();
  9546. }
  9547. if (!this._boundingInfo) {
  9548. this._updateBoundingInfo();
  9549. }
  9550. return this._boundingInfo;
  9551. };
  9552. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  9553. get: function () {
  9554. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  9555. },
  9556. enumerable: true,
  9557. configurable: true
  9558. });
  9559. AbstractMesh.prototype._preActivate = function () {
  9560. };
  9561. AbstractMesh.prototype._activate = function (renderId) {
  9562. this._renderId = renderId;
  9563. };
  9564. AbstractMesh.prototype.getWorldMatrix = function () {
  9565. if (this._masterMesh) {
  9566. return this._masterMesh.getWorldMatrix();
  9567. }
  9568. if (this._currentRenderId !== this.getScene().getRenderId()) {
  9569. this.computeWorldMatrix();
  9570. }
  9571. return this._worldMatrix;
  9572. };
  9573. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  9574. get: function () {
  9575. return this._worldMatrix;
  9576. },
  9577. enumerable: true,
  9578. configurable: true
  9579. });
  9580. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  9581. get: function () {
  9582. return this._absolutePosition;
  9583. },
  9584. enumerable: true,
  9585. configurable: true
  9586. });
  9587. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  9588. if (!this.rotationQuaternion) {
  9589. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9590. this.rotation = BABYLON.Vector3.Zero();
  9591. }
  9592. if (!space || space == 0 /* LOCAL */) {
  9593. var rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9594. this.rotationQuaternion = this.rotationQuaternion.multiply(rotationQuaternion);
  9595. }
  9596. else {
  9597. if (this.parent) {
  9598. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9599. invertParentWorldMatrix.invert();
  9600. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  9601. }
  9602. rotationQuaternion = BABYLON.Quaternion.RotationAxis(axis, amount);
  9603. this.rotationQuaternion = rotationQuaternion.multiply(this.rotationQuaternion);
  9604. }
  9605. };
  9606. AbstractMesh.prototype.translate = function (axis, distance, space) {
  9607. var displacementVector = axis.scale(distance);
  9608. if (!space || space == 0 /* LOCAL */) {
  9609. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  9610. this.setPositionWithLocalVector(tempV3);
  9611. }
  9612. else {
  9613. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  9614. }
  9615. };
  9616. AbstractMesh.prototype.getAbsolutePosition = function () {
  9617. this.computeWorldMatrix();
  9618. return this._absolutePosition;
  9619. };
  9620. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  9621. if (!absolutePosition) {
  9622. return;
  9623. }
  9624. var absolutePositionX;
  9625. var absolutePositionY;
  9626. var absolutePositionZ;
  9627. if (absolutePosition.x === undefined) {
  9628. if (arguments.length < 3) {
  9629. return;
  9630. }
  9631. absolutePositionX = arguments[0];
  9632. absolutePositionY = arguments[1];
  9633. absolutePositionZ = arguments[2];
  9634. }
  9635. else {
  9636. absolutePositionX = absolutePosition.x;
  9637. absolutePositionY = absolutePosition.y;
  9638. absolutePositionZ = absolutePosition.z;
  9639. }
  9640. if (this.parent) {
  9641. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  9642. invertParentWorldMatrix.invert();
  9643. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  9644. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  9645. }
  9646. else {
  9647. this.position.x = absolutePositionX;
  9648. this.position.y = absolutePositionY;
  9649. this.position.z = absolutePositionZ;
  9650. }
  9651. };
  9652. // ================================== Point of View Movement =================================
  9653. /**
  9654. * Perform relative position change from the point of view of behind the front of the mesh.
  9655. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9656. * Supports definition of mesh facing forward or backward.
  9657. * @param {number} amountRight
  9658. * @param {number} amountUp
  9659. * @param {number} amountForward
  9660. */
  9661. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  9662. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  9663. };
  9664. /**
  9665. * Calculate relative position change from the point of view of behind the front of the mesh.
  9666. * This is performed taking into account the meshes current rotation, so you do not have to care.
  9667. * Supports definition of mesh facing forward or backward.
  9668. * @param {number} amountRight
  9669. * @param {number} amountUp
  9670. * @param {number} amountForward
  9671. */
  9672. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  9673. var rotMatrix = new BABYLON.Matrix();
  9674. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  9675. rotQuaternion.toRotationMatrix(rotMatrix);
  9676. var translationDelta = BABYLON.Vector3.Zero();
  9677. var defForwardMult = this.definedFacingForward ? -1 : 1;
  9678. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  9679. return translationDelta;
  9680. };
  9681. // ================================== Point of View Rotation =================================
  9682. /**
  9683. * Perform relative rotation change from the point of view of behind the front of the mesh.
  9684. * Supports definition of mesh facing forward or backward.
  9685. * @param {number} flipBack
  9686. * @param {number} twirlClockwise
  9687. * @param {number} tiltRight
  9688. */
  9689. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9690. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  9691. };
  9692. /**
  9693. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  9694. * Supports definition of mesh facing forward or backward.
  9695. * @param {number} flipBack
  9696. * @param {number} twirlClockwise
  9697. * @param {number} tiltRight
  9698. */
  9699. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  9700. var defForwardMult = this.definedFacingForward ? 1 : -1;
  9701. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  9702. };
  9703. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  9704. this._pivotMatrix = matrix;
  9705. this._cache.pivotMatrixUpdated = true;
  9706. };
  9707. AbstractMesh.prototype.getPivotMatrix = function () {
  9708. return this._pivotMatrix;
  9709. };
  9710. AbstractMesh.prototype._isSynchronized = function () {
  9711. if (this._isDirty) {
  9712. return false;
  9713. }
  9714. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  9715. return false;
  9716. if (this._cache.pivotMatrixUpdated) {
  9717. return false;
  9718. }
  9719. if (this.infiniteDistance) {
  9720. return false;
  9721. }
  9722. if (!this._cache.position.equals(this.position))
  9723. return false;
  9724. if (this.rotationQuaternion) {
  9725. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  9726. return false;
  9727. }
  9728. else {
  9729. if (!this._cache.rotation.equals(this.rotation))
  9730. return false;
  9731. }
  9732. if (!this._cache.scaling.equals(this.scaling))
  9733. return false;
  9734. return true;
  9735. };
  9736. AbstractMesh.prototype._initCache = function () {
  9737. _super.prototype._initCache.call(this);
  9738. this._cache.localMatrixUpdated = false;
  9739. this._cache.position = BABYLON.Vector3.Zero();
  9740. this._cache.scaling = BABYLON.Vector3.Zero();
  9741. this._cache.rotation = BABYLON.Vector3.Zero();
  9742. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  9743. };
  9744. AbstractMesh.prototype.markAsDirty = function (property) {
  9745. if (property === "rotation") {
  9746. this.rotationQuaternion = null;
  9747. }
  9748. this._currentRenderId = Number.MAX_VALUE;
  9749. this._isDirty = true;
  9750. };
  9751. AbstractMesh.prototype._updateBoundingInfo = function () {
  9752. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  9753. this._boundingInfo._update(this.worldMatrixFromCache);
  9754. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  9755. };
  9756. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  9757. if (!this.subMeshes) {
  9758. return;
  9759. }
  9760. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  9761. var subMesh = this.subMeshes[subIndex];
  9762. subMesh.updateBoundingInfo(matrix);
  9763. }
  9764. };
  9765. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  9766. if (!force && (this._currentRenderId == this.getScene().getRenderId() || this.isSynchronized(true))) {
  9767. return this._worldMatrix;
  9768. }
  9769. this._cache.position.copyFrom(this.position);
  9770. this._cache.scaling.copyFrom(this.scaling);
  9771. this._cache.pivotMatrixUpdated = false;
  9772. this._currentRenderId = this.getScene().getRenderId();
  9773. this._isDirty = false;
  9774. // Scaling
  9775. BABYLON.Matrix.ScalingToRef(this.scaling.x, this.scaling.y, this.scaling.z, this._localScaling);
  9776. // Rotation
  9777. if (this.rotationQuaternion) {
  9778. this.rotationQuaternion.toRotationMatrix(this._localRotation);
  9779. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  9780. }
  9781. else {
  9782. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._localRotation);
  9783. this._cache.rotation.copyFrom(this.rotation);
  9784. }
  9785. // Translation
  9786. if (this.infiniteDistance && !this.parent) {
  9787. var camera = this.getScene().activeCamera;
  9788. var cameraWorldMatrix = camera.getWorldMatrix();
  9789. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  9790. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, this._localTranslation);
  9791. }
  9792. else {
  9793. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._localTranslation);
  9794. }
  9795. // Composing transformations
  9796. this._pivotMatrix.multiplyToRef(this._localScaling, this._localPivotScaling);
  9797. this._localPivotScaling.multiplyToRef(this._localRotation, this._localPivotScalingRotation);
  9798. // Billboarding
  9799. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  9800. var localPosition = this.position.clone();
  9801. var zero = this.getScene().activeCamera.position.clone();
  9802. if (this.parent && this.parent.position) {
  9803. localPosition.addInPlace(this.parent.position);
  9804. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, this._localTranslation);
  9805. }
  9806. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) === AbstractMesh.BILLBOARDMODE_ALL) {
  9807. zero = this.getScene().activeCamera.position;
  9808. }
  9809. else {
  9810. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X)
  9811. zero.x = localPosition.x + BABYLON.Engine.Epsilon;
  9812. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y)
  9813. zero.y = localPosition.y + 0.001;
  9814. if (this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z)
  9815. zero.z = localPosition.z + 0.001;
  9816. }
  9817. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), this._localBillboard);
  9818. this._localBillboard.m[12] = this._localBillboard.m[13] = this._localBillboard.m[14] = 0;
  9819. this._localBillboard.invert();
  9820. this._localPivotScalingRotation.multiplyToRef(this._localBillboard, this._localWorld);
  9821. this._rotateYByPI.multiplyToRef(this._localWorld, this._localPivotScalingRotation);
  9822. }
  9823. // Local world
  9824. this._localPivotScalingRotation.multiplyToRef(this._localTranslation, this._localWorld);
  9825. // Parent
  9826. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  9827. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  9828. }
  9829. else {
  9830. this._worldMatrix.copyFrom(this._localWorld);
  9831. }
  9832. // Bounding info
  9833. this._updateBoundingInfo();
  9834. // Absolute position
  9835. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  9836. for (var callbackIndex = 0; callbackIndex < this._onAfterWorldMatrixUpdate.length; callbackIndex++) {
  9837. this._onAfterWorldMatrixUpdate[callbackIndex](this);
  9838. }
  9839. return this._worldMatrix;
  9840. };
  9841. /**
  9842. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  9843. * @param func: callback function to add
  9844. */
  9845. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  9846. this._onAfterWorldMatrixUpdate.push(func);
  9847. };
  9848. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  9849. var index = this._onAfterWorldMatrixUpdate.indexOf(func);
  9850. if (index > -1) {
  9851. this._onAfterWorldMatrixUpdate.splice(index, 1);
  9852. }
  9853. };
  9854. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  9855. this.computeWorldMatrix();
  9856. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  9857. };
  9858. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  9859. this.computeWorldMatrix();
  9860. var invLocalWorldMatrix = this._localWorld.clone();
  9861. invLocalWorldMatrix.invert();
  9862. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  9863. };
  9864. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  9865. this.computeWorldMatrix();
  9866. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  9867. };
  9868. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor) {
  9869. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  9870. /// <param name="targetPoint" type="BABYLON.Vector3">The position (must be in same space as current mesh) to look at</param>
  9871. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  9872. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  9873. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  9874. /// <returns>Mesh oriented towards targetMesh</returns>
  9875. yawCor = yawCor || 0; // default to zero if undefined
  9876. pitchCor = pitchCor || 0;
  9877. rollCor = rollCor || 0;
  9878. var dv = targetPoint.subtract(this.position);
  9879. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  9880. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  9881. var pitch = Math.atan2(dv.y, len);
  9882. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(yaw + yawCor, pitch + pitchCor, rollCor);
  9883. };
  9884. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  9885. if (!this._boundingInfo.isInFrustum(frustumPlanes)) {
  9886. return false;
  9887. }
  9888. return true;
  9889. };
  9890. AbstractMesh.prototype.isCompletelyInFrustum = function (camera) {
  9891. if (!camera) {
  9892. camera = this.getScene().activeCamera;
  9893. }
  9894. var transformMatrix = camera.getViewMatrix().multiply(camera.getProjectionMatrix());
  9895. if (!this._boundingInfo.isCompletelyInFrustum(BABYLON.Frustum.GetPlanes(transformMatrix))) {
  9896. return false;
  9897. }
  9898. return true;
  9899. };
  9900. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  9901. if (!this._boundingInfo || !mesh._boundingInfo) {
  9902. return false;
  9903. }
  9904. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  9905. };
  9906. AbstractMesh.prototype.intersectsPoint = function (point) {
  9907. if (!this._boundingInfo) {
  9908. return false;
  9909. }
  9910. return this._boundingInfo.intersectsPoint(point);
  9911. };
  9912. // Physics
  9913. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  9914. var physicsEngine = this.getScene().getPhysicsEngine();
  9915. if (!physicsEngine) {
  9916. return;
  9917. }
  9918. impostor = impostor || BABYLON.PhysicsEngine.NoImpostor;
  9919. if (impostor.impostor) {
  9920. // Old API
  9921. options = impostor;
  9922. impostor = impostor.impostor;
  9923. }
  9924. if (impostor === BABYLON.PhysicsEngine.NoImpostor) {
  9925. physicsEngine._unregisterMesh(this);
  9926. return;
  9927. }
  9928. if (!options) {
  9929. options = { mass: 0, friction: 0.2, restitution: 0.2 };
  9930. }
  9931. else {
  9932. if (!options.mass && options.mass !== 0)
  9933. options.mass = 0;
  9934. if (!options.friction && options.friction !== 0)
  9935. options.friction = 0.2;
  9936. if (!options.restitution && options.restitution !== 0)
  9937. options.restitution = 0.2;
  9938. }
  9939. this._physicImpostor = impostor;
  9940. this._physicsMass = options.mass;
  9941. this._physicsFriction = options.friction;
  9942. this._physicRestitution = options.restitution;
  9943. return physicsEngine._registerMesh(this, impostor, options);
  9944. };
  9945. AbstractMesh.prototype.getPhysicsImpostor = function () {
  9946. if (!this._physicImpostor) {
  9947. return BABYLON.PhysicsEngine.NoImpostor;
  9948. }
  9949. return this._physicImpostor;
  9950. };
  9951. AbstractMesh.prototype.getPhysicsMass = function () {
  9952. if (!this._physicsMass) {
  9953. return 0;
  9954. }
  9955. return this._physicsMass;
  9956. };
  9957. AbstractMesh.prototype.getPhysicsFriction = function () {
  9958. if (!this._physicsFriction) {
  9959. return 0;
  9960. }
  9961. return this._physicsFriction;
  9962. };
  9963. AbstractMesh.prototype.getPhysicsRestitution = function () {
  9964. if (!this._physicRestitution) {
  9965. return 0;
  9966. }
  9967. return this._physicRestitution;
  9968. };
  9969. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  9970. if (!camera) {
  9971. camera = this.getScene().activeCamera;
  9972. }
  9973. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  9974. };
  9975. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  9976. if (!camera) {
  9977. camera = this.getScene().activeCamera;
  9978. }
  9979. return this.absolutePosition.subtract(camera.position).length();
  9980. };
  9981. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  9982. if (!this._physicImpostor) {
  9983. return;
  9984. }
  9985. this.getScene().getPhysicsEngine()._applyImpulse(this, force, contactPoint);
  9986. };
  9987. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  9988. if (!this._physicImpostor) {
  9989. return;
  9990. }
  9991. this.getScene().getPhysicsEngine()._createLink(this, otherMesh, pivot1, pivot2, options);
  9992. };
  9993. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  9994. if (!this._physicImpostor) {
  9995. return;
  9996. }
  9997. this.getScene().getPhysicsEngine()._updateBodyPosition(this);
  9998. };
  9999. // Collisions
  10000. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10001. var globalPosition = this.getAbsolutePosition();
  10002. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10003. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10004. this._collider.radius = this.ellipsoid;
  10005. this.getScene()._getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this._newPositionForCollisions, this);
  10006. this._newPositionForCollisions.subtractToRef(this._oldPositionForCollisions, this._diffPositionForCollisions);
  10007. if (this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10008. this.position.addInPlace(this._diffPositionForCollisions);
  10009. }
  10010. };
  10011. // Submeshes octree
  10012. /**
  10013. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10014. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10015. */
  10016. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10017. if (maxCapacity === void 0) { maxCapacity = 64; }
  10018. if (maxDepth === void 0) { maxDepth = 2; }
  10019. if (!this._submeshesOctree) {
  10020. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10021. }
  10022. this.computeWorldMatrix(true);
  10023. // Update octree
  10024. var bbox = this.getBoundingInfo().boundingBox;
  10025. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10026. return this._submeshesOctree;
  10027. };
  10028. // Collisions
  10029. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10030. this._generatePointsArray();
  10031. // Transformation
  10032. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10033. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10034. subMesh._lastColliderWorldVertices = [];
  10035. subMesh._trianglePlanes = [];
  10036. var start = subMesh.verticesStart;
  10037. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10038. for (var i = start; i < end; i++) {
  10039. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10040. }
  10041. }
  10042. // Collide
  10043. collider._collide(subMesh, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart);
  10044. };
  10045. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10046. var subMeshes;
  10047. var len;
  10048. // Octrees
  10049. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10050. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10051. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10052. len = intersections.length;
  10053. subMeshes = intersections.data;
  10054. }
  10055. else {
  10056. subMeshes = this.subMeshes;
  10057. len = subMeshes.length;
  10058. }
  10059. for (var index = 0; index < len; index++) {
  10060. var subMesh = subMeshes[index];
  10061. // Bounding test
  10062. if (len > 1 && !subMesh._checkCollision(collider))
  10063. continue;
  10064. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10065. }
  10066. };
  10067. AbstractMesh.prototype._checkCollision = function (collider) {
  10068. // Bounding box test
  10069. if (!this._boundingInfo._checkCollision(collider))
  10070. return;
  10071. // Transformation matrix
  10072. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10073. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10074. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10075. };
  10076. // Picking
  10077. AbstractMesh.prototype._generatePointsArray = function () {
  10078. return false;
  10079. };
  10080. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10081. var pickingInfo = new BABYLON.PickingInfo();
  10082. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10083. return pickingInfo;
  10084. }
  10085. if (!this._generatePointsArray()) {
  10086. return pickingInfo;
  10087. }
  10088. var intersectInfo = null;
  10089. // Octrees
  10090. var subMeshes;
  10091. var len;
  10092. if (this._submeshesOctree && this.useOctreeForPicking) {
  10093. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10094. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10095. len = intersections.length;
  10096. subMeshes = intersections.data;
  10097. }
  10098. else {
  10099. subMeshes = this.subMeshes;
  10100. len = subMeshes.length;
  10101. }
  10102. for (var index = 0; index < len; index++) {
  10103. var subMesh = subMeshes[index];
  10104. // Bounding test
  10105. if (len > 1 && !subMesh.canIntersects(ray))
  10106. continue;
  10107. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10108. if (currentIntersectInfo) {
  10109. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10110. intersectInfo = currentIntersectInfo;
  10111. intersectInfo.subMeshId = index;
  10112. if (fastCheck) {
  10113. break;
  10114. }
  10115. }
  10116. }
  10117. }
  10118. if (intersectInfo) {
  10119. // Get picked point
  10120. var world = this.getWorldMatrix();
  10121. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10122. var direction = ray.direction.clone();
  10123. direction = direction.scale(intersectInfo.distance);
  10124. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10125. var pickedPoint = worldOrigin.add(worldDirection);
  10126. // Return result
  10127. pickingInfo.hit = true;
  10128. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10129. pickingInfo.pickedPoint = pickedPoint;
  10130. pickingInfo.pickedMesh = this;
  10131. pickingInfo.bu = intersectInfo.bu;
  10132. pickingInfo.bv = intersectInfo.bv;
  10133. pickingInfo.faceId = intersectInfo.faceId;
  10134. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10135. return pickingInfo;
  10136. }
  10137. return pickingInfo;
  10138. };
  10139. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10140. return null;
  10141. };
  10142. AbstractMesh.prototype.releaseSubMeshes = function () {
  10143. if (this.subMeshes) {
  10144. while (this.subMeshes.length) {
  10145. this.subMeshes[0].dispose();
  10146. }
  10147. }
  10148. else {
  10149. this.subMeshes = new Array();
  10150. }
  10151. };
  10152. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  10153. // Physics
  10154. if (this.getPhysicsImpostor() != BABYLON.PhysicsEngine.NoImpostor) {
  10155. this.setPhysicsState(BABYLON.PhysicsEngine.NoImpostor);
  10156. }
  10157. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  10158. var other = this._intersectionsInProgress[index];
  10159. var pos = other._intersectionsInProgress.indexOf(this);
  10160. other._intersectionsInProgress.splice(pos, 1);
  10161. }
  10162. this._intersectionsInProgress = [];
  10163. // SubMeshes
  10164. this.releaseSubMeshes();
  10165. // Remove from scene
  10166. var index = this.getScene().meshes.indexOf(this);
  10167. if (index != -1) {
  10168. // Remove from the scene if mesh found
  10169. this.getScene().meshes.splice(index, 1);
  10170. }
  10171. if (!doNotRecurse) {
  10172. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  10173. if (this.getScene().particleSystems[index].emitter == this) {
  10174. this.getScene().particleSystems[index].dispose();
  10175. index--;
  10176. }
  10177. }
  10178. // Children
  10179. var objects = this.getScene().meshes.slice(0);
  10180. for (index = 0; index < objects.length; index++) {
  10181. if (objects[index].parent == this) {
  10182. objects[index].dispose();
  10183. }
  10184. }
  10185. }
  10186. else {
  10187. for (index = 0; index < this.getScene().meshes.length; index++) {
  10188. var obj = this.getScene().meshes[index];
  10189. if (obj.parent === this) {
  10190. obj.parent = null;
  10191. obj.computeWorldMatrix(true);
  10192. }
  10193. }
  10194. }
  10195. this._onAfterWorldMatrixUpdate = [];
  10196. this._isDisposed = true;
  10197. // Callback
  10198. if (this.onDispose) {
  10199. this.onDispose();
  10200. }
  10201. };
  10202. // Statics
  10203. AbstractMesh._BILLBOARDMODE_NONE = 0;
  10204. AbstractMesh._BILLBOARDMODE_X = 1;
  10205. AbstractMesh._BILLBOARDMODE_Y = 2;
  10206. AbstractMesh._BILLBOARDMODE_Z = 4;
  10207. AbstractMesh._BILLBOARDMODE_ALL = 7;
  10208. return AbstractMesh;
  10209. })(BABYLON.Node);
  10210. BABYLON.AbstractMesh = AbstractMesh;
  10211. })(BABYLON || (BABYLON = {}));
  10212. //# sourceMappingURL=babylon.abstractMesh.js.map
  10213. var BABYLON;
  10214. (function (BABYLON) {
  10215. var _InstancesBatch = (function () {
  10216. function _InstancesBatch() {
  10217. this.mustReturn = false;
  10218. this.visibleInstances = new Array();
  10219. this.renderSelf = new Array();
  10220. }
  10221. return _InstancesBatch;
  10222. })();
  10223. BABYLON._InstancesBatch = _InstancesBatch;
  10224. var Mesh = (function (_super) {
  10225. __extends(Mesh, _super);
  10226. /**
  10227. * @constructor
  10228. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  10229. * @param {Scene} scene - The scene to add this mesh to.
  10230. * @param {Node} parent - The parent of this mesh, if it has one
  10231. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  10232. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  10233. * When false, achieved by calling a clone(), also passing False.
  10234. * This will make creation of children, recursive.
  10235. */
  10236. function Mesh(name, scene, parent, source, doNotCloneChildren) {
  10237. if (parent === void 0) { parent = null; }
  10238. _super.call(this, name, scene);
  10239. // Members
  10240. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  10241. this.instances = new Array();
  10242. this._LODLevels = new Array();
  10243. this._onBeforeRenderCallbacks = new Array();
  10244. this._onAfterRenderCallbacks = new Array();
  10245. this._visibleInstances = {};
  10246. this._renderIdForInstances = new Array();
  10247. this._batchCache = new _InstancesBatch();
  10248. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  10249. if (source) {
  10250. // Geometry
  10251. if (source._geometry) {
  10252. source._geometry.applyToMesh(this);
  10253. }
  10254. // Deep copy
  10255. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  10256. // Material
  10257. this.material = source.material;
  10258. if (!doNotCloneChildren) {
  10259. for (var index = 0; index < scene.meshes.length; index++) {
  10260. var mesh = scene.meshes[index];
  10261. if (mesh.parent === source) {
  10262. // doNotCloneChildren is always going to be False
  10263. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  10264. }
  10265. }
  10266. }
  10267. for (index = 0; index < scene.particleSystems.length; index++) {
  10268. var system = scene.particleSystems[index];
  10269. if (system.emitter === source) {
  10270. system.clone(system.name, this);
  10271. }
  10272. }
  10273. this.computeWorldMatrix(true);
  10274. }
  10275. // Parent
  10276. if (parent !== null) {
  10277. this.parent = parent;
  10278. }
  10279. }
  10280. Object.defineProperty(Mesh, "FRONTSIDE", {
  10281. get: function () {
  10282. return Mesh._FRONTSIDE;
  10283. },
  10284. enumerable: true,
  10285. configurable: true
  10286. });
  10287. Object.defineProperty(Mesh, "BACKSIDE", {
  10288. get: function () {
  10289. return Mesh._BACKSIDE;
  10290. },
  10291. enumerable: true,
  10292. configurable: true
  10293. });
  10294. Object.defineProperty(Mesh, "DOUBLESIDE", {
  10295. get: function () {
  10296. return Mesh._DOUBLESIDE;
  10297. },
  10298. enumerable: true,
  10299. configurable: true
  10300. });
  10301. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  10302. get: function () {
  10303. return Mesh._DEFAULTSIDE;
  10304. },
  10305. enumerable: true,
  10306. configurable: true
  10307. });
  10308. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  10309. // Methods
  10310. get: function () {
  10311. return this._LODLevels.length > 0;
  10312. },
  10313. enumerable: true,
  10314. configurable: true
  10315. });
  10316. Mesh.prototype._sortLODLevels = function () {
  10317. this._LODLevels.sort(function (a, b) {
  10318. if (a.distance < b.distance) {
  10319. return 1;
  10320. }
  10321. if (a.distance > b.distance) {
  10322. return -1;
  10323. }
  10324. return 0;
  10325. });
  10326. };
  10327. /**
  10328. * Add a mesh as LOD level triggered at the given distance.
  10329. * @param {number} distance - the distance from the center of the object to show this level
  10330. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  10331. * @return {BABYLON.Mesh} this mesh (for chaining)
  10332. */
  10333. Mesh.prototype.addLODLevel = function (distance, mesh) {
  10334. if (mesh && mesh._masterMesh) {
  10335. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  10336. return this;
  10337. }
  10338. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  10339. this._LODLevels.push(level);
  10340. if (mesh) {
  10341. mesh._masterMesh = this;
  10342. }
  10343. this._sortLODLevels();
  10344. return this;
  10345. };
  10346. /**
  10347. * Remove a mesh from the LOD array
  10348. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  10349. * @return {BABYLON.Mesh} this mesh (for chaining)
  10350. */
  10351. Mesh.prototype.removeLODLevel = function (mesh) {
  10352. for (var index = 0; index < this._LODLevels.length; index++) {
  10353. if (this._LODLevels[index].mesh === mesh) {
  10354. this._LODLevels.splice(index, 1);
  10355. if (mesh) {
  10356. mesh._masterMesh = null;
  10357. }
  10358. }
  10359. }
  10360. this._sortLODLevels();
  10361. return this;
  10362. };
  10363. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  10364. if (!this._LODLevels || this._LODLevels.length === 0) {
  10365. return this;
  10366. }
  10367. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  10368. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  10369. return this;
  10370. }
  10371. for (var index = 0; index < this._LODLevels.length; index++) {
  10372. var level = this._LODLevels[index];
  10373. if (level.distance < distanceToCamera) {
  10374. if (level.mesh) {
  10375. level.mesh._preActivate();
  10376. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10377. }
  10378. return level.mesh;
  10379. }
  10380. }
  10381. return this;
  10382. };
  10383. Object.defineProperty(Mesh.prototype, "geometry", {
  10384. get: function () {
  10385. return this._geometry;
  10386. },
  10387. enumerable: true,
  10388. configurable: true
  10389. });
  10390. Mesh.prototype.getTotalVertices = function () {
  10391. if (!this._geometry) {
  10392. return 0;
  10393. }
  10394. return this._geometry.getTotalVertices();
  10395. };
  10396. Mesh.prototype.getVerticesData = function (kind) {
  10397. if (!this._geometry) {
  10398. return null;
  10399. }
  10400. return this._geometry.getVerticesData(kind);
  10401. };
  10402. Mesh.prototype.getVertexBuffer = function (kind) {
  10403. if (!this._geometry) {
  10404. return undefined;
  10405. }
  10406. return this._geometry.getVertexBuffer(kind);
  10407. };
  10408. Mesh.prototype.isVerticesDataPresent = function (kind) {
  10409. if (!this._geometry) {
  10410. if (this._delayInfo) {
  10411. return this._delayInfo.indexOf(kind) !== -1;
  10412. }
  10413. return false;
  10414. }
  10415. return this._geometry.isVerticesDataPresent(kind);
  10416. };
  10417. Mesh.prototype.getVerticesDataKinds = function () {
  10418. if (!this._geometry) {
  10419. var result = [];
  10420. if (this._delayInfo) {
  10421. for (var kind in this._delayInfo) {
  10422. result.push(kind);
  10423. }
  10424. }
  10425. return result;
  10426. }
  10427. return this._geometry.getVerticesDataKinds();
  10428. };
  10429. Mesh.prototype.getTotalIndices = function () {
  10430. if (!this._geometry) {
  10431. return 0;
  10432. }
  10433. return this._geometry.getTotalIndices();
  10434. };
  10435. Mesh.prototype.getIndices = function () {
  10436. if (!this._geometry) {
  10437. return [];
  10438. }
  10439. return this._geometry.getIndices();
  10440. };
  10441. Object.defineProperty(Mesh.prototype, "isBlocked", {
  10442. get: function () {
  10443. return this._masterMesh !== null && this._masterMesh !== undefined;
  10444. },
  10445. enumerable: true,
  10446. configurable: true
  10447. });
  10448. Mesh.prototype.isReady = function () {
  10449. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10450. return false;
  10451. }
  10452. return _super.prototype.isReady.call(this);
  10453. };
  10454. Mesh.prototype.isDisposed = function () {
  10455. return this._isDisposed;
  10456. };
  10457. // Methods
  10458. Mesh.prototype._preActivate = function () {
  10459. var sceneRenderId = this.getScene().getRenderId();
  10460. if (this._preActivateId === sceneRenderId) {
  10461. return;
  10462. }
  10463. this._preActivateId = sceneRenderId;
  10464. this._visibleInstances = null;
  10465. };
  10466. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  10467. if (!this._visibleInstances) {
  10468. this._visibleInstances = {};
  10469. this._visibleInstances.defaultRenderId = renderId;
  10470. this._visibleInstances.selfDefaultRenderId = this._renderId;
  10471. }
  10472. if (!this._visibleInstances[renderId]) {
  10473. this._visibleInstances[renderId] = new Array();
  10474. }
  10475. this._visibleInstances[renderId].push(instance);
  10476. };
  10477. Mesh.prototype.refreshBoundingInfo = function () {
  10478. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10479. if (data) {
  10480. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  10481. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  10482. }
  10483. if (this.subMeshes) {
  10484. for (var index = 0; index < this.subMeshes.length; index++) {
  10485. this.subMeshes[index].refreshBoundingInfo();
  10486. }
  10487. }
  10488. this._updateBoundingInfo();
  10489. };
  10490. Mesh.prototype._createGlobalSubMesh = function () {
  10491. var totalVertices = this.getTotalVertices();
  10492. if (!totalVertices || !this.getIndices()) {
  10493. return null;
  10494. }
  10495. this.releaseSubMeshes();
  10496. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  10497. };
  10498. Mesh.prototype.subdivide = function (count) {
  10499. if (count < 1) {
  10500. return;
  10501. }
  10502. var totalIndices = this.getTotalIndices();
  10503. var subdivisionSize = (totalIndices / count) | 0;
  10504. var offset = 0;
  10505. while (subdivisionSize % 3 !== 0) {
  10506. subdivisionSize++;
  10507. }
  10508. this.releaseSubMeshes();
  10509. for (var index = 0; index < count; index++) {
  10510. if (offset >= totalIndices) {
  10511. break;
  10512. }
  10513. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  10514. offset += subdivisionSize;
  10515. }
  10516. this.synchronizeInstances();
  10517. };
  10518. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  10519. if (kind instanceof Array) {
  10520. var temp = data;
  10521. data = kind;
  10522. kind = temp;
  10523. BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  10524. }
  10525. if (!this._geometry) {
  10526. var vertexData = new BABYLON.VertexData();
  10527. vertexData.set(data, kind);
  10528. var scene = this.getScene();
  10529. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  10530. }
  10531. else {
  10532. this._geometry.setVerticesData(kind, data, updatable, stride);
  10533. }
  10534. };
  10535. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  10536. if (!this._geometry) {
  10537. return;
  10538. }
  10539. if (!makeItUnique) {
  10540. this._geometry.updateVerticesData(kind, data, updateExtends);
  10541. }
  10542. else {
  10543. this.makeGeometryUnique();
  10544. this.updateVerticesData(kind, data, updateExtends, false);
  10545. }
  10546. };
  10547. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  10548. if (!this._geometry) {
  10549. return;
  10550. }
  10551. if (!makeItUnique) {
  10552. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  10553. }
  10554. else {
  10555. this.makeGeometryUnique();
  10556. this.updateVerticesDataDirectly(kind, data, offset, false);
  10557. }
  10558. };
  10559. Mesh.prototype.makeGeometryUnique = function () {
  10560. if (!this._geometry) {
  10561. return;
  10562. }
  10563. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  10564. geometry.applyToMesh(this);
  10565. };
  10566. Mesh.prototype.setIndices = function (indices, totalVertices) {
  10567. if (!this._geometry) {
  10568. var vertexData = new BABYLON.VertexData();
  10569. vertexData.indices = indices;
  10570. var scene = this.getScene();
  10571. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  10572. }
  10573. else {
  10574. this._geometry.setIndices(indices, totalVertices);
  10575. }
  10576. };
  10577. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  10578. var engine = this.getScene().getEngine();
  10579. // Wireframe
  10580. var indexToBind;
  10581. switch (fillMode) {
  10582. case BABYLON.Material.PointFillMode:
  10583. indexToBind = null;
  10584. break;
  10585. case BABYLON.Material.WireFrameFillMode:
  10586. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  10587. break;
  10588. default:
  10589. case BABYLON.Material.TriangleFillMode:
  10590. indexToBind = this._geometry.getIndexBuffer();
  10591. break;
  10592. }
  10593. // VBOs
  10594. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  10595. };
  10596. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  10597. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10598. return;
  10599. }
  10600. var engine = this.getScene().getEngine();
  10601. switch (fillMode) {
  10602. case BABYLON.Material.PointFillMode:
  10603. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  10604. break;
  10605. case BABYLON.Material.WireFrameFillMode:
  10606. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  10607. break;
  10608. default:
  10609. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  10610. }
  10611. };
  10612. Mesh.prototype.registerBeforeRender = function (func) {
  10613. this._onBeforeRenderCallbacks.push(func);
  10614. };
  10615. Mesh.prototype.unregisterBeforeRender = function (func) {
  10616. var index = this._onBeforeRenderCallbacks.indexOf(func);
  10617. if (index > -1) {
  10618. this._onBeforeRenderCallbacks.splice(index, 1);
  10619. }
  10620. };
  10621. Mesh.prototype.registerAfterRender = function (func) {
  10622. this._onAfterRenderCallbacks.push(func);
  10623. };
  10624. Mesh.prototype.unregisterAfterRender = function (func) {
  10625. var index = this._onAfterRenderCallbacks.indexOf(func);
  10626. if (index > -1) {
  10627. this._onAfterRenderCallbacks.splice(index, 1);
  10628. }
  10629. };
  10630. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  10631. var scene = this.getScene();
  10632. this._batchCache.mustReturn = false;
  10633. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  10634. this._batchCache.visibleInstances[subMeshId] = null;
  10635. if (this._visibleInstances) {
  10636. var currentRenderId = scene.getRenderId();
  10637. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  10638. var selfRenderId = this._renderId;
  10639. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  10640. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  10641. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  10642. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  10643. }
  10644. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  10645. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  10646. this._batchCache.mustReturn = true;
  10647. return this._batchCache;
  10648. }
  10649. if (currentRenderId !== selfRenderId) {
  10650. this._batchCache.renderSelf[subMeshId] = false;
  10651. }
  10652. }
  10653. this._renderIdForInstances[subMeshId] = currentRenderId;
  10654. }
  10655. return this._batchCache;
  10656. };
  10657. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  10658. var visibleInstances = batch.visibleInstances[subMesh._id];
  10659. var matricesCount = visibleInstances.length + 1;
  10660. var bufferSize = matricesCount * 16 * 4;
  10661. while (this._instancesBufferSize < bufferSize) {
  10662. this._instancesBufferSize *= 2;
  10663. }
  10664. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  10665. if (this._worldMatricesInstancesBuffer) {
  10666. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10667. }
  10668. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  10669. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  10670. }
  10671. var offset = 0;
  10672. var instancesCount = 0;
  10673. var world = this.getWorldMatrix();
  10674. if (batch.renderSelf[subMesh._id]) {
  10675. world.copyToArray(this._worldMatricesInstancesArray, offset);
  10676. offset += 16;
  10677. instancesCount++;
  10678. }
  10679. if (visibleInstances) {
  10680. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  10681. var instance = visibleInstances[instanceIndex];
  10682. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  10683. offset += 16;
  10684. instancesCount++;
  10685. }
  10686. }
  10687. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  10688. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  10689. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  10690. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  10691. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  10692. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  10693. this._draw(subMesh, fillMode, instancesCount);
  10694. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  10695. };
  10696. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw) {
  10697. var scene = this.getScene();
  10698. var engine = scene.getEngine();
  10699. if (hardwareInstancedRendering) {
  10700. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  10701. }
  10702. else {
  10703. if (batch.renderSelf[subMesh._id]) {
  10704. // Draw
  10705. if (onBeforeDraw) {
  10706. onBeforeDraw(false, this.getWorldMatrix());
  10707. }
  10708. this._draw(subMesh, fillMode);
  10709. }
  10710. if (batch.visibleInstances[subMesh._id]) {
  10711. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  10712. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  10713. // World
  10714. var world = instance.getWorldMatrix();
  10715. if (onBeforeDraw) {
  10716. onBeforeDraw(true, world);
  10717. }
  10718. // Draw
  10719. this._draw(subMesh, fillMode);
  10720. }
  10721. }
  10722. }
  10723. };
  10724. Mesh.prototype.render = function (subMesh) {
  10725. var scene = this.getScene();
  10726. // Managing instances
  10727. var batch = this._getInstancesRenderList(subMesh._id);
  10728. if (batch.mustReturn) {
  10729. return;
  10730. }
  10731. // Checking geometry state
  10732. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  10733. return;
  10734. }
  10735. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  10736. this._onBeforeRenderCallbacks[callbackIndex](this);
  10737. }
  10738. var engine = scene.getEngine();
  10739. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  10740. // Material
  10741. var effectiveMaterial = subMesh.getMaterial();
  10742. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  10743. return;
  10744. }
  10745. // Outline - step 1
  10746. var savedDepthWrite = engine.getDepthWrite();
  10747. if (this.renderOutline) {
  10748. engine.setDepthWrite(false);
  10749. scene.getOutlineRenderer().render(subMesh, batch);
  10750. engine.setDepthWrite(savedDepthWrite);
  10751. }
  10752. effectiveMaterial._preBind();
  10753. var effect = effectiveMaterial.getEffect();
  10754. // Bind
  10755. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  10756. this._bind(subMesh, effect, fillMode);
  10757. var world = this.getWorldMatrix();
  10758. effectiveMaterial.bind(world, this);
  10759. // Draw
  10760. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  10761. if (isInstance) {
  10762. effectiveMaterial.bindOnlyWorldMatrix(world);
  10763. }
  10764. });
  10765. // Unbind
  10766. effectiveMaterial.unbind();
  10767. // Outline - step 2
  10768. if (this.renderOutline && savedDepthWrite) {
  10769. engine.setDepthWrite(true);
  10770. engine.setColorWrite(false);
  10771. scene.getOutlineRenderer().render(subMesh, batch);
  10772. engine.setColorWrite(true);
  10773. }
  10774. // Overlay
  10775. if (this.renderOverlay) {
  10776. var currentMode = engine.getAlphaMode();
  10777. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  10778. scene.getOutlineRenderer().render(subMesh, batch, true);
  10779. engine.setAlphaMode(currentMode);
  10780. }
  10781. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  10782. this._onAfterRenderCallbacks[callbackIndex](this);
  10783. }
  10784. };
  10785. Mesh.prototype.getEmittedParticleSystems = function () {
  10786. var results = new Array();
  10787. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10788. var particleSystem = this.getScene().particleSystems[index];
  10789. if (particleSystem.emitter === this) {
  10790. results.push(particleSystem);
  10791. }
  10792. }
  10793. return results;
  10794. };
  10795. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  10796. var results = new Array();
  10797. var descendants = this.getDescendants();
  10798. descendants.push(this);
  10799. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  10800. var particleSystem = this.getScene().particleSystems[index];
  10801. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  10802. results.push(particleSystem);
  10803. }
  10804. }
  10805. return results;
  10806. };
  10807. Mesh.prototype.getChildren = function () {
  10808. var results = [];
  10809. for (var index = 0; index < this.getScene().meshes.length; index++) {
  10810. var mesh = this.getScene().meshes[index];
  10811. if (mesh.parent === this) {
  10812. results.push(mesh);
  10813. }
  10814. }
  10815. return results;
  10816. };
  10817. Mesh.prototype._checkDelayState = function () {
  10818. var _this = this;
  10819. var that = this;
  10820. var scene = this.getScene();
  10821. if (this._geometry) {
  10822. this._geometry.load(scene);
  10823. }
  10824. else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  10825. that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  10826. scene._addPendingData(that);
  10827. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  10828. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  10829. if (data instanceof ArrayBuffer) {
  10830. _this._delayLoadingFunction(data, _this);
  10831. }
  10832. else {
  10833. _this._delayLoadingFunction(JSON.parse(data), _this);
  10834. }
  10835. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  10836. scene._removePendingData(_this);
  10837. }, function () {
  10838. }, scene.database, getBinaryData);
  10839. }
  10840. };
  10841. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  10842. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  10843. return false;
  10844. }
  10845. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  10846. return false;
  10847. }
  10848. this._checkDelayState();
  10849. return true;
  10850. };
  10851. Mesh.prototype.setMaterialByID = function (id) {
  10852. var materials = this.getScene().materials;
  10853. for (var index = 0; index < materials.length; index++) {
  10854. if (materials[index].id === id) {
  10855. this.material = materials[index];
  10856. return;
  10857. }
  10858. }
  10859. // Multi
  10860. var multiMaterials = this.getScene().multiMaterials;
  10861. for (index = 0; index < multiMaterials.length; index++) {
  10862. if (multiMaterials[index].id === id) {
  10863. this.material = multiMaterials[index];
  10864. return;
  10865. }
  10866. }
  10867. };
  10868. Mesh.prototype.getAnimatables = function () {
  10869. var results = [];
  10870. if (this.material) {
  10871. results.push(this.material);
  10872. }
  10873. if (this.skeleton) {
  10874. results.push(this.skeleton);
  10875. }
  10876. return results;
  10877. };
  10878. // Geometry
  10879. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  10880. // Position
  10881. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  10882. return;
  10883. }
  10884. this._resetPointsArrayCache();
  10885. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10886. var temp = [];
  10887. for (var index = 0; index < data.length; index += 3) {
  10888. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10889. }
  10890. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  10891. // Normals
  10892. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  10893. return;
  10894. }
  10895. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10896. for (index = 0; index < data.length; index += 3) {
  10897. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  10898. }
  10899. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  10900. };
  10901. // Cache
  10902. Mesh.prototype._resetPointsArrayCache = function () {
  10903. this._positions = null;
  10904. };
  10905. Mesh.prototype._generatePointsArray = function () {
  10906. if (this._positions)
  10907. return true;
  10908. this._positions = [];
  10909. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10910. if (!data) {
  10911. return false;
  10912. }
  10913. for (var index = 0; index < data.length; index += 3) {
  10914. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  10915. }
  10916. return true;
  10917. };
  10918. // Clone
  10919. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  10920. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  10921. };
  10922. // Dispose
  10923. Mesh.prototype.dispose = function (doNotRecurse) {
  10924. if (this._geometry) {
  10925. this._geometry.releaseForMesh(this, true);
  10926. }
  10927. // Instances
  10928. if (this._worldMatricesInstancesBuffer) {
  10929. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  10930. this._worldMatricesInstancesBuffer = null;
  10931. }
  10932. while (this.instances.length) {
  10933. this.instances[0].dispose();
  10934. }
  10935. _super.prototype.dispose.call(this, doNotRecurse);
  10936. };
  10937. // Geometric tools
  10938. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  10939. var _this = this;
  10940. var scene = this.getScene();
  10941. var onload = function (img) {
  10942. // Getting height map data
  10943. var canvas = document.createElement("canvas");
  10944. var context = canvas.getContext("2d");
  10945. var heightMapWidth = img.width;
  10946. var heightMapHeight = img.height;
  10947. canvas.width = heightMapWidth;
  10948. canvas.height = heightMapHeight;
  10949. context.drawImage(img, 0, 0);
  10950. // Create VertexData from map data
  10951. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  10952. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  10953. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  10954. //execute success callback, if set
  10955. if (onSuccess) {
  10956. onSuccess(_this);
  10957. }
  10958. };
  10959. BABYLON.Tools.LoadImage(url, onload, function () {
  10960. }, scene.database);
  10961. };
  10962. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  10963. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  10964. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  10965. return;
  10966. }
  10967. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  10968. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  10969. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  10970. var position = BABYLON.Vector3.Zero();
  10971. var normal = BABYLON.Vector3.Zero();
  10972. var uv = BABYLON.Vector2.Zero();
  10973. for (var index = 0; index < positions.length; index += 3) {
  10974. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  10975. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  10976. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  10977. // Compute height
  10978. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  10979. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  10980. var pos = (u + v * heightMapWidth) * 4;
  10981. var r = buffer[pos] / 255.0;
  10982. var g = buffer[pos + 1] / 255.0;
  10983. var b = buffer[pos + 2] / 255.0;
  10984. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  10985. normal.normalize();
  10986. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  10987. position = position.add(normal);
  10988. position.toArray(positions, index);
  10989. }
  10990. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  10991. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  10992. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  10993. };
  10994. Mesh.prototype.convertToFlatShadedMesh = function () {
  10995. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  10996. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  10997. var kinds = this.getVerticesDataKinds();
  10998. var vbs = [];
  10999. var data = [];
  11000. var newdata = [];
  11001. var updatableNormals = false;
  11002. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11003. var kind = kinds[kindIndex];
  11004. var vertexBuffer = this.getVertexBuffer(kind);
  11005. if (kind === BABYLON.VertexBuffer.NormalKind) {
  11006. updatableNormals = vertexBuffer.isUpdatable();
  11007. kinds.splice(kindIndex, 1);
  11008. kindIndex--;
  11009. continue;
  11010. }
  11011. vbs[kind] = vertexBuffer;
  11012. data[kind] = vbs[kind].getData();
  11013. newdata[kind] = [];
  11014. }
  11015. // Save previous submeshes
  11016. var previousSubmeshes = this.subMeshes.slice(0);
  11017. var indices = this.getIndices();
  11018. var totalIndices = this.getTotalIndices();
  11019. for (var index = 0; index < totalIndices; index++) {
  11020. var vertexIndex = indices[index];
  11021. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11022. kind = kinds[kindIndex];
  11023. var stride = vbs[kind].getStrideSize();
  11024. for (var offset = 0; offset < stride; offset++) {
  11025. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  11026. }
  11027. }
  11028. }
  11029. // Updating faces & normal
  11030. var normals = [];
  11031. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  11032. for (index = 0; index < totalIndices; index += 3) {
  11033. indices[index] = index;
  11034. indices[index + 1] = index + 1;
  11035. indices[index + 2] = index + 2;
  11036. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  11037. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  11038. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  11039. var p1p2 = p1.subtract(p2);
  11040. var p3p2 = p3.subtract(p2);
  11041. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  11042. for (var localIndex = 0; localIndex < 3; localIndex++) {
  11043. normals.push(normal.x);
  11044. normals.push(normal.y);
  11045. normals.push(normal.z);
  11046. }
  11047. }
  11048. this.setIndices(indices);
  11049. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  11050. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  11051. kind = kinds[kindIndex];
  11052. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  11053. }
  11054. // Updating submeshes
  11055. this.releaseSubMeshes();
  11056. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  11057. var previousOne = previousSubmeshes[submeshIndex];
  11058. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  11059. }
  11060. this.synchronizeInstances();
  11061. };
  11062. // Instances
  11063. Mesh.prototype.createInstance = function (name) {
  11064. return new BABYLON.InstancedMesh(name, this);
  11065. };
  11066. Mesh.prototype.synchronizeInstances = function () {
  11067. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  11068. var instance = this.instances[instanceIndex];
  11069. instance._syncSubMeshes();
  11070. }
  11071. };
  11072. /**
  11073. * Simplify the mesh according to the given array of settings.
  11074. * Function will return immediately and will simplify async.
  11075. * @param settings a collection of simplification settings.
  11076. * @param parallelProcessing should all levels calculate parallel or one after the other.
  11077. * @param type the type of simplification to run.
  11078. * successCallback optional success callback to be called after the simplification finished processing all settings.
  11079. */
  11080. Mesh.prototype.simplify = function (settings, parallelProcessing, type, successCallback) {
  11081. var _this = this;
  11082. if (parallelProcessing === void 0) { parallelProcessing = true; }
  11083. if (type === void 0) { type = 0 /* QUADRATIC */; }
  11084. var getSimplifier = function () {
  11085. switch (type) {
  11086. case 0 /* QUADRATIC */:
  11087. default:
  11088. return new BABYLON.QuadraticErrorSimplification(_this);
  11089. }
  11090. };
  11091. if (parallelProcessing) {
  11092. //parallel simplifier
  11093. settings.forEach(function (setting) {
  11094. var simplifier = getSimplifier();
  11095. simplifier.simplify(setting, function (newMesh) {
  11096. _this.addLODLevel(setting.distance, newMesh);
  11097. //check if it is the last
  11098. if (setting.quality === settings[settings.length - 1].quality && successCallback) {
  11099. //all done, run the success callback.
  11100. successCallback();
  11101. }
  11102. });
  11103. });
  11104. }
  11105. else {
  11106. //single simplifier.
  11107. var simplifier = getSimplifier();
  11108. var runDecimation = function (setting, callback) {
  11109. simplifier.simplify(setting, function (newMesh) {
  11110. _this.addLODLevel(setting.distance, newMesh);
  11111. //run the next quality level
  11112. callback();
  11113. });
  11114. };
  11115. BABYLON.AsyncLoop.Run(settings.length, function (loop) {
  11116. runDecimation(settings[loop.index], function () {
  11117. loop.executeNext();
  11118. });
  11119. }, function () {
  11120. //execution ended, run the success callback.
  11121. if (successCallback) {
  11122. successCallback();
  11123. }
  11124. });
  11125. }
  11126. };
  11127. // Statics
  11128. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation) {
  11129. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11130. var ribbon = new Mesh(name, scene);
  11131. var vertexData = BABYLON.VertexData.CreateRibbon(pathArray, closeArray, closePath, offset, sideOrientation);
  11132. vertexData.applyToMesh(ribbon, updatable);
  11133. return ribbon;
  11134. };
  11135. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  11136. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11137. var box = new Mesh(name, scene);
  11138. var vertexData = BABYLON.VertexData.CreateBox(size, sideOrientation);
  11139. vertexData.applyToMesh(box, updatable);
  11140. return box;
  11141. };
  11142. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  11143. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11144. var sphere = new Mesh(name, scene);
  11145. var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter, sideOrientation);
  11146. vertexData.applyToMesh(sphere, updatable);
  11147. return sphere;
  11148. };
  11149. // Cylinder and cone (Code inspired by SharpDX.org)
  11150. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  11151. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11152. // subdivisions is a new parameter, we need to support old signature
  11153. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  11154. if (scene !== undefined) {
  11155. updatable = scene;
  11156. }
  11157. scene = subdivisions;
  11158. subdivisions = 1;
  11159. }
  11160. var cylinder = new Mesh(name, scene);
  11161. var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  11162. vertexData.applyToMesh(cylinder, updatable);
  11163. return cylinder;
  11164. };
  11165. // Torus (Code from SharpDX.org)
  11166. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  11167. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11168. var torus = new Mesh(name, scene);
  11169. var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation, sideOrientation);
  11170. vertexData.applyToMesh(torus, updatable);
  11171. return torus;
  11172. };
  11173. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  11174. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11175. var torusKnot = new Mesh(name, scene);
  11176. var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q, sideOrientation);
  11177. vertexData.applyToMesh(torusKnot, updatable);
  11178. return torusKnot;
  11179. };
  11180. // Lines
  11181. Mesh.CreateLines = function (name, points, scene, updatable) {
  11182. var lines = new BABYLON.LinesMesh(name, scene, updatable);
  11183. var vertexData = BABYLON.VertexData.CreateLines(points);
  11184. vertexData.applyToMesh(lines, updatable);
  11185. return lines;
  11186. };
  11187. // Plane & ground
  11188. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  11189. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11190. var plane = new Mesh(name, scene);
  11191. var vertexData = BABYLON.VertexData.CreatePlane(size, sideOrientation);
  11192. vertexData.applyToMesh(plane, updatable);
  11193. return plane;
  11194. };
  11195. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  11196. var ground = new BABYLON.GroundMesh(name, scene);
  11197. ground._setReady(false);
  11198. ground._subdivisions = subdivisions;
  11199. var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
  11200. vertexData.applyToMesh(ground, updatable);
  11201. ground._setReady(true);
  11202. return ground;
  11203. };
  11204. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  11205. var tiledGround = new Mesh(name, scene);
  11206. var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  11207. vertexData.applyToMesh(tiledGround, updatable);
  11208. return tiledGround;
  11209. };
  11210. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  11211. var ground = new BABYLON.GroundMesh(name, scene);
  11212. ground._subdivisions = subdivisions;
  11213. ground._setReady(false);
  11214. var onload = function (img) {
  11215. // Getting height map data
  11216. var canvas = document.createElement("canvas");
  11217. var context = canvas.getContext("2d");
  11218. var heightMapWidth = img.width;
  11219. var heightMapHeight = img.height;
  11220. canvas.width = heightMapWidth;
  11221. canvas.height = heightMapHeight;
  11222. context.drawImage(img, 0, 0);
  11223. // Create VertexData from map data
  11224. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  11225. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  11226. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  11227. vertexData.applyToMesh(ground, updatable);
  11228. ground._setReady(true);
  11229. //execute ready callback, if set
  11230. if (onReady) {
  11231. onReady(ground);
  11232. }
  11233. };
  11234. BABYLON.Tools.LoadImage(url, onload, function () {
  11235. }, scene.database);
  11236. return ground;
  11237. };
  11238. Mesh.CreateTube = function (name, path, radius, tesselation, radiusFunction, scene, updatable, sideOrientation) {
  11239. if (sideOrientation === void 0) { sideOrientation = Mesh.DEFAULTSIDE; }
  11240. var path3D = new BABYLON.Path3D(path);
  11241. var tangents = path3D.getTangents();
  11242. var normals = path3D.getNormals();
  11243. var distances = path3D.getDistances();
  11244. var pi2 = Math.PI * 2;
  11245. var step = pi2 / tesselation;
  11246. var returnRadius = function (i, distance) { return radius; };
  11247. var radiusFunctionFinal = radiusFunction || returnRadius;
  11248. var circlePaths = [];
  11249. var circlePath;
  11250. var rad;
  11251. var normal;
  11252. var rotated;
  11253. var rotationMatrix;
  11254. for (var i = 0; i < path.length; i++) {
  11255. rad = radiusFunctionFinal(i, distances[i]); // current radius
  11256. circlePath = []; // current circle array
  11257. normal = normals[i]; // current normal
  11258. for (var ang = 0; ang < pi2; ang += step) {
  11259. rotationMatrix = BABYLON.Matrix.RotationAxis(tangents[i], ang);
  11260. rotated = BABYLON.Vector3.TransformCoordinates(normal, rotationMatrix).scaleInPlace(rad).add(path[i]);
  11261. circlePath.push(rotated);
  11262. }
  11263. circlePaths.push(circlePath);
  11264. }
  11265. var tube = Mesh.CreateRibbon(name, circlePaths, false, true, 0, scene, updatable, sideOrientation);
  11266. return tube;
  11267. };
  11268. // Tools
  11269. Mesh.MinMax = function (meshes) {
  11270. var minVector = null;
  11271. var maxVector = null;
  11272. for (var i in meshes) {
  11273. var mesh = meshes[i];
  11274. var boundingBox = mesh.getBoundingInfo().boundingBox;
  11275. if (!minVector) {
  11276. minVector = boundingBox.minimumWorld;
  11277. maxVector = boundingBox.maximumWorld;
  11278. continue;
  11279. }
  11280. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  11281. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  11282. }
  11283. return {
  11284. min: minVector,
  11285. max: maxVector
  11286. };
  11287. };
  11288. Mesh.Center = function (meshesOrMinMaxVector) {
  11289. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  11290. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  11291. };
  11292. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices) {
  11293. if (disposeSource === void 0) { disposeSource = true; }
  11294. var source = meshes[0];
  11295. var material = source.material;
  11296. var scene = source.getScene();
  11297. if (!allow32BitsIndices) {
  11298. var totalVertices = 0;
  11299. for (var index = 0; index < meshes.length; index++) {
  11300. totalVertices += meshes[index].getTotalVertices();
  11301. if (totalVertices > 65536) {
  11302. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  11303. return null;
  11304. }
  11305. }
  11306. }
  11307. // Merge
  11308. var vertexData = BABYLON.VertexData.ExtractFromMesh(source);
  11309. vertexData.transform(source.getWorldMatrix());
  11310. for (index = 1; index < meshes.length; index++) {
  11311. var otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index]);
  11312. otherVertexData.transform(meshes[index].getWorldMatrix());
  11313. vertexData.merge(otherVertexData);
  11314. }
  11315. var newMesh = new Mesh(source.name + "_merged", scene);
  11316. vertexData.applyToMesh(newMesh);
  11317. // Setting properties
  11318. newMesh.material = material;
  11319. newMesh.checkCollisions = source.checkCollisions;
  11320. // Cleaning
  11321. if (disposeSource) {
  11322. for (index = 0; index < meshes.length; index++) {
  11323. meshes[index].dispose();
  11324. }
  11325. }
  11326. return newMesh;
  11327. };
  11328. // Consts
  11329. Mesh._FRONTSIDE = 0;
  11330. Mesh._BACKSIDE = 1;
  11331. Mesh._DOUBLESIDE = 2;
  11332. Mesh._DEFAULTSIDE = 0;
  11333. return Mesh;
  11334. })(BABYLON.AbstractMesh);
  11335. BABYLON.Mesh = Mesh;
  11336. })(BABYLON || (BABYLON = {}));
  11337. //# sourceMappingURL=babylon.mesh.js.map
  11338. var BABYLON;
  11339. (function (BABYLON) {
  11340. var GroundMesh = (function (_super) {
  11341. __extends(GroundMesh, _super);
  11342. function GroundMesh(name, scene) {
  11343. _super.call(this, name, scene);
  11344. this.generateOctree = false;
  11345. this._worldInverse = new BABYLON.Matrix();
  11346. }
  11347. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  11348. get: function () {
  11349. return this._subdivisions;
  11350. },
  11351. enumerable: true,
  11352. configurable: true
  11353. });
  11354. GroundMesh.prototype.optimize = function (chunksCount) {
  11355. this.subdivide(this._subdivisions);
  11356. this.createOrUpdateSubmeshesOctree(32);
  11357. };
  11358. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  11359. var ray = new BABYLON.Ray(new BABYLON.Vector3(x, this.getBoundingInfo().boundingBox.maximumWorld.y + 1, z), new BABYLON.Vector3(0, -1, 0));
  11360. this.getWorldMatrix().invertToRef(this._worldInverse);
  11361. ray = BABYLON.Ray.Transform(ray, this._worldInverse);
  11362. var pickInfo = this.intersects(ray);
  11363. if (pickInfo.hit) {
  11364. return pickInfo.pickedPoint.y;
  11365. }
  11366. return 0;
  11367. };
  11368. return GroundMesh;
  11369. })(BABYLON.Mesh);
  11370. BABYLON.GroundMesh = GroundMesh;
  11371. })(BABYLON || (BABYLON = {}));
  11372. //# sourceMappingURL=babylon.groundMesh.js.map
  11373. var BABYLON;
  11374. (function (BABYLON) {
  11375. /**
  11376. * Creates an instance based on a source mesh.
  11377. */
  11378. var InstancedMesh = (function (_super) {
  11379. __extends(InstancedMesh, _super);
  11380. function InstancedMesh(name, source) {
  11381. _super.call(this, name, source.getScene());
  11382. source.instances.push(this);
  11383. this._sourceMesh = source;
  11384. this.position.copyFrom(source.position);
  11385. this.rotation.copyFrom(source.rotation);
  11386. this.scaling.copyFrom(source.scaling);
  11387. if (source.rotationQuaternion) {
  11388. this.rotationQuaternion = source.rotationQuaternion.clone();
  11389. }
  11390. this.infiniteDistance = source.infiniteDistance;
  11391. this.setPivotMatrix(source.getPivotMatrix());
  11392. this.refreshBoundingInfo();
  11393. this._syncSubMeshes();
  11394. }
  11395. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  11396. // Methods
  11397. get: function () {
  11398. return this._sourceMesh.receiveShadows;
  11399. },
  11400. enumerable: true,
  11401. configurable: true
  11402. });
  11403. Object.defineProperty(InstancedMesh.prototype, "material", {
  11404. get: function () {
  11405. return this._sourceMesh.material;
  11406. },
  11407. enumerable: true,
  11408. configurable: true
  11409. });
  11410. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  11411. get: function () {
  11412. return this._sourceMesh.visibility;
  11413. },
  11414. enumerable: true,
  11415. configurable: true
  11416. });
  11417. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  11418. get: function () {
  11419. return this._sourceMesh.skeleton;
  11420. },
  11421. enumerable: true,
  11422. configurable: true
  11423. });
  11424. InstancedMesh.prototype.getTotalVertices = function () {
  11425. return this._sourceMesh.getTotalVertices();
  11426. };
  11427. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  11428. get: function () {
  11429. return this._sourceMesh;
  11430. },
  11431. enumerable: true,
  11432. configurable: true
  11433. });
  11434. InstancedMesh.prototype.getVerticesData = function (kind) {
  11435. return this._sourceMesh.getVerticesData(kind);
  11436. };
  11437. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  11438. return this._sourceMesh.isVerticesDataPresent(kind);
  11439. };
  11440. InstancedMesh.prototype.getIndices = function () {
  11441. return this._sourceMesh.getIndices();
  11442. };
  11443. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  11444. get: function () {
  11445. return this._sourceMesh._positions;
  11446. },
  11447. enumerable: true,
  11448. configurable: true
  11449. });
  11450. InstancedMesh.prototype.refreshBoundingInfo = function () {
  11451. var data = this._sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11452. if (data) {
  11453. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._sourceMesh.getTotalVertices());
  11454. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11455. }
  11456. this._updateBoundingInfo();
  11457. };
  11458. InstancedMesh.prototype._preActivate = function () {
  11459. if (this._currentLOD) {
  11460. this._currentLOD._preActivate();
  11461. }
  11462. };
  11463. InstancedMesh.prototype._activate = function (renderId) {
  11464. if (this._currentLOD) {
  11465. this._currentLOD._registerInstanceForRenderId(this, renderId);
  11466. }
  11467. };
  11468. InstancedMesh.prototype.getLOD = function (camera) {
  11469. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  11470. if (this._currentLOD === this.sourceMesh) {
  11471. return this;
  11472. }
  11473. return this._currentLOD;
  11474. };
  11475. InstancedMesh.prototype._syncSubMeshes = function () {
  11476. this.releaseSubMeshes();
  11477. if (this._sourceMesh.subMeshes) {
  11478. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  11479. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  11480. }
  11481. }
  11482. };
  11483. InstancedMesh.prototype._generatePointsArray = function () {
  11484. return this._sourceMesh._generatePointsArray();
  11485. };
  11486. // Clone
  11487. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11488. var result = this._sourceMesh.createInstance(name);
  11489. // Deep copy
  11490. BABYLON.Tools.DeepCopy(this, result, ["name"], []);
  11491. // Bounding info
  11492. this.refreshBoundingInfo();
  11493. // Parent
  11494. if (newParent) {
  11495. result.parent = newParent;
  11496. }
  11497. if (!doNotCloneChildren) {
  11498. for (var index = 0; index < this.getScene().meshes.length; index++) {
  11499. var mesh = this.getScene().meshes[index];
  11500. if (mesh.parent === this) {
  11501. mesh.clone(mesh.name, result);
  11502. }
  11503. }
  11504. }
  11505. result.computeWorldMatrix(true);
  11506. return result;
  11507. };
  11508. // Dispoe
  11509. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  11510. // Remove from mesh
  11511. var index = this._sourceMesh.instances.indexOf(this);
  11512. this._sourceMesh.instances.splice(index, 1);
  11513. _super.prototype.dispose.call(this, doNotRecurse);
  11514. };
  11515. return InstancedMesh;
  11516. })(BABYLON.AbstractMesh);
  11517. BABYLON.InstancedMesh = InstancedMesh;
  11518. })(BABYLON || (BABYLON = {}));
  11519. //# sourceMappingURL=babylon.instancedMesh.js.mapvar BABYLON;
  11520. (function (BABYLON) {
  11521. var SubMesh = (function () {
  11522. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  11523. if (createBoundingBox === void 0) { createBoundingBox = true; }
  11524. this.materialIndex = materialIndex;
  11525. this.verticesStart = verticesStart;
  11526. this.verticesCount = verticesCount;
  11527. this.indexStart = indexStart;
  11528. this.indexCount = indexCount;
  11529. this._renderId = 0;
  11530. this._mesh = mesh;
  11531. this._renderingMesh = renderingMesh || mesh;
  11532. mesh.subMeshes.push(this);
  11533. this._id = mesh.subMeshes.length - 1;
  11534. if (createBoundingBox) {
  11535. this.refreshBoundingInfo();
  11536. }
  11537. }
  11538. SubMesh.prototype.getBoundingInfo = function () {
  11539. return this._boundingInfo;
  11540. };
  11541. SubMesh.prototype.getMesh = function () {
  11542. return this._mesh;
  11543. };
  11544. SubMesh.prototype.getRenderingMesh = function () {
  11545. return this._renderingMesh;
  11546. };
  11547. SubMesh.prototype.getMaterial = function () {
  11548. var rootMaterial = this._renderingMesh.material;
  11549. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  11550. var multiMaterial = rootMaterial;
  11551. return multiMaterial.getSubMaterial(this.materialIndex);
  11552. }
  11553. if (!rootMaterial) {
  11554. return this._mesh.getScene().defaultMaterial;
  11555. }
  11556. return rootMaterial;
  11557. };
  11558. // Methods
  11559. SubMesh.prototype.refreshBoundingInfo = function () {
  11560. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  11561. if (!data) {
  11562. this._boundingInfo = this._mesh._boundingInfo;
  11563. return;
  11564. }
  11565. var indices = this._renderingMesh.getIndices();
  11566. var extend;
  11567. if (this.indexStart === 0 && this.indexCount === indices.length) {
  11568. extend = BABYLON.Tools.ExtractMinAndMax(data, this.verticesStart, this.verticesCount);
  11569. }
  11570. else {
  11571. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount);
  11572. }
  11573. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  11574. };
  11575. SubMesh.prototype._checkCollision = function (collider) {
  11576. return this._boundingInfo._checkCollision(collider);
  11577. };
  11578. SubMesh.prototype.updateBoundingInfo = function (world) {
  11579. if (!this._boundingInfo) {
  11580. this.refreshBoundingInfo();
  11581. }
  11582. this._boundingInfo._update(world);
  11583. };
  11584. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  11585. return this._boundingInfo.isInFrustum(frustumPlanes);
  11586. };
  11587. SubMesh.prototype.render = function () {
  11588. this._renderingMesh.render(this);
  11589. };
  11590. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  11591. if (!this._linesIndexBuffer) {
  11592. var linesIndices = [];
  11593. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11594. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  11595. }
  11596. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  11597. this.linesIndexCount = linesIndices.length;
  11598. }
  11599. return this._linesIndexBuffer;
  11600. };
  11601. SubMesh.prototype.canIntersects = function (ray) {
  11602. return ray.intersectsBox(this._boundingInfo.boundingBox);
  11603. };
  11604. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  11605. var intersectInfo = null;
  11606. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  11607. var p0 = positions[indices[index]];
  11608. var p1 = positions[indices[index + 1]];
  11609. var p2 = positions[indices[index + 2]];
  11610. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  11611. if (currentIntersectInfo) {
  11612. if (currentIntersectInfo.distance < 0) {
  11613. continue;
  11614. }
  11615. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11616. intersectInfo = currentIntersectInfo;
  11617. intersectInfo.faceId = index / 3;
  11618. if (fastCheck) {
  11619. break;
  11620. }
  11621. }
  11622. }
  11623. }
  11624. return intersectInfo;
  11625. };
  11626. // Clone
  11627. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  11628. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  11629. result._boundingInfo = new BABYLON.BoundingInfo(this._boundingInfo.minimum, this._boundingInfo.maximum);
  11630. return result;
  11631. };
  11632. // Dispose
  11633. SubMesh.prototype.dispose = function () {
  11634. if (this._linesIndexBuffer) {
  11635. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  11636. this._linesIndexBuffer = null;
  11637. }
  11638. // Remove from mesh
  11639. var index = this._mesh.subMeshes.indexOf(this);
  11640. this._mesh.subMeshes.splice(index, 1);
  11641. };
  11642. // Statics
  11643. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  11644. var minVertexIndex = Number.MAX_VALUE;
  11645. var maxVertexIndex = -Number.MAX_VALUE;
  11646. renderingMesh = renderingMesh || mesh;
  11647. var indices = renderingMesh.getIndices();
  11648. for (var index = startIndex; index < startIndex + indexCount; index++) {
  11649. var vertexIndex = indices[index];
  11650. if (vertexIndex < minVertexIndex)
  11651. minVertexIndex = vertexIndex;
  11652. if (vertexIndex > maxVertexIndex)
  11653. maxVertexIndex = vertexIndex;
  11654. }
  11655. return new BABYLON.SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  11656. };
  11657. return SubMesh;
  11658. })();
  11659. BABYLON.SubMesh = SubMesh;
  11660. })(BABYLON || (BABYLON = {}));
  11661. //# sourceMappingURL=babylon.subMesh.js.mapvar BABYLON;
  11662. (function (BABYLON) {
  11663. var BaseTexture = (function () {
  11664. function BaseTexture(scene) {
  11665. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  11666. this.hasAlpha = false;
  11667. this.getAlphaFromRGB = false;
  11668. this.level = 1;
  11669. this.isCube = false;
  11670. this.isRenderTarget = false;
  11671. this.animations = new Array();
  11672. this.coordinatesIndex = 0;
  11673. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  11674. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  11675. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  11676. this.anisotropicFilteringLevel = 4;
  11677. this._scene = scene;
  11678. this._scene.textures.push(this);
  11679. }
  11680. BaseTexture.prototype.getScene = function () {
  11681. return this._scene;
  11682. };
  11683. BaseTexture.prototype.getTextureMatrix = function () {
  11684. return null;
  11685. };
  11686. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  11687. return null;
  11688. };
  11689. BaseTexture.prototype.getInternalTexture = function () {
  11690. return this._texture;
  11691. };
  11692. BaseTexture.prototype.isReady = function () {
  11693. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  11694. return true;
  11695. }
  11696. if (this._texture) {
  11697. return this._texture.isReady;
  11698. }
  11699. return false;
  11700. };
  11701. BaseTexture.prototype.getSize = function () {
  11702. if (this._texture._width) {
  11703. return { width: this._texture._width, height: this._texture._height };
  11704. }
  11705. if (this._texture._size) {
  11706. return { width: this._texture._size, height: this._texture._size };
  11707. }
  11708. return { width: 0, height: 0 };
  11709. };
  11710. BaseTexture.prototype.getBaseSize = function () {
  11711. if (!this.isReady())
  11712. return { width: 0, height: 0 };
  11713. if (this._texture._size) {
  11714. return { width: this._texture._size, height: this._texture._size };
  11715. }
  11716. return { width: this._texture._baseWidth, height: this._texture._baseHeight };
  11717. };
  11718. BaseTexture.prototype.scale = function (ratio) {
  11719. };
  11720. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  11721. get: function () {
  11722. return false;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  11728. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11729. for (var index = 0; index < texturesCache.length; index++) {
  11730. var texturesCacheEntry = texturesCache[index];
  11731. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11732. texturesCache.splice(index, 1);
  11733. return;
  11734. }
  11735. }
  11736. };
  11737. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  11738. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11739. for (var index = 0; index < texturesCache.length; index++) {
  11740. var texturesCacheEntry = texturesCache[index];
  11741. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  11742. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  11743. texturesCacheEntry.references++;
  11744. return texturesCacheEntry;
  11745. }
  11746. }
  11747. }
  11748. return null;
  11749. };
  11750. BaseTexture.prototype.delayLoad = function () {
  11751. };
  11752. BaseTexture.prototype.releaseInternalTexture = function () {
  11753. if (!this._texture) {
  11754. return;
  11755. }
  11756. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  11757. this._texture.references--;
  11758. // Final reference ?
  11759. if (this._texture.references === 0) {
  11760. var index = texturesCache.indexOf(this._texture);
  11761. texturesCache.splice(index, 1);
  11762. this._scene.getEngine()._releaseTexture(this._texture);
  11763. delete this._texture;
  11764. }
  11765. };
  11766. BaseTexture.prototype.clone = function () {
  11767. return null;
  11768. };
  11769. BaseTexture.prototype.dispose = function () {
  11770. // Remove from scene
  11771. var index = this._scene.textures.indexOf(this);
  11772. if (index >= 0) {
  11773. this._scene.textures.splice(index, 1);
  11774. }
  11775. if (this._texture === undefined) {
  11776. return;
  11777. }
  11778. this.releaseInternalTexture();
  11779. // Callback
  11780. if (this.onDispose) {
  11781. this.onDispose();
  11782. }
  11783. };
  11784. return BaseTexture;
  11785. })();
  11786. BABYLON.BaseTexture = BaseTexture;
  11787. })(BABYLON || (BABYLON = {}));
  11788. //# sourceMappingURL=babylon.baseTexture.js.mapvar BABYLON;
  11789. (function (BABYLON) {
  11790. var RenderingGroup = (function () {
  11791. function RenderingGroup(index, scene) {
  11792. this.index = index;
  11793. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  11794. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  11795. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  11796. this._scene = scene;
  11797. }
  11798. RenderingGroup.prototype.render = function (customRenderFunction) {
  11799. if (customRenderFunction) {
  11800. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  11801. return true;
  11802. }
  11803. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  11804. return false;
  11805. }
  11806. var engine = this._scene.getEngine();
  11807. // Opaque
  11808. var subIndex;
  11809. var submesh;
  11810. for (subIndex = 0; subIndex < this._opaqueSubMeshes.length; subIndex++) {
  11811. submesh = this._opaqueSubMeshes.data[subIndex];
  11812. submesh.render();
  11813. }
  11814. // Alpha test
  11815. engine.setAlphaTesting(true);
  11816. for (subIndex = 0; subIndex < this._alphaTestSubMeshes.length; subIndex++) {
  11817. submesh = this._alphaTestSubMeshes.data[subIndex];
  11818. submesh.render();
  11819. }
  11820. engine.setAlphaTesting(false);
  11821. // Transparent
  11822. if (this._transparentSubMeshes.length) {
  11823. for (subIndex = 0; subIndex < this._transparentSubMeshes.length; subIndex++) {
  11824. submesh = this._transparentSubMeshes.data[subIndex];
  11825. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  11826. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(this._scene.activeCamera.position).length();
  11827. }
  11828. var sortedArray = this._transparentSubMeshes.data.slice(0, this._transparentSubMeshes.length);
  11829. sortedArray.sort(function (a, b) {
  11830. // Alpha index first
  11831. if (a._alphaIndex > b._alphaIndex) {
  11832. return 1;
  11833. }
  11834. if (a._alphaIndex < b._alphaIndex) {
  11835. return -1;
  11836. }
  11837. // Then distance to camera
  11838. if (a._distanceToCamera < b._distanceToCamera) {
  11839. return 1;
  11840. }
  11841. if (a._distanceToCamera > b._distanceToCamera) {
  11842. return -1;
  11843. }
  11844. return 0;
  11845. });
  11846. // Rendering
  11847. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  11848. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  11849. submesh = sortedArray[subIndex];
  11850. submesh.render();
  11851. }
  11852. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  11853. }
  11854. return true;
  11855. };
  11856. RenderingGroup.prototype.prepare = function () {
  11857. this._opaqueSubMeshes.reset();
  11858. this._transparentSubMeshes.reset();
  11859. this._alphaTestSubMeshes.reset();
  11860. };
  11861. RenderingGroup.prototype.dispatch = function (subMesh) {
  11862. var material = subMesh.getMaterial();
  11863. var mesh = subMesh.getMesh();
  11864. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  11865. this._transparentSubMeshes.push(subMesh);
  11866. }
  11867. else if (material.needAlphaTesting()) {
  11868. this._alphaTestSubMeshes.push(subMesh);
  11869. }
  11870. else {
  11871. this._opaqueSubMeshes.push(subMesh); // Opaque
  11872. }
  11873. };
  11874. return RenderingGroup;
  11875. })();
  11876. BABYLON.RenderingGroup = RenderingGroup;
  11877. })(BABYLON || (BABYLON = {}));
  11878. //# sourceMappingURL=babylon.renderingGroup.js.mapvar BABYLON;
  11879. (function (BABYLON) {
  11880. var RenderingManager = (function () {
  11881. function RenderingManager(scene) {
  11882. this._renderingGroups = new Array();
  11883. this._scene = scene;
  11884. }
  11885. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  11886. if (this._scene._activeParticleSystems.length === 0) {
  11887. return;
  11888. }
  11889. // Particles
  11890. var beforeParticlesDate = BABYLON.Tools.Now;
  11891. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  11892. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  11893. if (particleSystem.renderingGroupId !== index) {
  11894. continue;
  11895. }
  11896. this._clearDepthBuffer();
  11897. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  11898. this._scene._activeParticles += particleSystem.render();
  11899. }
  11900. }
  11901. this._scene._particlesDuration += BABYLON.Tools.Now - beforeParticlesDate;
  11902. };
  11903. RenderingManager.prototype._renderSprites = function (index) {
  11904. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  11905. return;
  11906. }
  11907. // Sprites
  11908. var beforeSpritessDate = BABYLON.Tools.Now;
  11909. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  11910. var spriteManager = this._scene.spriteManagers[id];
  11911. if (spriteManager.renderingGroupId === index) {
  11912. this._clearDepthBuffer();
  11913. spriteManager.render();
  11914. }
  11915. }
  11916. this._scene._spritesDuration += BABYLON.Tools.Now - beforeSpritessDate;
  11917. };
  11918. RenderingManager.prototype._clearDepthBuffer = function () {
  11919. if (this._depthBufferAlreadyCleaned) {
  11920. return;
  11921. }
  11922. this._scene.getEngine().clear(0, false, true);
  11923. this._depthBufferAlreadyCleaned = true;
  11924. };
  11925. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  11926. for (var index = 0; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  11927. this._depthBufferAlreadyCleaned = false;
  11928. var renderingGroup = this._renderingGroups[index];
  11929. var needToStepBack = false;
  11930. if (renderingGroup) {
  11931. this._clearDepthBuffer();
  11932. if (!renderingGroup.render(customRenderFunction)) {
  11933. this._renderingGroups.splice(index, 1);
  11934. needToStepBack = true;
  11935. }
  11936. }
  11937. if (renderSprites) {
  11938. this._renderSprites(index);
  11939. }
  11940. if (renderParticles) {
  11941. this._renderParticles(index, activeMeshes);
  11942. }
  11943. if (needToStepBack) {
  11944. index--;
  11945. }
  11946. }
  11947. };
  11948. RenderingManager.prototype.reset = function () {
  11949. for (var index in this._renderingGroups) {
  11950. var renderingGroup = this._renderingGroups[index];
  11951. renderingGroup.prepare();
  11952. }
  11953. };
  11954. RenderingManager.prototype.dispatch = function (subMesh) {
  11955. var mesh = subMesh.getMesh();
  11956. var renderingGroupId = mesh.renderingGroupId || 0;
  11957. if (!this._renderingGroups[renderingGroupId]) {
  11958. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene);
  11959. }
  11960. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  11961. };
  11962. RenderingManager.MAX_RENDERINGGROUPS = 4;
  11963. return RenderingManager;
  11964. })();
  11965. BABYLON.RenderingManager = RenderingManager;
  11966. })(BABYLON || (BABYLON = {}));
  11967. //# sourceMappingURL=babylon.renderingManager.js.map
  11968. var BABYLON;
  11969. (function (BABYLON) {
  11970. var Texture = (function (_super) {
  11971. __extends(Texture, _super);
  11972. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  11973. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  11974. if (onLoad === void 0) { onLoad = null; }
  11975. if (onError === void 0) { onError = null; }
  11976. if (buffer === void 0) { buffer = null; }
  11977. if (deleteBuffer === void 0) { deleteBuffer = false; }
  11978. _super.call(this, scene);
  11979. this.uOffset = 0;
  11980. this.vOffset = 0;
  11981. this.uScale = 1.0;
  11982. this.vScale = 1.0;
  11983. this.uAng = 0;
  11984. this.vAng = 0;
  11985. this.wAng = 0;
  11986. this.name = url;
  11987. this.url = url;
  11988. this._noMipmap = noMipmap;
  11989. this._invertY = invertY;
  11990. this._samplingMode = samplingMode;
  11991. this._buffer = buffer;
  11992. this._deleteBuffer = deleteBuffer;
  11993. if (!url) {
  11994. return;
  11995. }
  11996. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  11997. if (!this._texture) {
  11998. if (!scene.useDelayedTextureLoading) {
  11999. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, onLoad, onError, this._buffer);
  12000. if (deleteBuffer) {
  12001. delete this._buffer;
  12002. }
  12003. }
  12004. else {
  12005. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12006. }
  12007. }
  12008. }
  12009. Texture.prototype.delayLoad = function () {
  12010. if (this.delayLoadState != BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12011. return;
  12012. }
  12013. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12014. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  12015. if (!this._texture) {
  12016. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, null, null, this._buffer);
  12017. if (this._deleteBuffer) {
  12018. delete this._buffer;
  12019. }
  12020. }
  12021. };
  12022. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  12023. x -= this.uOffset + 0.5;
  12024. y -= this.vOffset + 0.5;
  12025. z -= 0.5;
  12026. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  12027. t.x *= this.uScale;
  12028. t.y *= this.vScale;
  12029. t.x += 0.5;
  12030. t.y += 0.5;
  12031. t.z += 0.5;
  12032. };
  12033. Texture.prototype.getTextureMatrix = function () {
  12034. 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) {
  12035. return this._cachedTextureMatrix;
  12036. }
  12037. this._cachedUOffset = this.uOffset;
  12038. this._cachedVOffset = this.vOffset;
  12039. this._cachedUScale = this.uScale;
  12040. this._cachedVScale = this.vScale;
  12041. this._cachedUAng = this.uAng;
  12042. this._cachedVAng = this.vAng;
  12043. this._cachedWAng = this.wAng;
  12044. if (!this._cachedTextureMatrix) {
  12045. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12046. this._rowGenerationMatrix = new BABYLON.Matrix();
  12047. this._t0 = BABYLON.Vector3.Zero();
  12048. this._t1 = BABYLON.Vector3.Zero();
  12049. this._t2 = BABYLON.Vector3.Zero();
  12050. }
  12051. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  12052. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  12053. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  12054. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  12055. this._t1.subtractInPlace(this._t0);
  12056. this._t2.subtractInPlace(this._t0);
  12057. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12058. this._cachedTextureMatrix.m[0] = this._t1.x;
  12059. this._cachedTextureMatrix.m[1] = this._t1.y;
  12060. this._cachedTextureMatrix.m[2] = this._t1.z;
  12061. this._cachedTextureMatrix.m[4] = this._t2.x;
  12062. this._cachedTextureMatrix.m[5] = this._t2.y;
  12063. this._cachedTextureMatrix.m[6] = this._t2.z;
  12064. this._cachedTextureMatrix.m[8] = this._t0.x;
  12065. this._cachedTextureMatrix.m[9] = this._t0.y;
  12066. this._cachedTextureMatrix.m[10] = this._t0.z;
  12067. return this._cachedTextureMatrix;
  12068. };
  12069. Texture.prototype.getReflectionTextureMatrix = function () {
  12070. if (this.uOffset === this._cachedUOffset && this.vOffset === this._cachedVOffset && this.uScale === this._cachedUScale && this.vScale === this._cachedVScale && this.coordinatesMode === this._cachedCoordinatesMode) {
  12071. return this._cachedTextureMatrix;
  12072. }
  12073. if (!this._cachedTextureMatrix) {
  12074. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  12075. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  12076. }
  12077. this._cachedCoordinatesMode = this.coordinatesMode;
  12078. switch (this.coordinatesMode) {
  12079. case BABYLON.Texture.SPHERICAL_MODE:
  12080. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12081. this._cachedTextureMatrix[0] = -0.5 * this.uScale;
  12082. this._cachedTextureMatrix[5] = -0.5 * this.vScale;
  12083. this._cachedTextureMatrix[12] = 0.5 + this.uOffset;
  12084. this._cachedTextureMatrix[13] = 0.5 + this.vOffset;
  12085. break;
  12086. case BABYLON.Texture.PLANAR_MODE:
  12087. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12088. this._cachedTextureMatrix[0] = this.uScale;
  12089. this._cachedTextureMatrix[5] = this.vScale;
  12090. this._cachedTextureMatrix[12] = this.uOffset;
  12091. this._cachedTextureMatrix[13] = this.vOffset;
  12092. break;
  12093. case BABYLON.Texture.PROJECTION_MODE:
  12094. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  12095. this._projectionModeMatrix.m[0] = 0.5;
  12096. this._projectionModeMatrix.m[5] = -0.5;
  12097. this._projectionModeMatrix.m[10] = 0.0;
  12098. this._projectionModeMatrix.m[12] = 0.5;
  12099. this._projectionModeMatrix.m[13] = 0.5;
  12100. this._projectionModeMatrix.m[14] = 1.0;
  12101. this._projectionModeMatrix.m[15] = 1.0;
  12102. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  12103. break;
  12104. default:
  12105. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  12106. break;
  12107. }
  12108. return this._cachedTextureMatrix;
  12109. };
  12110. Texture.prototype.clone = function () {
  12111. var newTexture = new BABYLON.Texture(this._texture.url, this.getScene(), this._noMipmap, this._invertY, this._samplingMode);
  12112. // Base texture
  12113. newTexture.hasAlpha = this.hasAlpha;
  12114. newTexture.level = this.level;
  12115. newTexture.wrapU = this.wrapU;
  12116. newTexture.wrapV = this.wrapV;
  12117. newTexture.coordinatesIndex = this.coordinatesIndex;
  12118. newTexture.coordinatesMode = this.coordinatesMode;
  12119. // Texture
  12120. newTexture.uOffset = this.uOffset;
  12121. newTexture.vOffset = this.vOffset;
  12122. newTexture.uScale = this.uScale;
  12123. newTexture.vScale = this.vScale;
  12124. newTexture.uAng = this.uAng;
  12125. newTexture.vAng = this.vAng;
  12126. newTexture.wAng = this.wAng;
  12127. return newTexture;
  12128. };
  12129. // Statics
  12130. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  12131. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  12132. if (onLoad === void 0) { onLoad = null; }
  12133. if (onError === void 0) { onError = null; }
  12134. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  12135. };
  12136. // Constants
  12137. Texture.NEAREST_SAMPLINGMODE = 1;
  12138. Texture.BILINEAR_SAMPLINGMODE = 2;
  12139. Texture.TRILINEAR_SAMPLINGMODE = 3;
  12140. Texture.EXPLICIT_MODE = 0;
  12141. Texture.SPHERICAL_MODE = 1;
  12142. Texture.PLANAR_MODE = 2;
  12143. Texture.CUBIC_MODE = 3;
  12144. Texture.PROJECTION_MODE = 4;
  12145. Texture.SKYBOX_MODE = 5;
  12146. Texture.CLAMP_ADDRESSMODE = 0;
  12147. Texture.WRAP_ADDRESSMODE = 1;
  12148. Texture.MIRROR_ADDRESSMODE = 2;
  12149. return Texture;
  12150. })(BABYLON.BaseTexture);
  12151. BABYLON.Texture = Texture;
  12152. })(BABYLON || (BABYLON = {}));
  12153. //# sourceMappingURL=babylon.texture.js.map
  12154. var BABYLON;
  12155. (function (BABYLON) {
  12156. var CubeTexture = (function (_super) {
  12157. __extends(CubeTexture, _super);
  12158. function CubeTexture(rootUrl, scene, extensions, noMipmap) {
  12159. _super.call(this, scene);
  12160. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  12161. this.name = rootUrl;
  12162. this.url = rootUrl;
  12163. this._noMipmap = noMipmap;
  12164. this.hasAlpha = false;
  12165. this._texture = this._getFromCache(rootUrl, noMipmap);
  12166. if (!extensions) {
  12167. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  12168. }
  12169. this._extensions = extensions;
  12170. if (!this._texture) {
  12171. if (!scene.useDelayedTextureLoading) {
  12172. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, extensions, noMipmap);
  12173. }
  12174. else {
  12175. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  12176. }
  12177. }
  12178. this.isCube = true;
  12179. this._textureMatrix = BABYLON.Matrix.Identity();
  12180. }
  12181. CubeTexture.prototype.clone = function () {
  12182. var newTexture = new CubeTexture(this.url, this.getScene(), this._extensions, this._noMipmap);
  12183. // Base texture
  12184. newTexture.level = this.level;
  12185. newTexture.wrapU = this.wrapU;
  12186. newTexture.wrapV = this.wrapV;
  12187. newTexture.coordinatesIndex = this.coordinatesIndex;
  12188. newTexture.coordinatesMode = this.coordinatesMode;
  12189. return newTexture;
  12190. };
  12191. // Methods
  12192. CubeTexture.prototype.delayLoad = function () {
  12193. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  12194. return;
  12195. }
  12196. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  12197. this._texture = this._getFromCache(this.url, this._noMipmap);
  12198. if (!this._texture) {
  12199. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._extensions);
  12200. }
  12201. };
  12202. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  12203. return this._textureMatrix;
  12204. };
  12205. return CubeTexture;
  12206. })(BABYLON.BaseTexture);
  12207. BABYLON.CubeTexture = CubeTexture;
  12208. })(BABYLON || (BABYLON = {}));
  12209. //# sourceMappingURL=babylon.cubeTexture.js.map
  12210. var BABYLON;
  12211. (function (BABYLON) {
  12212. var RenderTargetTexture = (function (_super) {
  12213. __extends(RenderTargetTexture, _super);
  12214. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type) {
  12215. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  12216. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  12217. _super.call(this, null, scene, !generateMipMaps);
  12218. this.renderList = new Array();
  12219. this.renderParticles = true;
  12220. this.renderSprites = false;
  12221. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  12222. this._currentRefreshId = -1;
  12223. this._refreshRate = 1;
  12224. this.name = name;
  12225. this.isRenderTarget = true;
  12226. this._size = size;
  12227. this._generateMipMaps = generateMipMaps;
  12228. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  12229. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: generateMipMaps, type: type });
  12230. // Rendering groups
  12231. this._renderingManager = new BABYLON.RenderingManager(scene);
  12232. }
  12233. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  12234. this._currentRefreshId = -1;
  12235. };
  12236. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  12237. get: function () {
  12238. return this._refreshRate;
  12239. },
  12240. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12241. set: function (value) {
  12242. this._refreshRate = value;
  12243. this.resetRefreshCounter();
  12244. },
  12245. enumerable: true,
  12246. configurable: true
  12247. });
  12248. RenderTargetTexture.prototype._shouldRender = function () {
  12249. if (this._currentRefreshId === -1) {
  12250. this._currentRefreshId = 1;
  12251. return true;
  12252. }
  12253. if (this.refreshRate === this._currentRefreshId) {
  12254. this._currentRefreshId = 1;
  12255. return true;
  12256. }
  12257. this._currentRefreshId++;
  12258. return false;
  12259. };
  12260. RenderTargetTexture.prototype.isReady = function () {
  12261. if (!this.getScene().renderTargetsEnabled) {
  12262. return false;
  12263. }
  12264. return _super.prototype.isReady.call(this);
  12265. };
  12266. RenderTargetTexture.prototype.getRenderSize = function () {
  12267. return this._size;
  12268. };
  12269. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  12270. get: function () {
  12271. return true;
  12272. },
  12273. enumerable: true,
  12274. configurable: true
  12275. });
  12276. RenderTargetTexture.prototype.scale = function (ratio) {
  12277. var newSize = this._size * ratio;
  12278. this.resize(newSize, this._generateMipMaps);
  12279. };
  12280. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  12281. this.releaseInternalTexture();
  12282. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12283. };
  12284. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  12285. var scene = this.getScene();
  12286. var engine = scene.getEngine();
  12287. if (this._waitingRenderList) {
  12288. this.renderList = [];
  12289. for (var index = 0; index < this._waitingRenderList.length; index++) {
  12290. var id = this._waitingRenderList[index];
  12291. this.renderList.push(scene.getMeshByID(id));
  12292. }
  12293. delete this._waitingRenderList;
  12294. }
  12295. if (this.renderList && this.renderList.length === 0) {
  12296. return;
  12297. }
  12298. // Bind
  12299. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  12300. engine.bindFramebuffer(this._texture);
  12301. }
  12302. this._renderingManager.reset();
  12303. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  12304. for (var meshIndex = 0; meshIndex < currentRenderList.length; meshIndex++) {
  12305. var mesh = currentRenderList[meshIndex];
  12306. if (mesh) {
  12307. if (!mesh.isReady()) {
  12308. // Reset _currentRefreshId
  12309. this.resetRefreshCounter();
  12310. continue;
  12311. }
  12312. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  12313. mesh._activate(scene.getRenderId());
  12314. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  12315. var subMesh = mesh.subMeshes[subIndex];
  12316. scene._activeVertices += subMesh.indexCount;
  12317. this._renderingManager.dispatch(subMesh);
  12318. }
  12319. }
  12320. }
  12321. }
  12322. if (this.onBeforeRender) {
  12323. this.onBeforeRender();
  12324. }
  12325. // Clear
  12326. engine.clear(scene.clearColor, true, true);
  12327. if (!this._doNotChangeAspectRatio) {
  12328. scene.updateTransformMatrix(true);
  12329. }
  12330. // Render
  12331. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  12332. if (useCameraPostProcess) {
  12333. scene.postProcessManager._finalizeFrame(false, this._texture);
  12334. }
  12335. if (!this._doNotChangeAspectRatio) {
  12336. scene.updateTransformMatrix(true);
  12337. }
  12338. if (this.onAfterRender) {
  12339. this.onAfterRender();
  12340. }
  12341. // Dump ?
  12342. if (dumpForDebug) {
  12343. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  12344. }
  12345. // Unbind
  12346. engine.unBindFramebuffer(this._texture);
  12347. };
  12348. RenderTargetTexture.prototype.clone = function () {
  12349. var textureSize = this.getSize();
  12350. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  12351. // Base texture
  12352. newTexture.hasAlpha = this.hasAlpha;
  12353. newTexture.level = this.level;
  12354. // RenderTarget Texture
  12355. newTexture.coordinatesMode = this.coordinatesMode;
  12356. newTexture.renderList = this.renderList.slice(0);
  12357. return newTexture;
  12358. };
  12359. return RenderTargetTexture;
  12360. })(BABYLON.Texture);
  12361. BABYLON.RenderTargetTexture = RenderTargetTexture;
  12362. })(BABYLON || (BABYLON = {}));
  12363. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  12364. var BABYLON;
  12365. (function (BABYLON) {
  12366. var ProceduralTexture = (function (_super) {
  12367. __extends(ProceduralTexture, _super);
  12368. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps) {
  12369. if (generateMipMaps === void 0) { generateMipMaps = true; }
  12370. _super.call(this, null, scene, !generateMipMaps);
  12371. this._currentRefreshId = -1;
  12372. this._refreshRate = 1;
  12373. this._vertexDeclaration = [2];
  12374. this._vertexStrideSize = 2 * 4;
  12375. this._uniforms = new Array();
  12376. this._samplers = new Array();
  12377. this._textures = new Array();
  12378. this._floats = new Array();
  12379. this._floatsArrays = {};
  12380. this._colors3 = new Array();
  12381. this._colors4 = new Array();
  12382. this._vectors2 = new Array();
  12383. this._vectors3 = new Array();
  12384. this._matrices = new Array();
  12385. this._fallbackTextureUsed = false;
  12386. scene._proceduralTextures.push(this);
  12387. this.name = name;
  12388. this.isRenderTarget = true;
  12389. this._size = size;
  12390. this._generateMipMaps = generateMipMaps;
  12391. this.setFragment(fragment);
  12392. this._fallbackTexture = fallbackTexture;
  12393. this._texture = scene.getEngine().createRenderTargetTexture(size, generateMipMaps);
  12394. // VBO
  12395. var vertices = [];
  12396. vertices.push(1, 1);
  12397. vertices.push(-1, 1);
  12398. vertices.push(-1, -1);
  12399. vertices.push(1, -1);
  12400. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  12401. // Indices
  12402. var indices = [];
  12403. indices.push(0);
  12404. indices.push(1);
  12405. indices.push(2);
  12406. indices.push(0);
  12407. indices.push(2);
  12408. indices.push(3);
  12409. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  12410. }
  12411. ProceduralTexture.prototype.reset = function () {
  12412. if (this._effect === undefined) {
  12413. return;
  12414. }
  12415. var engine = this.getScene().getEngine();
  12416. engine._releaseEffect(this._effect);
  12417. };
  12418. ProceduralTexture.prototype.isReady = function () {
  12419. var _this = this;
  12420. var engine = this.getScene().getEngine();
  12421. var shaders;
  12422. if (!this._fragment) {
  12423. return false;
  12424. }
  12425. if (this._fallbackTextureUsed) {
  12426. return true;
  12427. }
  12428. if (this._fragment.fragmentElement !== undefined) {
  12429. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  12430. }
  12431. else {
  12432. shaders = { vertex: "procedural", fragment: this._fragment };
  12433. }
  12434. this._effect = engine.createEffect(shaders, ["position"], this._uniforms, this._samplers, "", null, null, function () {
  12435. _this.releaseInternalTexture();
  12436. if (_this._fallbackTexture) {
  12437. _this._texture = _this._fallbackTexture._texture;
  12438. _this._texture.references++;
  12439. }
  12440. _this._fallbackTextureUsed = true;
  12441. });
  12442. return this._effect.isReady();
  12443. };
  12444. ProceduralTexture.prototype.resetRefreshCounter = function () {
  12445. this._currentRefreshId = -1;
  12446. };
  12447. ProceduralTexture.prototype.setFragment = function (fragment) {
  12448. this._fragment = fragment;
  12449. };
  12450. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  12451. get: function () {
  12452. return this._refreshRate;
  12453. },
  12454. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  12455. set: function (value) {
  12456. this._refreshRate = value;
  12457. this.resetRefreshCounter();
  12458. },
  12459. enumerable: true,
  12460. configurable: true
  12461. });
  12462. ProceduralTexture.prototype._shouldRender = function () {
  12463. if (!this.isReady() || !this._texture) {
  12464. return false;
  12465. }
  12466. if (this._fallbackTextureUsed) {
  12467. return false;
  12468. }
  12469. if (this._currentRefreshId === -1) {
  12470. this._currentRefreshId = 1;
  12471. return true;
  12472. }
  12473. if (this.refreshRate === this._currentRefreshId) {
  12474. this._currentRefreshId = 1;
  12475. return true;
  12476. }
  12477. this._currentRefreshId++;
  12478. return false;
  12479. };
  12480. ProceduralTexture.prototype.getRenderSize = function () {
  12481. return this._size;
  12482. };
  12483. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  12484. if (this._fallbackTextureUsed) {
  12485. return;
  12486. }
  12487. this.releaseInternalTexture();
  12488. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  12489. };
  12490. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  12491. if (this._uniforms.indexOf(uniformName) === -1) {
  12492. this._uniforms.push(uniformName);
  12493. }
  12494. };
  12495. ProceduralTexture.prototype.setTexture = function (name, texture) {
  12496. if (this._samplers.indexOf(name) === -1) {
  12497. this._samplers.push(name);
  12498. }
  12499. this._textures[name] = texture;
  12500. return this;
  12501. };
  12502. ProceduralTexture.prototype.setFloat = function (name, value) {
  12503. this._checkUniform(name);
  12504. this._floats[name] = value;
  12505. return this;
  12506. };
  12507. ProceduralTexture.prototype.setFloats = function (name, value) {
  12508. this._checkUniform(name);
  12509. this._floatsArrays[name] = value;
  12510. return this;
  12511. };
  12512. ProceduralTexture.prototype.setColor3 = function (name, value) {
  12513. this._checkUniform(name);
  12514. this._colors3[name] = value;
  12515. return this;
  12516. };
  12517. ProceduralTexture.prototype.setColor4 = function (name, value) {
  12518. this._checkUniform(name);
  12519. this._colors4[name] = value;
  12520. return this;
  12521. };
  12522. ProceduralTexture.prototype.setVector2 = function (name, value) {
  12523. this._checkUniform(name);
  12524. this._vectors2[name] = value;
  12525. return this;
  12526. };
  12527. ProceduralTexture.prototype.setVector3 = function (name, value) {
  12528. this._checkUniform(name);
  12529. this._vectors3[name] = value;
  12530. return this;
  12531. };
  12532. ProceduralTexture.prototype.setMatrix = function (name, value) {
  12533. this._checkUniform(name);
  12534. this._matrices[name] = value;
  12535. return this;
  12536. };
  12537. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12538. var scene = this.getScene();
  12539. var engine = scene.getEngine();
  12540. engine.bindFramebuffer(this._texture);
  12541. // Clear
  12542. engine.clear(scene.clearColor, true, true);
  12543. // Render
  12544. engine.enableEffect(this._effect);
  12545. engine.setState(false);
  12546. for (var name in this._textures) {
  12547. this._effect.setTexture(name, this._textures[name]);
  12548. }
  12549. for (name in this._floats) {
  12550. this._effect.setFloat(name, this._floats[name]);
  12551. }
  12552. for (name in this._floatsArrays) {
  12553. this._effect.setArray(name, this._floatsArrays[name]);
  12554. }
  12555. for (name in this._colors3) {
  12556. this._effect.setColor3(name, this._colors3[name]);
  12557. }
  12558. for (name in this._colors4) {
  12559. var color = this._colors4[name];
  12560. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  12561. }
  12562. for (name in this._vectors2) {
  12563. this._effect.setVector2(name, this._vectors2[name]);
  12564. }
  12565. for (name in this._vectors3) {
  12566. this._effect.setVector3(name, this._vectors3[name]);
  12567. }
  12568. for (name in this._matrices) {
  12569. this._effect.setMatrix(name, this._matrices[name]);
  12570. }
  12571. // VBOs
  12572. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  12573. // Draw order
  12574. engine.draw(true, 0, 6);
  12575. // Unbind
  12576. engine.unBindFramebuffer(this._texture);
  12577. };
  12578. ProceduralTexture.prototype.clone = function () {
  12579. var textureSize = this.getSize();
  12580. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  12581. // Base texture
  12582. newTexture.hasAlpha = this.hasAlpha;
  12583. newTexture.level = this.level;
  12584. // RenderTarget Texture
  12585. newTexture.coordinatesMode = this.coordinatesMode;
  12586. return newTexture;
  12587. };
  12588. ProceduralTexture.prototype.dispose = function () {
  12589. var index = this.getScene()._proceduralTextures.indexOf(this);
  12590. if (index >= 0) {
  12591. this.getScene()._proceduralTextures.splice(index, 1);
  12592. }
  12593. _super.prototype.dispose.call(this);
  12594. };
  12595. return ProceduralTexture;
  12596. })(BABYLON.Texture);
  12597. BABYLON.ProceduralTexture = ProceduralTexture;
  12598. })(BABYLON || (BABYLON = {}));
  12599. //# sourceMappingURL=babylon.proceduralTexture.js.map
  12600. var BABYLON;
  12601. (function (BABYLON) {
  12602. var WoodProceduralTexture = (function (_super) {
  12603. __extends(WoodProceduralTexture, _super);
  12604. function WoodProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12605. _super.call(this, name, size, "wood", scene, fallbackTexture, generateMipMaps);
  12606. this._ampScale = 100.0;
  12607. this._woodColor = new BABYLON.Color3(0.32, 0.17, 0.09);
  12608. this.updateShaderUniforms();
  12609. this.refreshRate = 0;
  12610. }
  12611. WoodProceduralTexture.prototype.updateShaderUniforms = function () {
  12612. this.setFloat("ampScale", this._ampScale);
  12613. this.setColor3("woodColor", this._woodColor);
  12614. };
  12615. Object.defineProperty(WoodProceduralTexture.prototype, "ampScale", {
  12616. get: function () {
  12617. return this._ampScale;
  12618. },
  12619. set: function (value) {
  12620. this._ampScale = value;
  12621. this.updateShaderUniforms();
  12622. },
  12623. enumerable: true,
  12624. configurable: true
  12625. });
  12626. Object.defineProperty(WoodProceduralTexture.prototype, "woodColor", {
  12627. get: function () {
  12628. return this._woodColor;
  12629. },
  12630. set: function (value) {
  12631. this._woodColor = value;
  12632. this.updateShaderUniforms();
  12633. },
  12634. enumerable: true,
  12635. configurable: true
  12636. });
  12637. return WoodProceduralTexture;
  12638. })(BABYLON.ProceduralTexture);
  12639. BABYLON.WoodProceduralTexture = WoodProceduralTexture;
  12640. var FireProceduralTexture = (function (_super) {
  12641. __extends(FireProceduralTexture, _super);
  12642. function FireProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12643. _super.call(this, name, size, "fire", scene, fallbackTexture, generateMipMaps);
  12644. this._time = 0.0;
  12645. this._speed = new BABYLON.Vector2(0.5, 0.3);
  12646. this._shift = 1.6;
  12647. this._autoGenerateTime = true;
  12648. this._alphaThreshold = 0.5;
  12649. this._fireColors = FireProceduralTexture.RedFireColors;
  12650. this.updateShaderUniforms();
  12651. this.refreshRate = 1;
  12652. }
  12653. FireProceduralTexture.prototype.updateShaderUniforms = function () {
  12654. this.setFloat("time", this._time);
  12655. this.setVector2("speed", this._speed);
  12656. this.setFloat("shift", this._shift);
  12657. this.setColor3("c1", this._fireColors[0]);
  12658. this.setColor3("c2", this._fireColors[1]);
  12659. this.setColor3("c3", this._fireColors[2]);
  12660. this.setColor3("c4", this._fireColors[3]);
  12661. this.setColor3("c5", this._fireColors[4]);
  12662. this.setColor3("c6", this._fireColors[5]);
  12663. this.setFloat("alphaThreshold", this._alphaThreshold);
  12664. };
  12665. FireProceduralTexture.prototype.render = function (useCameraPostProcess) {
  12666. if (this._autoGenerateTime) {
  12667. this._time += this.getScene().getAnimationRatio() * 0.03;
  12668. this.updateShaderUniforms();
  12669. }
  12670. _super.prototype.render.call(this, useCameraPostProcess);
  12671. };
  12672. Object.defineProperty(FireProceduralTexture, "PurpleFireColors", {
  12673. get: function () {
  12674. return [
  12675. new BABYLON.Color3(0.5, 0.0, 1.0),
  12676. new BABYLON.Color3(0.9, 0.0, 1.0),
  12677. new BABYLON.Color3(0.2, 0.0, 1.0),
  12678. new BABYLON.Color3(1.0, 0.9, 1.0),
  12679. new BABYLON.Color3(0.1, 0.1, 1.0),
  12680. new BABYLON.Color3(0.9, 0.9, 1.0)
  12681. ];
  12682. },
  12683. enumerable: true,
  12684. configurable: true
  12685. });
  12686. Object.defineProperty(FireProceduralTexture, "GreenFireColors", {
  12687. get: function () {
  12688. return [
  12689. new BABYLON.Color3(0.5, 1.0, 0.0),
  12690. new BABYLON.Color3(0.5, 1.0, 0.0),
  12691. new BABYLON.Color3(0.3, 0.4, 0.0),
  12692. new BABYLON.Color3(0.5, 1.0, 0.0),
  12693. new BABYLON.Color3(0.2, 0.0, 0.0),
  12694. new BABYLON.Color3(0.5, 1.0, 0.0)
  12695. ];
  12696. },
  12697. enumerable: true,
  12698. configurable: true
  12699. });
  12700. Object.defineProperty(FireProceduralTexture, "RedFireColors", {
  12701. get: function () {
  12702. return [
  12703. new BABYLON.Color3(0.5, 0.0, 0.1),
  12704. new BABYLON.Color3(0.9, 0.0, 0.0),
  12705. new BABYLON.Color3(0.2, 0.0, 0.0),
  12706. new BABYLON.Color3(1.0, 0.9, 0.0),
  12707. new BABYLON.Color3(0.1, 0.1, 0.1),
  12708. new BABYLON.Color3(0.9, 0.9, 0.9)
  12709. ];
  12710. },
  12711. enumerable: true,
  12712. configurable: true
  12713. });
  12714. Object.defineProperty(FireProceduralTexture, "BlueFireColors", {
  12715. get: function () {
  12716. return [
  12717. new BABYLON.Color3(0.1, 0.0, 0.5),
  12718. new BABYLON.Color3(0.0, 0.0, 0.5),
  12719. new BABYLON.Color3(0.1, 0.0, 0.2),
  12720. new BABYLON.Color3(0.0, 0.0, 1.0),
  12721. new BABYLON.Color3(0.1, 0.2, 0.3),
  12722. new BABYLON.Color3(0.0, 0.2, 0.9)
  12723. ];
  12724. },
  12725. enumerable: true,
  12726. configurable: true
  12727. });
  12728. Object.defineProperty(FireProceduralTexture.prototype, "fireColors", {
  12729. get: function () {
  12730. return this._fireColors;
  12731. },
  12732. set: function (value) {
  12733. this._fireColors = value;
  12734. this.updateShaderUniforms();
  12735. },
  12736. enumerable: true,
  12737. configurable: true
  12738. });
  12739. Object.defineProperty(FireProceduralTexture.prototype, "time", {
  12740. get: function () {
  12741. return this._time;
  12742. },
  12743. set: function (value) {
  12744. this._time = value;
  12745. this.updateShaderUniforms();
  12746. },
  12747. enumerable: true,
  12748. configurable: true
  12749. });
  12750. Object.defineProperty(FireProceduralTexture.prototype, "speed", {
  12751. get: function () {
  12752. return this._speed;
  12753. },
  12754. set: function (value) {
  12755. this._speed = value;
  12756. this.updateShaderUniforms();
  12757. },
  12758. enumerable: true,
  12759. configurable: true
  12760. });
  12761. Object.defineProperty(FireProceduralTexture.prototype, "shift", {
  12762. get: function () {
  12763. return this._shift;
  12764. },
  12765. set: function (value) {
  12766. this._shift = value;
  12767. this.updateShaderUniforms();
  12768. },
  12769. enumerable: true,
  12770. configurable: true
  12771. });
  12772. Object.defineProperty(FireProceduralTexture.prototype, "alphaThreshold", {
  12773. get: function () {
  12774. return this._alphaThreshold;
  12775. },
  12776. set: function (value) {
  12777. this._alphaThreshold = value;
  12778. this.updateShaderUniforms();
  12779. },
  12780. enumerable: true,
  12781. configurable: true
  12782. });
  12783. return FireProceduralTexture;
  12784. })(BABYLON.ProceduralTexture);
  12785. BABYLON.FireProceduralTexture = FireProceduralTexture;
  12786. var CloudProceduralTexture = (function (_super) {
  12787. __extends(CloudProceduralTexture, _super);
  12788. function CloudProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12789. _super.call(this, name, size, "cloud", scene, fallbackTexture, generateMipMaps);
  12790. this._skyColor = new BABYLON.Color3(0.15, 0.68, 1.0);
  12791. this._cloudColor = new BABYLON.Color3(1, 1, 1);
  12792. this.updateShaderUniforms();
  12793. this.refreshRate = 0;
  12794. }
  12795. CloudProceduralTexture.prototype.updateShaderUniforms = function () {
  12796. this.setColor3("skyColor", this._skyColor);
  12797. this.setColor3("cloudColor", this._cloudColor);
  12798. };
  12799. Object.defineProperty(CloudProceduralTexture.prototype, "skyColor", {
  12800. get: function () {
  12801. return this._skyColor;
  12802. },
  12803. set: function (value) {
  12804. this._skyColor = value;
  12805. this.updateShaderUniforms();
  12806. },
  12807. enumerable: true,
  12808. configurable: true
  12809. });
  12810. Object.defineProperty(CloudProceduralTexture.prototype, "cloudColor", {
  12811. get: function () {
  12812. return this._cloudColor;
  12813. },
  12814. set: function (value) {
  12815. this._cloudColor = value;
  12816. this.updateShaderUniforms();
  12817. },
  12818. enumerable: true,
  12819. configurable: true
  12820. });
  12821. return CloudProceduralTexture;
  12822. })(BABYLON.ProceduralTexture);
  12823. BABYLON.CloudProceduralTexture = CloudProceduralTexture;
  12824. var GrassProceduralTexture = (function (_super) {
  12825. __extends(GrassProceduralTexture, _super);
  12826. function GrassProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12827. _super.call(this, name, size, "grass", scene, fallbackTexture, generateMipMaps);
  12828. this._herb1 = new BABYLON.Color3(0.29, 0.38, 0.02);
  12829. this._herb2 = new BABYLON.Color3(0.36, 0.49, 0.09);
  12830. this._herb3 = new BABYLON.Color3(0.51, 0.6, 0.28);
  12831. this._groundColor = new BABYLON.Color3(1, 1, 1);
  12832. this._grassColors = [
  12833. new BABYLON.Color3(0.29, 0.38, 0.02),
  12834. new BABYLON.Color3(0.36, 0.49, 0.09),
  12835. new BABYLON.Color3(0.51, 0.6, 0.28)
  12836. ];
  12837. this.updateShaderUniforms();
  12838. this.refreshRate = 0;
  12839. }
  12840. GrassProceduralTexture.prototype.updateShaderUniforms = function () {
  12841. this.setColor3("herb1Color", this._grassColors[0]);
  12842. this.setColor3("herb2Color", this._grassColors[1]);
  12843. this.setColor3("herb3Color", this._grassColors[2]);
  12844. this.setColor3("groundColor", this._groundColor);
  12845. };
  12846. Object.defineProperty(GrassProceduralTexture.prototype, "grassColors", {
  12847. get: function () {
  12848. return this._grassColors;
  12849. },
  12850. set: function (value) {
  12851. this._grassColors = value;
  12852. this.updateShaderUniforms();
  12853. },
  12854. enumerable: true,
  12855. configurable: true
  12856. });
  12857. Object.defineProperty(GrassProceduralTexture.prototype, "groundColor", {
  12858. get: function () {
  12859. return this._groundColor;
  12860. },
  12861. set: function (value) {
  12862. this.groundColor = value;
  12863. this.updateShaderUniforms();
  12864. },
  12865. enumerable: true,
  12866. configurable: true
  12867. });
  12868. return GrassProceduralTexture;
  12869. })(BABYLON.ProceduralTexture);
  12870. BABYLON.GrassProceduralTexture = GrassProceduralTexture;
  12871. var RoadProceduralTexture = (function (_super) {
  12872. __extends(RoadProceduralTexture, _super);
  12873. function RoadProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12874. _super.call(this, name, size, "road", scene, fallbackTexture, generateMipMaps);
  12875. this._roadColor = new BABYLON.Color3(0.53, 0.53, 0.53);
  12876. this.updateShaderUniforms();
  12877. this.refreshRate = 0;
  12878. }
  12879. RoadProceduralTexture.prototype.updateShaderUniforms = function () {
  12880. this.setColor3("roadColor", this._roadColor);
  12881. };
  12882. Object.defineProperty(RoadProceduralTexture.prototype, "roadColor", {
  12883. get: function () {
  12884. return this._roadColor;
  12885. },
  12886. set: function (value) {
  12887. this._roadColor = value;
  12888. this.updateShaderUniforms();
  12889. },
  12890. enumerable: true,
  12891. configurable: true
  12892. });
  12893. return RoadProceduralTexture;
  12894. })(BABYLON.ProceduralTexture);
  12895. BABYLON.RoadProceduralTexture = RoadProceduralTexture;
  12896. var BrickProceduralTexture = (function (_super) {
  12897. __extends(BrickProceduralTexture, _super);
  12898. function BrickProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12899. _super.call(this, name, size, "brick", scene, fallbackTexture, generateMipMaps);
  12900. this._numberOfBricksHeight = 15;
  12901. this._numberOfBricksWidth = 5;
  12902. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12903. this._brickColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12904. this.updateShaderUniforms();
  12905. this.refreshRate = 0;
  12906. }
  12907. BrickProceduralTexture.prototype.updateShaderUniforms = function () {
  12908. this.setFloat("numberOfBricksHeight", this._numberOfBricksHeight);
  12909. this.setFloat("numberOfBricksWidth", this._numberOfBricksWidth);
  12910. this.setColor3("brickColor", this._brickColor);
  12911. this.setColor3("jointColor", this._jointColor);
  12912. };
  12913. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksHeight", {
  12914. get: function () {
  12915. return this._numberOfBricksHeight;
  12916. },
  12917. enumerable: true,
  12918. configurable: true
  12919. });
  12920. Object.defineProperty(BrickProceduralTexture.prototype, "cloudColor", {
  12921. set: function (value) {
  12922. this._numberOfBricksHeight = value;
  12923. this.updateShaderUniforms();
  12924. },
  12925. enumerable: true,
  12926. configurable: true
  12927. });
  12928. Object.defineProperty(BrickProceduralTexture.prototype, "numberOfBricksWidth", {
  12929. get: function () {
  12930. return this._numberOfBricksWidth;
  12931. },
  12932. set: function (value) {
  12933. this._numberOfBricksHeight = value;
  12934. this.updateShaderUniforms();
  12935. },
  12936. enumerable: true,
  12937. configurable: true
  12938. });
  12939. Object.defineProperty(BrickProceduralTexture.prototype, "jointColor", {
  12940. get: function () {
  12941. return this._jointColor;
  12942. },
  12943. set: function (value) {
  12944. this._jointColor = value;
  12945. this.updateShaderUniforms();
  12946. },
  12947. enumerable: true,
  12948. configurable: true
  12949. });
  12950. Object.defineProperty(BrickProceduralTexture.prototype, "brickColor", {
  12951. get: function () {
  12952. return this._brickColor;
  12953. },
  12954. set: function (value) {
  12955. this._brickColor = value;
  12956. this.updateShaderUniforms();
  12957. },
  12958. enumerable: true,
  12959. configurable: true
  12960. });
  12961. return BrickProceduralTexture;
  12962. })(BABYLON.ProceduralTexture);
  12963. BABYLON.BrickProceduralTexture = BrickProceduralTexture;
  12964. var MarbleProceduralTexture = (function (_super) {
  12965. __extends(MarbleProceduralTexture, _super);
  12966. function MarbleProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  12967. _super.call(this, name, size, "marble", scene, fallbackTexture, generateMipMaps);
  12968. this._numberOfTilesHeight = 3;
  12969. this._numberOfTilesWidth = 3;
  12970. this._amplitude = 9.0;
  12971. this._marbleColor = new BABYLON.Color3(0.77, 0.47, 0.40);
  12972. this._jointColor = new BABYLON.Color3(0.72, 0.72, 0.72);
  12973. this.updateShaderUniforms();
  12974. this.refreshRate = 0;
  12975. }
  12976. MarbleProceduralTexture.prototype.updateShaderUniforms = function () {
  12977. this.setFloat("numberOfTilesHeight", this._numberOfTilesHeight);
  12978. this.setFloat("numberOfTilesWidth", this._numberOfTilesWidth);
  12979. this.setFloat("amplitude", this._amplitude);
  12980. this.setColor3("marbleColor", this._marbleColor);
  12981. this.setColor3("jointColor", this._jointColor);
  12982. };
  12983. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesHeight", {
  12984. get: function () {
  12985. return this._numberOfTilesHeight;
  12986. },
  12987. set: function (value) {
  12988. this._numberOfTilesHeight = value;
  12989. this.updateShaderUniforms();
  12990. },
  12991. enumerable: true,
  12992. configurable: true
  12993. });
  12994. Object.defineProperty(MarbleProceduralTexture.prototype, "numberOfTilesWidth", {
  12995. get: function () {
  12996. return this._numberOfTilesWidth;
  12997. },
  12998. set: function (value) {
  12999. this._numberOfTilesWidth = value;
  13000. this.updateShaderUniforms();
  13001. },
  13002. enumerable: true,
  13003. configurable: true
  13004. });
  13005. Object.defineProperty(MarbleProceduralTexture.prototype, "jointColor", {
  13006. get: function () {
  13007. return this._jointColor;
  13008. },
  13009. set: function (value) {
  13010. this._jointColor = value;
  13011. this.updateShaderUniforms();
  13012. },
  13013. enumerable: true,
  13014. configurable: true
  13015. });
  13016. Object.defineProperty(MarbleProceduralTexture.prototype, "marbleColor", {
  13017. get: function () {
  13018. return this._marbleColor;
  13019. },
  13020. set: function (value) {
  13021. this._marbleColor = value;
  13022. this.updateShaderUniforms();
  13023. },
  13024. enumerable: true,
  13025. configurable: true
  13026. });
  13027. return MarbleProceduralTexture;
  13028. })(BABYLON.ProceduralTexture);
  13029. BABYLON.MarbleProceduralTexture = MarbleProceduralTexture;
  13030. })(BABYLON || (BABYLON = {}));
  13031. //# sourceMappingURL=babylon.standardProceduralTexture.js.map
  13032. var BABYLON;
  13033. (function (BABYLON) {
  13034. var CustomProceduralTexture = (function (_super) {
  13035. __extends(CustomProceduralTexture, _super);
  13036. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  13037. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  13038. this._animate = true;
  13039. this._time = 0;
  13040. this._texturePath = texturePath;
  13041. //Try to load json
  13042. this.loadJson(texturePath);
  13043. this.refreshRate = 1;
  13044. }
  13045. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  13046. var _this = this;
  13047. var that = this;
  13048. function noConfigFile() {
  13049. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  13050. try {
  13051. that.setFragment(that._texturePath);
  13052. }
  13053. catch (ex) {
  13054. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  13055. }
  13056. }
  13057. var configFileUrl = jsonUrl + "/config.json";
  13058. var xhr = new XMLHttpRequest();
  13059. xhr.open("GET", configFileUrl, true);
  13060. xhr.addEventListener("load", function () {
  13061. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  13062. try {
  13063. _this._config = JSON.parse(xhr.response);
  13064. _this.updateShaderUniforms();
  13065. _this.updateTextures();
  13066. _this.setFragment(_this._texturePath + "/custom");
  13067. _this._animate = _this._config.animate;
  13068. _this.refreshRate = _this._config.refreshrate;
  13069. }
  13070. catch (ex) {
  13071. noConfigFile();
  13072. }
  13073. }
  13074. else {
  13075. noConfigFile();
  13076. }
  13077. }, false);
  13078. xhr.addEventListener("error", function () {
  13079. noConfigFile();
  13080. }, false);
  13081. try {
  13082. xhr.send();
  13083. }
  13084. catch (ex) {
  13085. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  13086. }
  13087. };
  13088. CustomProceduralTexture.prototype.isReady = function () {
  13089. if (!_super.prototype.isReady.call(this)) {
  13090. return false;
  13091. }
  13092. for (var name in this._textures) {
  13093. var texture = this._textures[name];
  13094. if (!texture.isReady()) {
  13095. return false;
  13096. }
  13097. }
  13098. return true;
  13099. };
  13100. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  13101. if (this._animate) {
  13102. this._time += this.getScene().getAnimationRatio() * 0.03;
  13103. this.updateShaderUniforms();
  13104. }
  13105. _super.prototype.render.call(this, useCameraPostProcess);
  13106. };
  13107. CustomProceduralTexture.prototype.updateTextures = function () {
  13108. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  13109. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  13110. }
  13111. };
  13112. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  13113. if (this._config) {
  13114. for (var j = 0; j < this._config.uniforms.length; j++) {
  13115. var uniform = this._config.uniforms[j];
  13116. switch (uniform.type) {
  13117. case "float":
  13118. this.setFloat(uniform.name, uniform.value);
  13119. break;
  13120. case "color3":
  13121. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  13122. break;
  13123. case "color4":
  13124. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  13125. break;
  13126. case "vector2":
  13127. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  13128. break;
  13129. case "vector3":
  13130. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  13131. break;
  13132. }
  13133. }
  13134. }
  13135. this.setFloat("time", this._time);
  13136. };
  13137. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  13138. get: function () {
  13139. return this._animate;
  13140. },
  13141. set: function (value) {
  13142. this._animate = value;
  13143. },
  13144. enumerable: true,
  13145. configurable: true
  13146. });
  13147. return CustomProceduralTexture;
  13148. })(BABYLON.ProceduralTexture);
  13149. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  13150. })(BABYLON || (BABYLON = {}));
  13151. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  13152. var BABYLON;
  13153. (function (BABYLON) {
  13154. var MirrorTexture = (function (_super) {
  13155. __extends(MirrorTexture, _super);
  13156. function MirrorTexture(name, size, scene, generateMipMaps) {
  13157. var _this = this;
  13158. _super.call(this, name, size, scene, generateMipMaps, true);
  13159. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  13160. this._transformMatrix = BABYLON.Matrix.Zero();
  13161. this._mirrorMatrix = BABYLON.Matrix.Zero();
  13162. this.onBeforeRender = function () {
  13163. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  13164. _this._savedViewMatrix = scene.getViewMatrix();
  13165. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  13166. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  13167. scene.clipPlane = _this.mirrorPlane;
  13168. scene.getEngine().cullBackFaces = false;
  13169. };
  13170. this.onAfterRender = function () {
  13171. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  13172. scene.getEngine().cullBackFaces = true;
  13173. delete scene.clipPlane;
  13174. };
  13175. }
  13176. MirrorTexture.prototype.clone = function () {
  13177. var textureSize = this.getSize();
  13178. var newTexture = new BABYLON.MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13179. // Base texture
  13180. newTexture.hasAlpha = this.hasAlpha;
  13181. newTexture.level = this.level;
  13182. // Mirror Texture
  13183. newTexture.mirrorPlane = this.mirrorPlane.clone();
  13184. newTexture.renderList = this.renderList.slice(0);
  13185. return newTexture;
  13186. };
  13187. return MirrorTexture;
  13188. })(BABYLON.RenderTargetTexture);
  13189. BABYLON.MirrorTexture = MirrorTexture;
  13190. })(BABYLON || (BABYLON = {}));
  13191. //# sourceMappingURL=babylon.mirrorTexture.js.map
  13192. var BABYLON;
  13193. (function (BABYLON) {
  13194. var DynamicTexture = (function (_super) {
  13195. __extends(DynamicTexture, _super);
  13196. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  13197. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13198. _super.call(this, null, scene, !generateMipMaps);
  13199. this.name = name;
  13200. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13201. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  13202. this._generateMipMaps = generateMipMaps;
  13203. if (options.getContext) {
  13204. this._canvas = options;
  13205. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13206. }
  13207. else {
  13208. this._canvas = document.createElement("canvas");
  13209. if (options.width) {
  13210. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  13211. }
  13212. else {
  13213. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  13214. }
  13215. }
  13216. var textureSize = this.getSize();
  13217. this._canvas.width = textureSize.width;
  13218. this._canvas.height = textureSize.height;
  13219. this._context = this._canvas.getContext("2d");
  13220. }
  13221. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  13222. get: function () {
  13223. return true;
  13224. },
  13225. enumerable: true,
  13226. configurable: true
  13227. });
  13228. DynamicTexture.prototype.scale = function (ratio) {
  13229. var textureSize = this.getSize();
  13230. textureSize.width *= ratio;
  13231. textureSize.height *= ratio;
  13232. this._canvas.width = textureSize.width;
  13233. this._canvas.height = textureSize.height;
  13234. this.releaseInternalTexture();
  13235. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  13236. };
  13237. DynamicTexture.prototype.getContext = function () {
  13238. return this._context;
  13239. };
  13240. DynamicTexture.prototype.clear = function () {
  13241. var size = this.getSize();
  13242. this._context.fillRect(0, 0, size.width, size.height);
  13243. };
  13244. DynamicTexture.prototype.update = function (invertY) {
  13245. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  13246. };
  13247. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  13248. if (update === void 0) { update = true; }
  13249. var size = this.getSize();
  13250. if (clearColor) {
  13251. this._context.fillStyle = clearColor;
  13252. this._context.fillRect(0, 0, size.width, size.height);
  13253. }
  13254. this._context.font = font;
  13255. if (x === null) {
  13256. var textSize = this._context.measureText(text);
  13257. x = (size.width - textSize.width) / 2;
  13258. }
  13259. this._context.fillStyle = color;
  13260. this._context.fillText(text, x, y);
  13261. if (update) {
  13262. this.update(invertY);
  13263. }
  13264. };
  13265. DynamicTexture.prototype.clone = function () {
  13266. var textureSize = this.getSize();
  13267. var newTexture = new DynamicTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  13268. // Base texture
  13269. newTexture.hasAlpha = this.hasAlpha;
  13270. newTexture.level = this.level;
  13271. // Dynamic Texture
  13272. newTexture.wrapU = this.wrapU;
  13273. newTexture.wrapV = this.wrapV;
  13274. return newTexture;
  13275. };
  13276. return DynamicTexture;
  13277. })(BABYLON.Texture);
  13278. BABYLON.DynamicTexture = DynamicTexture;
  13279. })(BABYLON || (BABYLON = {}));
  13280. //# sourceMappingURL=babylon.dynamicTexture.js.map
  13281. var BABYLON;
  13282. (function (BABYLON) {
  13283. var VideoTexture = (function (_super) {
  13284. __extends(VideoTexture, _super);
  13285. function VideoTexture(name, urls, size, scene, generateMipMaps, invertY, samplingMode) {
  13286. var _this = this;
  13287. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13288. _super.call(this, null, scene, !generateMipMaps, invertY);
  13289. this._autoLaunch = true;
  13290. this.name = name;
  13291. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  13292. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  13293. var requiredWidth = size.width || size;
  13294. var requiredHeight = size.height || size;
  13295. this._texture = scene.getEngine().createDynamicTexture(requiredWidth, requiredHeight, generateMipMaps, samplingMode);
  13296. var textureSize = this.getSize();
  13297. this.video = document.createElement("video");
  13298. this.video.width = textureSize.width;
  13299. this.video.height = textureSize.height;
  13300. this.video.autoplay = false;
  13301. this.video.loop = true;
  13302. this.video.addEventListener("canplaythrough", function () {
  13303. if (_this._texture) {
  13304. _this._texture.isReady = true;
  13305. }
  13306. });
  13307. urls.forEach(function (url) {
  13308. //Backwards-compatibility for typescript 1. from 1.3 it should say "SOURCE". see here - https://github.com/Microsoft/TypeScript/issues/1850
  13309. var source = document.createElement("source");
  13310. source.src = url;
  13311. _this.video.appendChild(source);
  13312. });
  13313. this._lastUpdate = BABYLON.Tools.Now;
  13314. }
  13315. VideoTexture.prototype.update = function () {
  13316. if (this._autoLaunch) {
  13317. this._autoLaunch = false;
  13318. this.video.play();
  13319. }
  13320. var now = BABYLON.Tools.Now;
  13321. if (now - this._lastUpdate < 15) {
  13322. return false;
  13323. }
  13324. this._lastUpdate = now;
  13325. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  13326. return true;
  13327. };
  13328. return VideoTexture;
  13329. })(BABYLON.Texture);
  13330. BABYLON.VideoTexture = VideoTexture;
  13331. })(BABYLON || (BABYLON = {}));
  13332. //# sourceMappingURL=babylon.videoTexture.js.mapvar BABYLON;
  13333. (function (BABYLON) {
  13334. var EffectFallbacks = (function () {
  13335. function EffectFallbacks() {
  13336. this._defines = {};
  13337. this._currentRank = 32;
  13338. this._maxRank = -1;
  13339. }
  13340. EffectFallbacks.prototype.addFallback = function (rank, define) {
  13341. if (!this._defines[rank]) {
  13342. if (rank < this._currentRank) {
  13343. this._currentRank = rank;
  13344. }
  13345. if (rank > this._maxRank) {
  13346. this._maxRank = rank;
  13347. }
  13348. this._defines[rank] = new Array();
  13349. }
  13350. this._defines[rank].push(define);
  13351. };
  13352. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  13353. get: function () {
  13354. return this._currentRank <= this._maxRank;
  13355. },
  13356. enumerable: true,
  13357. configurable: true
  13358. });
  13359. EffectFallbacks.prototype.reduce = function (currentDefines) {
  13360. var currentFallbacks = this._defines[this._currentRank];
  13361. for (var index = 0; index < currentFallbacks.length; index++) {
  13362. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  13363. }
  13364. this._currentRank++;
  13365. return currentDefines;
  13366. };
  13367. return EffectFallbacks;
  13368. })();
  13369. BABYLON.EffectFallbacks = EffectFallbacks;
  13370. var Effect = (function () {
  13371. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError) {
  13372. var _this = this;
  13373. this._isReady = false;
  13374. this._compilationError = "";
  13375. this._valueCache = [];
  13376. this._engine = engine;
  13377. this.name = baseName;
  13378. this.defines = defines;
  13379. this._uniformsNames = uniformsNames.concat(samplers);
  13380. this._samplers = samplers;
  13381. this._attributesNames = attributesNames;
  13382. this.onError = onError;
  13383. this.onCompiled = onCompiled;
  13384. var vertexSource;
  13385. var fragmentSource;
  13386. if (baseName.vertexElement) {
  13387. vertexSource = document.getElementById(baseName.vertexElement);
  13388. if (!vertexSource) {
  13389. vertexSource = baseName.vertexElement;
  13390. }
  13391. }
  13392. else {
  13393. vertexSource = baseName.vertex || baseName;
  13394. }
  13395. if (baseName.fragmentElement) {
  13396. fragmentSource = document.getElementById(baseName.fragmentElement);
  13397. if (!fragmentSource) {
  13398. fragmentSource = baseName.fragmentElement;
  13399. }
  13400. }
  13401. else {
  13402. fragmentSource = baseName.fragment || baseName;
  13403. }
  13404. this._loadVertexShader(vertexSource, function (vertexCode) {
  13405. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  13406. _this._prepareEffect(vertexCode, fragmentCode, attributesNames, defines, fallbacks);
  13407. });
  13408. });
  13409. }
  13410. // Properties
  13411. Effect.prototype.isReady = function () {
  13412. return this._isReady;
  13413. };
  13414. Effect.prototype.getProgram = function () {
  13415. return this._program;
  13416. };
  13417. Effect.prototype.getAttributesNames = function () {
  13418. return this._attributesNames;
  13419. };
  13420. Effect.prototype.getAttributeLocation = function (index) {
  13421. return this._attributes[index];
  13422. };
  13423. Effect.prototype.getAttributeLocationByName = function (name) {
  13424. var index = this._attributesNames.indexOf(name);
  13425. return this._attributes[index];
  13426. };
  13427. Effect.prototype.getAttributesCount = function () {
  13428. return this._attributes.length;
  13429. };
  13430. Effect.prototype.getUniformIndex = function (uniformName) {
  13431. return this._uniformsNames.indexOf(uniformName);
  13432. };
  13433. Effect.prototype.getUniform = function (uniformName) {
  13434. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  13435. };
  13436. Effect.prototype.getSamplers = function () {
  13437. return this._samplers;
  13438. };
  13439. Effect.prototype.getCompilationError = function () {
  13440. return this._compilationError;
  13441. };
  13442. // Methods
  13443. Effect.prototype._loadVertexShader = function (vertex, callback) {
  13444. // DOM element ?
  13445. if (vertex instanceof HTMLElement) {
  13446. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  13447. callback(vertexCode);
  13448. return;
  13449. }
  13450. // Is in local store ?
  13451. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  13452. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  13453. return;
  13454. }
  13455. var vertexShaderUrl;
  13456. if (vertex[0] === ".") {
  13457. vertexShaderUrl = vertex;
  13458. }
  13459. else {
  13460. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  13461. }
  13462. // Vertex shader
  13463. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  13464. };
  13465. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  13466. // DOM element ?
  13467. if (fragment instanceof HTMLElement) {
  13468. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  13469. callback(fragmentCode);
  13470. return;
  13471. }
  13472. // Is in local store ?
  13473. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  13474. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  13475. return;
  13476. }
  13477. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  13478. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  13479. return;
  13480. }
  13481. var fragmentShaderUrl;
  13482. if (fragment[0] === ".") {
  13483. fragmentShaderUrl = fragment;
  13484. }
  13485. else {
  13486. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  13487. }
  13488. // Fragment shader
  13489. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  13490. };
  13491. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  13492. try {
  13493. var engine = this._engine;
  13494. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  13495. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  13496. this._attributes = engine.getAttributes(this._program, attributesNames);
  13497. for (var index = 0; index < this._samplers.length; index++) {
  13498. var sampler = this.getUniform(this._samplers[index]);
  13499. if (sampler == null) {
  13500. this._samplers.splice(index, 1);
  13501. index--;
  13502. }
  13503. }
  13504. engine.bindSamplers(this);
  13505. this._isReady = true;
  13506. if (this.onCompiled) {
  13507. this.onCompiled(this);
  13508. }
  13509. }
  13510. catch (e) {
  13511. // Is it a problem with precision?
  13512. if (e.message.indexOf("highp") !== -1) {
  13513. vertexSourceCode = vertexSourceCode.replace("precision highp float", "precision mediump float");
  13514. fragmentSourceCode = fragmentSourceCode.replace("precision highp float", "precision mediump float");
  13515. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13516. return;
  13517. }
  13518. // Let's go through fallbacks then
  13519. if (fallbacks && fallbacks.isMoreFallbacks) {
  13520. defines = fallbacks.reduce(defines);
  13521. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  13522. }
  13523. else {
  13524. BABYLON.Tools.Error("Unable to compile effect: " + this.name);
  13525. BABYLON.Tools.Error("Defines: " + defines);
  13526. BABYLON.Tools.Error("Error: " + e.message);
  13527. this._compilationError = e.message;
  13528. if (this.onError) {
  13529. this.onError(this, this._compilationError);
  13530. }
  13531. }
  13532. }
  13533. };
  13534. Effect.prototype._bindTexture = function (channel, texture) {
  13535. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  13536. };
  13537. Effect.prototype.setTexture = function (channel, texture) {
  13538. this._engine.setTexture(this._samplers.indexOf(channel), texture);
  13539. };
  13540. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  13541. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  13542. };
  13543. //public _cacheMatrix(uniformName, matrix) {
  13544. // if (!this._valueCache[uniformName]) {
  13545. // this._valueCache[uniformName] = new BABYLON.Matrix();
  13546. // }
  13547. // for (var index = 0; index < 16; index++) {
  13548. // this._valueCache[uniformName].m[index] = matrix.m[index];
  13549. // }
  13550. //};
  13551. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  13552. if (!this._valueCache[uniformName]) {
  13553. this._valueCache[uniformName] = [x, y];
  13554. return;
  13555. }
  13556. this._valueCache[uniformName][0] = x;
  13557. this._valueCache[uniformName][1] = y;
  13558. };
  13559. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  13560. if (!this._valueCache[uniformName]) {
  13561. this._valueCache[uniformName] = [x, y, z];
  13562. return;
  13563. }
  13564. this._valueCache[uniformName][0] = x;
  13565. this._valueCache[uniformName][1] = y;
  13566. this._valueCache[uniformName][2] = z;
  13567. };
  13568. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  13569. if (!this._valueCache[uniformName]) {
  13570. this._valueCache[uniformName] = [x, y, z, w];
  13571. return;
  13572. }
  13573. this._valueCache[uniformName][0] = x;
  13574. this._valueCache[uniformName][1] = y;
  13575. this._valueCache[uniformName][2] = z;
  13576. this._valueCache[uniformName][3] = w;
  13577. };
  13578. Effect.prototype.setArray = function (uniformName, array) {
  13579. this._engine.setArray(this.getUniform(uniformName), array);
  13580. return this;
  13581. };
  13582. Effect.prototype.setArray2 = function (uniformName, array) {
  13583. this._engine.setArray2(this.getUniform(uniformName), array);
  13584. return this;
  13585. };
  13586. Effect.prototype.setArray3 = function (uniformName, array) {
  13587. this._engine.setArray3(this.getUniform(uniformName), array);
  13588. return this;
  13589. };
  13590. Effect.prototype.setArray4 = function (uniformName, array) {
  13591. this._engine.setArray4(this.getUniform(uniformName), array);
  13592. return this;
  13593. };
  13594. Effect.prototype.setMatrices = function (uniformName, matrices) {
  13595. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  13596. return this;
  13597. };
  13598. Effect.prototype.setMatrix = function (uniformName, matrix) {
  13599. //if (this._valueCache[uniformName] && this._valueCache[uniformName].equals(matrix))
  13600. // return;
  13601. //this._cacheMatrix(uniformName, matrix);
  13602. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  13603. return this;
  13604. };
  13605. Effect.prototype.setFloat = function (uniformName, value) {
  13606. if (this._valueCache[uniformName] && this._valueCache[uniformName] === value)
  13607. return this;
  13608. this._valueCache[uniformName] = value;
  13609. this._engine.setFloat(this.getUniform(uniformName), value);
  13610. return this;
  13611. };
  13612. Effect.prototype.setBool = function (uniformName, bool) {
  13613. if (this._valueCache[uniformName] && this._valueCache[uniformName] === bool)
  13614. return this;
  13615. this._valueCache[uniformName] = bool;
  13616. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  13617. return this;
  13618. };
  13619. Effect.prototype.setVector2 = function (uniformName, vector2) {
  13620. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector2.x && this._valueCache[uniformName][1] === vector2.y)
  13621. return this;
  13622. this._cacheFloat2(uniformName, vector2.x, vector2.y);
  13623. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  13624. return this;
  13625. };
  13626. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  13627. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y)
  13628. return this;
  13629. this._cacheFloat2(uniformName, x, y);
  13630. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  13631. return this;
  13632. };
  13633. Effect.prototype.setVector3 = function (uniformName, vector3) {
  13634. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === vector3.x && this._valueCache[uniformName][1] === vector3.y && this._valueCache[uniformName][2] === vector3.z)
  13635. return this;
  13636. this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z);
  13637. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  13638. return this;
  13639. };
  13640. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  13641. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z)
  13642. return this;
  13643. this._cacheFloat3(uniformName, x, y, z);
  13644. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  13645. return this;
  13646. };
  13647. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  13648. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === x && this._valueCache[uniformName][1] === y && this._valueCache[uniformName][2] === z && this._valueCache[uniformName][3] === w)
  13649. return this;
  13650. this._cacheFloat4(uniformName, x, y, z, w);
  13651. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  13652. return this;
  13653. };
  13654. Effect.prototype.setColor3 = function (uniformName, color3) {
  13655. if (this._valueCache[uniformName] && this._valueCache[uniformName][0] === color3.r && this._valueCache[uniformName][1] === color3.g && this._valueCache[uniformName][2] === color3.b)
  13656. return this;
  13657. this._cacheFloat3(uniformName, color3.r, color3.g, color3.b);
  13658. this._engine.setColor3(this.getUniform(uniformName), color3);
  13659. return this;
  13660. };
  13661. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  13662. 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)
  13663. return this;
  13664. this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha);
  13665. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  13666. return this;
  13667. };
  13668. // Statics
  13669. 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}",
  13670. 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}",
  13671. 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}",
  13672. 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}",
  13673. 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}",
  13674. 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}",
  13675. colorPixelShader:"precision highp float;\n\nuniform vec4 color;\n\nvoid main(void) {\n gl_FragColor = color;\n}",
  13676. 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}",
  13677. 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}",
  13678. 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 bitShift = vec4(1. / (255. * 255. * 255.), 1. / (255. * 255.), 1. / 255., 1.);\n return dot(color, bitShift);\n}\n\nfloat unpackHalf(vec2 color)\n{\n return color.x + (color.y / 255.0);\n}\n\nfloat computeShadow(vec4 vPositionFromLight, sampler2D shadowSampler, float darkness, float bias)\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)) + 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 vec2 uv = 0.5 * depth.xy + vec2(0.5, 0.5);\n\n if (uv.x < 0. || uv.x > 1.0 || uv.y < 0. || uv.y > 1.0)\n {\n return 1.0;\n }\n\n float visibility = 1.;\n\n vec2 poissonDisk[4];\n poissonDisk[0] = vec2(-0.94201624, -0.39906216);\n poissonDisk[1] = vec2(0.94558609, -0.76890725);\n poissonDisk[2] = vec2(-0.094184101, -0.92938870);\n poissonDisk[3] = vec2(0.34495938, 0.29387760);\n\n // Poisson Sampling\n if (unpack(texture2D(shadowSampler, uv + poissonDisk[0] / 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)\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.02);\n\n float d = t - moments.x;\n return clamp(variance / (variance + d * d) - 0.2, 0., 1.0);\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 || 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);\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);\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);\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);\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);\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}",
  13679. 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}",
  13680. 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}",
  13681. depthVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#else\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n\n#ifdef ALPHATEST\n#ifdef UV1\n vUV = vec2(diffuseMatrix * vec4(uv, 1.0, 0.0));\n#endif\n#ifdef UV2\n vUV = vec2(diffuseMatrix * vec4(uv2, 1.0, 0.0));\n#endif\n#endif\n}",
  13682. 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}",
  13683. 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}",
  13684. 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}",
  13685. 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}",
  13686. 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}",
  13687. 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}",
  13688. 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}",
  13689. 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}",
  13690. 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}",
  13691. 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}",
  13692. 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}",
  13693. 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}",
  13694. 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}",
  13695. 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}",
  13696. 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}",
  13697. 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}",
  13698. 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}",
  13699. 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}",
  13700. 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}",
  13701. 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}",
  13702. 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}",
  13703. 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}",
  13704. 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}",
  13705. shadowMapPixelShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\nvec4 pack(float depth)\n{\n const vec4 bitOffset = vec4(255. * 255. * 255., 255. * 255., 255., 1.);\n const vec4 bitMask = vec4(0., 1. / 255., 1. / 255., 1. / 255.);\n \n vec4 comp = mod(depth * bitOffset * vec4(255.), vec4(255.)) / vec4(255.);\n comp -= comp.xxyz * bitMask;\n \n return comp;\n}\n\n// Thanks to http://devmaster.net/\nvec2 packHalf(float depth) \n{ \n const vec2 bitOffset = vec2(1.0 / 255., 0.);\n vec2 color = vec2(depth, fract(depth * 255.));\n\n return color - (color.yy * bitOffset);\n}\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n\nvoid main(void)\n{\n#ifdef ALPHATEST\n if (texture2D(diffuseSampler, vUV).a < 0.4)\n discard;\n#endif\n\n#ifdef VSM\n float moment1 = gl_FragCoord.z;\n float moment2 = moment1 * moment1;\n gl_FragColor = vec4(packHalf(moment1), packHalf(moment2));\n#else\n gl_FragColor = pack(vPosition.z / vPosition.w);\n#endif\n}",
  13706. shadowMapVertexShader:"#ifdef GL_ES\nprecision highp float;\n#endif\n\n// Attribute\nattribute vec3 position;\n#ifdef BONES\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#endif\n\n// Uniform\n#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif\n\nuniform mat4 viewProjection;\n#ifdef BONES\nuniform mat4 mBones[BonesPerMesh];\n#endif\n\n#ifndef VSM\nvarying vec4 vPosition;\n#endif\n\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n\nvoid main(void)\n{\n#ifdef INSTANCES\n mat4 finalWorld = mat4(world0, world1, world2, world3);\n#else\n mat4 finalWorld = world;\n#endif\n\n#ifdef BONES\n mat4 m0 = mBones[int(matricesIndices.x)] * matricesWeights.x;\n mat4 m1 = mBones[int(matricesIndices.y)] * matricesWeights.y;\n mat4 m2 = mBones[int(matricesIndices.z)] * matricesWeights.z;\n mat4 m3 = mBones[int(matricesIndices.w)] * matricesWeights.w;\n finalWorld = finalWorld * (m0 + m1 + m2 + m3);\n#endif\n\n#ifndef VSM\n vPosition = viewProjection * finalWorld * vec4(position, 1.0);\n#endif\n gl_Position = viewProjection * finalWorld * vec4(position, 1.0);\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}",
  13707. 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}",
  13708. 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}",
  13709. 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}",
  13710. 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}",
  13711. 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}",
  13712. 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}",
  13713. 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}",
  13714. };
  13715. return Effect;
  13716. })();
  13717. BABYLON.Effect = Effect;
  13718. })(BABYLON || (BABYLON = {}));
  13719. //# sourceMappingURL=babylon.effect.js.mapvar BABYLON;
  13720. (function (BABYLON) {
  13721. var Material = (function () {
  13722. function Material(name, scene, doNotAdd) {
  13723. this.name = name;
  13724. this.checkReadyOnEveryCall = true;
  13725. this.checkReadyOnlyOnce = false;
  13726. this.state = "";
  13727. this.alpha = 1.0;
  13728. this.backFaceCulling = true;
  13729. this._wasPreviouslyReady = false;
  13730. this._fillMode = Material.TriangleFillMode;
  13731. this.pointSize = 1.0;
  13732. this.id = name;
  13733. this._scene = scene;
  13734. if (!doNotAdd) {
  13735. scene.materials.push(this);
  13736. }
  13737. }
  13738. Object.defineProperty(Material, "TriangleFillMode", {
  13739. get: function () {
  13740. return Material._TriangleFillMode;
  13741. },
  13742. enumerable: true,
  13743. configurable: true
  13744. });
  13745. Object.defineProperty(Material, "WireFrameFillMode", {
  13746. get: function () {
  13747. return Material._WireFrameFillMode;
  13748. },
  13749. enumerable: true,
  13750. configurable: true
  13751. });
  13752. Object.defineProperty(Material, "PointFillMode", {
  13753. get: function () {
  13754. return Material._PointFillMode;
  13755. },
  13756. enumerable: true,
  13757. configurable: true
  13758. });
  13759. Object.defineProperty(Material.prototype, "wireframe", {
  13760. get: function () {
  13761. return this._fillMode === Material.WireFrameFillMode;
  13762. },
  13763. set: function (value) {
  13764. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  13765. },
  13766. enumerable: true,
  13767. configurable: true
  13768. });
  13769. Object.defineProperty(Material.prototype, "pointsCloud", {
  13770. get: function () {
  13771. return this._fillMode === Material.PointFillMode;
  13772. },
  13773. set: function (value) {
  13774. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  13775. },
  13776. enumerable: true,
  13777. configurable: true
  13778. });
  13779. Object.defineProperty(Material.prototype, "fillMode", {
  13780. get: function () {
  13781. return this._fillMode;
  13782. },
  13783. set: function (value) {
  13784. this._fillMode = value;
  13785. },
  13786. enumerable: true,
  13787. configurable: true
  13788. });
  13789. Material.prototype.isReady = function (mesh, useInstances) {
  13790. return true;
  13791. };
  13792. Material.prototype.getEffect = function () {
  13793. return this._effect;
  13794. };
  13795. Material.prototype.getScene = function () {
  13796. return this._scene;
  13797. };
  13798. Material.prototype.needAlphaBlending = function () {
  13799. return (this.alpha < 1.0);
  13800. };
  13801. Material.prototype.needAlphaTesting = function () {
  13802. return false;
  13803. };
  13804. Material.prototype.getAlphaTestTexture = function () {
  13805. return null;
  13806. };
  13807. Material.prototype.trackCreation = function (onCompiled, onError) {
  13808. };
  13809. Material.prototype._preBind = function () {
  13810. var engine = this._scene.getEngine();
  13811. engine.enableEffect(this._effect);
  13812. engine.setState(this.backFaceCulling);
  13813. };
  13814. Material.prototype.bind = function (world, mesh) {
  13815. this._scene._cachedMaterial = this;
  13816. if (this.onBind) {
  13817. this.onBind(this);
  13818. }
  13819. };
  13820. Material.prototype.bindOnlyWorldMatrix = function (world) {
  13821. };
  13822. Material.prototype.unbind = function () {
  13823. };
  13824. Material.prototype.dispose = function (forceDisposeEffect) {
  13825. // Remove from scene
  13826. var index = this._scene.materials.indexOf(this);
  13827. this._scene.materials.splice(index, 1);
  13828. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  13829. if (forceDisposeEffect && this._effect) {
  13830. this._scene.getEngine()._releaseEffect(this._effect);
  13831. this._effect = null;
  13832. }
  13833. // Callback
  13834. if (this.onDispose) {
  13835. this.onDispose();
  13836. }
  13837. };
  13838. Material._TriangleFillMode = 0;
  13839. Material._WireFrameFillMode = 1;
  13840. Material._PointFillMode = 2;
  13841. return Material;
  13842. })();
  13843. BABYLON.Material = Material;
  13844. })(BABYLON || (BABYLON = {}));
  13845. //# sourceMappingURL=babylon.material.js.map
  13846. var BABYLON;
  13847. (function (BABYLON) {
  13848. var maxSimultaneousLights = 4;
  13849. var FresnelParameters = (function () {
  13850. function FresnelParameters() {
  13851. this.isEnabled = true;
  13852. this.leftColor = BABYLON.Color3.White();
  13853. this.rightColor = BABYLON.Color3.Black();
  13854. this.bias = 0;
  13855. this.power = 1;
  13856. }
  13857. return FresnelParameters;
  13858. })();
  13859. BABYLON.FresnelParameters = FresnelParameters;
  13860. var StandardMaterial = (function (_super) {
  13861. __extends(StandardMaterial, _super);
  13862. function StandardMaterial(name, scene) {
  13863. var _this = this;
  13864. _super.call(this, name, scene);
  13865. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  13866. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  13867. this.specularColor = new BABYLON.Color3(1, 1, 1);
  13868. this.specularPower = 64;
  13869. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  13870. this.useAlphaFromDiffuseTexture = false;
  13871. this.useSpecularOverAlpha = true;
  13872. this.fogEnabled = true;
  13873. this._cachedDefines = null;
  13874. this._renderTargets = new BABYLON.SmartArray(16);
  13875. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  13876. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  13877. this._scaledDiffuse = new BABYLON.Color3();
  13878. this._scaledSpecular = new BABYLON.Color3();
  13879. this.getRenderTargetTextures = function () {
  13880. _this._renderTargets.reset();
  13881. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  13882. _this._renderTargets.push(_this.reflectionTexture);
  13883. }
  13884. return _this._renderTargets;
  13885. };
  13886. }
  13887. StandardMaterial.prototype.needAlphaBlending = function () {
  13888. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  13889. };
  13890. StandardMaterial.prototype.needAlphaTesting = function () {
  13891. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && !this.diffuseTexture.getAlphaFromRGB;
  13892. };
  13893. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  13894. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  13895. };
  13896. StandardMaterial.prototype.getAlphaTestTexture = function () {
  13897. return this.diffuseTexture;
  13898. };
  13899. // Methods
  13900. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  13901. if (this.checkReadyOnlyOnce) {
  13902. if (this._wasPreviouslyReady) {
  13903. return true;
  13904. }
  13905. }
  13906. var scene = this.getScene();
  13907. if (!this.checkReadyOnEveryCall) {
  13908. if (this._renderId === scene.getRenderId()) {
  13909. return true;
  13910. }
  13911. }
  13912. var engine = scene.getEngine();
  13913. var defines = [];
  13914. var fallbacks = new BABYLON.EffectFallbacks();
  13915. var needNormals = false;
  13916. var needUVs = false;
  13917. // Textures
  13918. if (scene.texturesEnabled) {
  13919. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  13920. if (!this.diffuseTexture.isReady()) {
  13921. return false;
  13922. }
  13923. else {
  13924. needUVs = true;
  13925. defines.push("#define DIFFUSE");
  13926. }
  13927. }
  13928. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  13929. if (!this.ambientTexture.isReady()) {
  13930. return false;
  13931. }
  13932. else {
  13933. needUVs = true;
  13934. defines.push("#define AMBIENT");
  13935. }
  13936. }
  13937. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  13938. if (!this.opacityTexture.isReady()) {
  13939. return false;
  13940. }
  13941. else {
  13942. needUVs = true;
  13943. defines.push("#define OPACITY");
  13944. if (this.opacityTexture.getAlphaFromRGB) {
  13945. defines.push("#define OPACITYRGB");
  13946. }
  13947. }
  13948. }
  13949. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  13950. if (!this.reflectionTexture.isReady()) {
  13951. return false;
  13952. }
  13953. else {
  13954. needNormals = true;
  13955. needUVs = true;
  13956. defines.push("#define REFLECTION");
  13957. fallbacks.addFallback(0, "REFLECTION");
  13958. }
  13959. }
  13960. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  13961. if (!this.emissiveTexture.isReady()) {
  13962. return false;
  13963. }
  13964. else {
  13965. needUVs = true;
  13966. defines.push("#define EMISSIVE");
  13967. }
  13968. }
  13969. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  13970. if (!this.specularTexture.isReady()) {
  13971. return false;
  13972. }
  13973. else {
  13974. needUVs = true;
  13975. defines.push("#define SPECULAR");
  13976. fallbacks.addFallback(0, "SPECULAR");
  13977. }
  13978. }
  13979. }
  13980. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  13981. if (!this.bumpTexture.isReady()) {
  13982. return false;
  13983. }
  13984. else {
  13985. needUVs = true;
  13986. defines.push("#define BUMP");
  13987. fallbacks.addFallback(0, "BUMP");
  13988. }
  13989. }
  13990. // Effect
  13991. if (this.useSpecularOverAlpha) {
  13992. defines.push("#define SPECULAROVERALPHA");
  13993. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  13994. }
  13995. if (scene.clipPlane) {
  13996. defines.push("#define CLIPPLANE");
  13997. }
  13998. if (engine.getAlphaTesting()) {
  13999. defines.push("#define ALPHATEST");
  14000. }
  14001. if (this._shouldUseAlphaFromDiffuseTexture()) {
  14002. defines.push("#define ALPHAFROMDIFFUSE");
  14003. }
  14004. // Point size
  14005. if (this.pointsCloud || scene.forcePointsCloud) {
  14006. defines.push("#define POINTSIZE");
  14007. }
  14008. // Fog
  14009. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  14010. defines.push("#define FOG");
  14011. fallbacks.addFallback(1, "FOG");
  14012. }
  14013. var shadowsActivated = false;
  14014. var lightIndex = 0;
  14015. if (scene.lightsEnabled) {
  14016. for (var index = 0; index < scene.lights.length; index++) {
  14017. var light = scene.lights[index];
  14018. if (!light.isEnabled()) {
  14019. continue;
  14020. }
  14021. // Excluded check
  14022. if (light._excludedMeshesIds.length > 0) {
  14023. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  14024. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  14025. if (excludedMesh) {
  14026. light.excludedMeshes.push(excludedMesh);
  14027. }
  14028. }
  14029. light._excludedMeshesIds = [];
  14030. }
  14031. // Included check
  14032. if (light._includedOnlyMeshesIds.length > 0) {
  14033. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  14034. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  14035. if (includedOnlyMesh) {
  14036. light.includedOnlyMeshes.push(includedOnlyMesh);
  14037. }
  14038. }
  14039. light._includedOnlyMeshesIds = [];
  14040. }
  14041. if (!light.canAffectMesh(mesh)) {
  14042. continue;
  14043. }
  14044. needNormals = true;
  14045. defines.push("#define LIGHT" + lightIndex);
  14046. if (lightIndex > 0) {
  14047. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  14048. }
  14049. var type;
  14050. if (light instanceof BABYLON.SpotLight) {
  14051. type = "#define SPOTLIGHT" + lightIndex;
  14052. }
  14053. else if (light instanceof BABYLON.HemisphericLight) {
  14054. type = "#define HEMILIGHT" + lightIndex;
  14055. }
  14056. else {
  14057. type = "#define POINTDIRLIGHT" + lightIndex;
  14058. }
  14059. defines.push(type);
  14060. if (lightIndex > 0) {
  14061. fallbacks.addFallback(lightIndex, type.replace("#define ", ""));
  14062. }
  14063. // Shadows
  14064. if (scene.shadowsEnabled) {
  14065. var shadowGenerator = light.getShadowGenerator();
  14066. if (mesh && mesh.receiveShadows && shadowGenerator) {
  14067. defines.push("#define SHADOW" + lightIndex);
  14068. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  14069. if (!shadowsActivated) {
  14070. defines.push("#define SHADOWS");
  14071. shadowsActivated = true;
  14072. }
  14073. if (shadowGenerator.useVarianceShadowMap) {
  14074. defines.push("#define SHADOWVSM" + lightIndex);
  14075. if (lightIndex > 0) {
  14076. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  14077. }
  14078. }
  14079. if (shadowGenerator.usePoissonSampling) {
  14080. defines.push("#define SHADOWPCF" + lightIndex);
  14081. if (lightIndex > 0) {
  14082. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  14083. }
  14084. }
  14085. }
  14086. }
  14087. lightIndex++;
  14088. if (lightIndex === maxSimultaneousLights)
  14089. break;
  14090. }
  14091. }
  14092. if (StandardMaterial.FresnelEnabled) {
  14093. // Fresnel
  14094. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled || this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled || this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14095. var fresnelRank = 1;
  14096. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14097. defines.push("#define DIFFUSEFRESNEL");
  14098. fallbacks.addFallback(fresnelRank, "DIFFUSEFRESNEL");
  14099. fresnelRank++;
  14100. }
  14101. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14102. defines.push("#define OPACITYFRESNEL");
  14103. fallbacks.addFallback(fresnelRank, "OPACITYFRESNEL");
  14104. fresnelRank++;
  14105. }
  14106. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14107. defines.push("#define REFLECTIONFRESNEL");
  14108. fallbacks.addFallback(fresnelRank, "REFLECTIONFRESNEL");
  14109. fresnelRank++;
  14110. }
  14111. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14112. defines.push("#define EMISSIVEFRESNEL");
  14113. fallbacks.addFallback(fresnelRank, "EMISSIVEFRESNEL");
  14114. fresnelRank++;
  14115. }
  14116. needNormals = true;
  14117. defines.push("#define FRESNEL");
  14118. fallbacks.addFallback(fresnelRank - 1, "FRESNEL");
  14119. }
  14120. }
  14121. // Attribs
  14122. var attribs = [BABYLON.VertexBuffer.PositionKind];
  14123. if (mesh) {
  14124. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  14125. attribs.push(BABYLON.VertexBuffer.NormalKind);
  14126. defines.push("#define NORMAL");
  14127. }
  14128. if (needUVs) {
  14129. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  14130. attribs.push(BABYLON.VertexBuffer.UVKind);
  14131. defines.push("#define UV1");
  14132. }
  14133. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  14134. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  14135. defines.push("#define UV2");
  14136. }
  14137. }
  14138. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  14139. attribs.push(BABYLON.VertexBuffer.ColorKind);
  14140. defines.push("#define VERTEXCOLOR");
  14141. if (mesh.hasVertexAlpha) {
  14142. defines.push("#define VERTEXALPHA");
  14143. }
  14144. }
  14145. if (mesh.useBones) {
  14146. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  14147. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  14148. defines.push("#define BONES");
  14149. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  14150. defines.push("#define BONES4");
  14151. fallbacks.addFallback(0, "BONES4");
  14152. }
  14153. // Instances
  14154. if (useInstances) {
  14155. defines.push("#define INSTANCES");
  14156. attribs.push("world0");
  14157. attribs.push("world1");
  14158. attribs.push("world2");
  14159. attribs.push("world3");
  14160. }
  14161. }
  14162. // Get correct effect
  14163. var join = defines.join("\n");
  14164. if (this._cachedDefines !== join) {
  14165. this._cachedDefines = join;
  14166. scene.resetCachedMaterial();
  14167. // Legacy browser patch
  14168. var shaderName = "default";
  14169. if (!scene.getEngine().getCaps().standardDerivatives) {
  14170. shaderName = "legacydefault";
  14171. }
  14172. 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);
  14173. }
  14174. if (!this._effect.isReady()) {
  14175. return false;
  14176. }
  14177. this._renderId = scene.getRenderId();
  14178. this._wasPreviouslyReady = true;
  14179. return true;
  14180. };
  14181. StandardMaterial.prototype.unbind = function () {
  14182. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  14183. this._effect.setTexture("reflection2DSampler", null);
  14184. }
  14185. };
  14186. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  14187. this._effect.setMatrix("world", world);
  14188. };
  14189. StandardMaterial.prototype.bind = function (world, mesh) {
  14190. var scene = this.getScene();
  14191. // Matrices
  14192. this.bindOnlyWorldMatrix(world);
  14193. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  14194. // Bones
  14195. if (mesh.useBones) {
  14196. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  14197. }
  14198. if (scene.getCachedMaterial() !== this) {
  14199. if (StandardMaterial.FresnelEnabled) {
  14200. // Fresnel
  14201. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  14202. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  14203. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  14204. }
  14205. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  14206. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  14207. }
  14208. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  14209. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  14210. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  14211. }
  14212. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  14213. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  14214. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  14215. }
  14216. }
  14217. // Textures
  14218. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  14219. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  14220. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  14221. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  14222. }
  14223. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  14224. this._effect.setTexture("ambientSampler", this.ambientTexture);
  14225. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  14226. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  14227. }
  14228. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  14229. this._effect.setTexture("opacitySampler", this.opacityTexture);
  14230. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  14231. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  14232. }
  14233. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  14234. if (this.reflectionTexture.isCube) {
  14235. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  14236. }
  14237. else {
  14238. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  14239. }
  14240. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  14241. this._effect.setFloat3("vReflectionInfos", this.reflectionTexture.coordinatesMode, this.reflectionTexture.level, this.reflectionTexture.isCube ? 1 : 0);
  14242. }
  14243. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  14244. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  14245. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  14246. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  14247. }
  14248. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  14249. this._effect.setTexture("specularSampler", this.specularTexture);
  14250. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  14251. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  14252. }
  14253. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  14254. this._effect.setTexture("bumpSampler", this.bumpTexture);
  14255. this._effect.setFloat2("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level);
  14256. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  14257. }
  14258. // Clip plane
  14259. if (scene.clipPlane) {
  14260. var clipPlane = scene.clipPlane;
  14261. this._effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  14262. }
  14263. // Point size
  14264. if (this.pointsCloud) {
  14265. this._effect.setFloat("pointSize", this.pointSize);
  14266. }
  14267. // Colors
  14268. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  14269. // Scaling down color according to emissive
  14270. this._scaledSpecular.r = this.specularColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14271. this._scaledSpecular.g = this.specularColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14272. this._scaledSpecular.b = this.specularColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14273. this._effect.setVector3("vEyePosition", scene.activeCamera.position);
  14274. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  14275. this._effect.setColor4("vSpecularColor", this._scaledSpecular, this.specularPower);
  14276. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  14277. }
  14278. // Scaling down color according to emissive
  14279. this._scaledDiffuse.r = this.diffuseColor.r * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.r);
  14280. this._scaledDiffuse.g = this.diffuseColor.g * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.g);
  14281. this._scaledDiffuse.b = this.diffuseColor.b * BABYLON.Tools.Clamp(1.0 - this.emissiveColor.b);
  14282. this._effect.setColor4("vDiffuseColor", this._scaledDiffuse, this.alpha * mesh.visibility);
  14283. if (scene.lightsEnabled) {
  14284. var lightIndex = 0;
  14285. for (var index = 0; index < scene.lights.length; index++) {
  14286. var light = scene.lights[index];
  14287. if (!light.isEnabled()) {
  14288. continue;
  14289. }
  14290. if (!light.canAffectMesh(mesh)) {
  14291. continue;
  14292. }
  14293. if (light instanceof BABYLON.PointLight) {
  14294. // Point Light
  14295. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14296. }
  14297. else if (light instanceof BABYLON.DirectionalLight) {
  14298. // Directional Light
  14299. light.transferToEffect(this._effect, "vLightData" + lightIndex);
  14300. }
  14301. else if (light instanceof BABYLON.SpotLight) {
  14302. // Spot Light
  14303. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  14304. }
  14305. else if (light instanceof BABYLON.HemisphericLight) {
  14306. // Hemispheric Light
  14307. light.transferToEffect(this._effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  14308. }
  14309. light.diffuse.scaleToRef(light.intensity, this._scaledDiffuse);
  14310. light.specular.scaleToRef(light.intensity, this._scaledSpecular);
  14311. this._effect.setColor4("vLightDiffuse" + lightIndex, this._scaledDiffuse, light.range);
  14312. this._effect.setColor3("vLightSpecular" + lightIndex, this._scaledSpecular);
  14313. // Shadows
  14314. if (scene.shadowsEnabled) {
  14315. var shadowGenerator = light.getShadowGenerator();
  14316. if (mesh.receiveShadows && shadowGenerator) {
  14317. this._effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  14318. this._effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMap());
  14319. this._effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.getShadowMap().getSize().width, shadowGenerator.getBias());
  14320. }
  14321. }
  14322. lightIndex++;
  14323. if (lightIndex === maxSimultaneousLights)
  14324. break;
  14325. }
  14326. }
  14327. // View
  14328. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  14329. this._effect.setMatrix("view", scene.getViewMatrix());
  14330. }
  14331. // Fog
  14332. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  14333. this._effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  14334. this._effect.setColor3("vFogColor", scene.fogColor);
  14335. }
  14336. _super.prototype.bind.call(this, world, mesh);
  14337. };
  14338. StandardMaterial.prototype.getAnimatables = function () {
  14339. var results = [];
  14340. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  14341. results.push(this.diffuseTexture);
  14342. }
  14343. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  14344. results.push(this.ambientTexture);
  14345. }
  14346. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  14347. results.push(this.opacityTexture);
  14348. }
  14349. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  14350. results.push(this.reflectionTexture);
  14351. }
  14352. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  14353. results.push(this.emissiveTexture);
  14354. }
  14355. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  14356. results.push(this.specularTexture);
  14357. }
  14358. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  14359. results.push(this.bumpTexture);
  14360. }
  14361. return results;
  14362. };
  14363. StandardMaterial.prototype.dispose = function (forceDisposeEffect) {
  14364. if (this.diffuseTexture) {
  14365. this.diffuseTexture.dispose();
  14366. }
  14367. if (this.ambientTexture) {
  14368. this.ambientTexture.dispose();
  14369. }
  14370. if (this.opacityTexture) {
  14371. this.opacityTexture.dispose();
  14372. }
  14373. if (this.reflectionTexture) {
  14374. this.reflectionTexture.dispose();
  14375. }
  14376. if (this.emissiveTexture) {
  14377. this.emissiveTexture.dispose();
  14378. }
  14379. if (this.specularTexture) {
  14380. this.specularTexture.dispose();
  14381. }
  14382. if (this.bumpTexture) {
  14383. this.bumpTexture.dispose();
  14384. }
  14385. _super.prototype.dispose.call(this, forceDisposeEffect);
  14386. };
  14387. StandardMaterial.prototype.clone = function (name) {
  14388. var newStandardMaterial = new StandardMaterial(name, this.getScene());
  14389. // Base material
  14390. newStandardMaterial.checkReadyOnEveryCall = this.checkReadyOnEveryCall;
  14391. newStandardMaterial.alpha = this.alpha;
  14392. newStandardMaterial.fillMode = this.fillMode;
  14393. newStandardMaterial.backFaceCulling = this.backFaceCulling;
  14394. // Standard material
  14395. if (this.diffuseTexture && this.diffuseTexture.clone) {
  14396. newStandardMaterial.diffuseTexture = this.diffuseTexture.clone();
  14397. }
  14398. if (this.ambientTexture && this.ambientTexture.clone) {
  14399. newStandardMaterial.ambientTexture = this.ambientTexture.clone();
  14400. }
  14401. if (this.opacityTexture && this.opacityTexture.clone) {
  14402. newStandardMaterial.opacityTexture = this.opacityTexture.clone();
  14403. }
  14404. if (this.reflectionTexture && this.reflectionTexture.clone) {
  14405. newStandardMaterial.reflectionTexture = this.reflectionTexture.clone();
  14406. }
  14407. if (this.emissiveTexture && this.emissiveTexture.clone) {
  14408. newStandardMaterial.emissiveTexture = this.emissiveTexture.clone();
  14409. }
  14410. if (this.specularTexture && this.specularTexture.clone) {
  14411. newStandardMaterial.specularTexture = this.specularTexture.clone();
  14412. }
  14413. if (this.bumpTexture && this.bumpTexture.clone) {
  14414. newStandardMaterial.bumpTexture = this.bumpTexture.clone();
  14415. }
  14416. newStandardMaterial.ambientColor = this.ambientColor.clone();
  14417. newStandardMaterial.diffuseColor = this.diffuseColor.clone();
  14418. newStandardMaterial.specularColor = this.specularColor.clone();
  14419. newStandardMaterial.specularPower = this.specularPower;
  14420. newStandardMaterial.emissiveColor = this.emissiveColor.clone();
  14421. return newStandardMaterial;
  14422. };
  14423. // Statics
  14424. // Flags used to enable or disable a type of texture for all Standard Materials
  14425. StandardMaterial.DiffuseTextureEnabled = true;
  14426. StandardMaterial.AmbientTextureEnabled = true;
  14427. StandardMaterial.OpacityTextureEnabled = true;
  14428. StandardMaterial.ReflectionTextureEnabled = true;
  14429. StandardMaterial.EmissiveTextureEnabled = true;
  14430. StandardMaterial.SpecularTextureEnabled = true;
  14431. StandardMaterial.BumpTextureEnabled = true;
  14432. StandardMaterial.FresnelEnabled = true;
  14433. return StandardMaterial;
  14434. })(BABYLON.Material);
  14435. BABYLON.StandardMaterial = StandardMaterial;
  14436. })(BABYLON || (BABYLON = {}));
  14437. //# sourceMappingURL=babylon.standardMaterial.js.map
  14438. var BABYLON;
  14439. (function (BABYLON) {
  14440. var MultiMaterial = (function (_super) {
  14441. __extends(MultiMaterial, _super);
  14442. function MultiMaterial(name, scene) {
  14443. _super.call(this, name, scene, true);
  14444. this.subMaterials = new Array();
  14445. scene.multiMaterials.push(this);
  14446. }
  14447. // Properties
  14448. MultiMaterial.prototype.getSubMaterial = function (index) {
  14449. if (index < 0 || index >= this.subMaterials.length) {
  14450. return this.getScene().defaultMaterial;
  14451. }
  14452. return this.subMaterials[index];
  14453. };
  14454. // Methods
  14455. MultiMaterial.prototype.isReady = function (mesh) {
  14456. for (var index = 0; index < this.subMaterials.length; index++) {
  14457. var subMaterial = this.subMaterials[index];
  14458. if (subMaterial) {
  14459. if (!this.subMaterials[index].isReady(mesh)) {
  14460. return false;
  14461. }
  14462. }
  14463. }
  14464. return true;
  14465. };
  14466. return MultiMaterial;
  14467. })(BABYLON.Material);
  14468. BABYLON.MultiMaterial = MultiMaterial;
  14469. })(BABYLON || (BABYLON = {}));
  14470. //# sourceMappingURL=babylon.multiMaterial.js.mapvar BABYLON;
  14471. (function (BABYLON) {
  14472. var Database = (function () {
  14473. function Database(urlToScene, callbackManifestChecked) {
  14474. // Handling various flavors of prefixed version of IndexedDB
  14475. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  14476. this.callbackManifestChecked = callbackManifestChecked;
  14477. this.currentSceneUrl = BABYLON.Database.ReturnFullUrlLocation(urlToScene);
  14478. this.db = null;
  14479. this.enableSceneOffline = false;
  14480. this.enableTexturesOffline = false;
  14481. this.manifestVersionFound = 0;
  14482. this.mustUpdateRessources = false;
  14483. this.hasReachedQuota = false;
  14484. this.checkManifestFile();
  14485. }
  14486. Database.prototype.checkManifestFile = function () {
  14487. var _this = this;
  14488. function noManifestFile() {
  14489. //BABYLON.Tools.Log("Valid manifest file not found. Scene & textures will be loaded directly from the web server.");
  14490. that.enableSceneOffline = false;
  14491. that.enableTexturesOffline = false;
  14492. that.callbackManifestChecked(false);
  14493. }
  14494. var that = this;
  14495. var manifestURL = this.currentSceneUrl + ".manifest";
  14496. var xhr = new XMLHttpRequest();
  14497. var manifestURLTimeStamped = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  14498. xhr.open("GET", manifestURLTimeStamped, true);
  14499. xhr.addEventListener("load", function () {
  14500. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  14501. try {
  14502. var manifestFile = JSON.parse(xhr.response);
  14503. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  14504. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  14505. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  14506. _this.manifestVersionFound = manifestFile.version;
  14507. }
  14508. if (_this.callbackManifestChecked) {
  14509. _this.callbackManifestChecked(true);
  14510. }
  14511. }
  14512. catch (ex) {
  14513. noManifestFile();
  14514. }
  14515. }
  14516. else {
  14517. noManifestFile();
  14518. }
  14519. }, false);
  14520. xhr.addEventListener("error", function (event) {
  14521. noManifestFile();
  14522. }, false);
  14523. try {
  14524. xhr.send();
  14525. }
  14526. catch (ex) {
  14527. BABYLON.Tools.Error("Error on XHR send request.");
  14528. that.callbackManifestChecked(false);
  14529. }
  14530. };
  14531. Database.prototype.openAsync = function (successCallback, errorCallback) {
  14532. var _this = this;
  14533. function handleError() {
  14534. that.isSupported = false;
  14535. if (errorCallback)
  14536. errorCallback();
  14537. }
  14538. var that = this;
  14539. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  14540. // Your browser doesn't support IndexedDB
  14541. this.isSupported = false;
  14542. if (errorCallback)
  14543. errorCallback();
  14544. }
  14545. else {
  14546. // If the DB hasn't been opened or created yet
  14547. if (!this.db) {
  14548. this.hasReachedQuota = false;
  14549. this.isSupported = true;
  14550. var request = this.idbFactory.open("babylonjs", 1);
  14551. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  14552. request.onerror = function (event) {
  14553. handleError();
  14554. };
  14555. // executes when a version change transaction cannot complete due to other active transactions
  14556. request.onblocked = function (event) {
  14557. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  14558. handleError();
  14559. };
  14560. // DB has been opened successfully
  14561. request.onsuccess = function (event) {
  14562. _this.db = request.result;
  14563. successCallback();
  14564. };
  14565. // Initialization of the DB. Creating Scenes & Textures stores
  14566. request.onupgradeneeded = function (event) {
  14567. _this.db = (event.target).result;
  14568. try {
  14569. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  14570. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  14571. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  14572. }
  14573. catch (ex) {
  14574. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  14575. handleError();
  14576. }
  14577. };
  14578. }
  14579. else {
  14580. if (successCallback)
  14581. successCallback();
  14582. }
  14583. }
  14584. };
  14585. Database.prototype.loadImageFromDB = function (url, image) {
  14586. var _this = this;
  14587. var completeURL = Database.ReturnFullUrlLocation(url);
  14588. var saveAndLoadImage = function () {
  14589. if (!_this.hasReachedQuota && _this.db !== null) {
  14590. // the texture is not yet in the DB, let's try to save it
  14591. _this._saveImageIntoDBAsync(completeURL, image);
  14592. }
  14593. else {
  14594. image.src = url;
  14595. }
  14596. };
  14597. if (!this.mustUpdateRessources) {
  14598. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  14599. }
  14600. else {
  14601. saveAndLoadImage();
  14602. }
  14603. };
  14604. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  14605. if (this.isSupported && this.db !== null) {
  14606. var texture;
  14607. var transaction = this.db.transaction(["textures"]);
  14608. transaction.onabort = function (event) {
  14609. image.src = url;
  14610. };
  14611. transaction.oncomplete = function (event) {
  14612. var blobTextureURL;
  14613. if (texture) {
  14614. var URL = window.URL || window.webkitURL;
  14615. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  14616. image.onerror = function () {
  14617. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  14618. image.src = url;
  14619. };
  14620. image.src = blobTextureURL;
  14621. }
  14622. else {
  14623. notInDBCallback();
  14624. }
  14625. };
  14626. var getRequest = transaction.objectStore("textures").get(url);
  14627. getRequest.onsuccess = function (event) {
  14628. texture = (event.target).result;
  14629. };
  14630. getRequest.onerror = function (event) {
  14631. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  14632. image.src = url;
  14633. };
  14634. }
  14635. else {
  14636. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14637. image.src = url;
  14638. }
  14639. };
  14640. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  14641. var _this = this;
  14642. if (this.isSupported) {
  14643. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  14644. var generateBlobUrl = function () {
  14645. var blobTextureURL;
  14646. if (blob) {
  14647. var URL = window.URL || window.webkitURL;
  14648. try {
  14649. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  14650. }
  14651. catch (ex) {
  14652. blobTextureURL = URL.createObjectURL(blob);
  14653. }
  14654. }
  14655. image.src = blobTextureURL;
  14656. };
  14657. if (Database.isUASupportingBlobStorage) {
  14658. var xhr = new XMLHttpRequest(), blob;
  14659. xhr.open("GET", url, true);
  14660. xhr.responseType = "blob";
  14661. xhr.addEventListener("load", function () {
  14662. if (xhr.status === 200) {
  14663. // Blob as response (XHR2)
  14664. blob = xhr.response;
  14665. var transaction = _this.db.transaction(["textures"], "readwrite");
  14666. // the transaction could abort because of a QuotaExceededError error
  14667. transaction.onabort = function (event) {
  14668. try {
  14669. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14670. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14671. this.hasReachedQuota = true;
  14672. }
  14673. }
  14674. catch (ex) {
  14675. }
  14676. generateBlobUrl();
  14677. };
  14678. transaction.oncomplete = function (event) {
  14679. generateBlobUrl();
  14680. };
  14681. var newTexture = { textureUrl: url, data: blob };
  14682. try {
  14683. // Put the blob into the dabase
  14684. var addRequest = transaction.objectStore("textures").put(newTexture);
  14685. addRequest.onsuccess = function (event) {
  14686. };
  14687. addRequest.onerror = function (event) {
  14688. generateBlobUrl();
  14689. };
  14690. }
  14691. catch (ex) {
  14692. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  14693. if (ex.code === 25) {
  14694. Database.isUASupportingBlobStorage = false;
  14695. }
  14696. image.src = url;
  14697. }
  14698. }
  14699. else {
  14700. image.src = url;
  14701. }
  14702. }, false);
  14703. xhr.addEventListener("error", function (event) {
  14704. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  14705. image.src = url;
  14706. }, false);
  14707. xhr.send();
  14708. }
  14709. else {
  14710. image.src = url;
  14711. }
  14712. }
  14713. else {
  14714. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14715. image.src = url;
  14716. }
  14717. };
  14718. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  14719. var _this = this;
  14720. var updateVersion = function (event) {
  14721. // the version is not yet in the DB or we need to update it
  14722. _this._saveVersionIntoDBAsync(url, versionLoaded);
  14723. };
  14724. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  14725. };
  14726. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  14727. var _this = this;
  14728. if (this.isSupported) {
  14729. var version;
  14730. try {
  14731. var transaction = this.db.transaction(["versions"]);
  14732. transaction.oncomplete = function (event) {
  14733. if (version) {
  14734. // If the version in the JSON file is > than the version in DB
  14735. if (_this.manifestVersionFound > version.data) {
  14736. _this.mustUpdateRessources = true;
  14737. updateInDBCallback();
  14738. }
  14739. else {
  14740. callback(version.data);
  14741. }
  14742. }
  14743. else {
  14744. _this.mustUpdateRessources = true;
  14745. updateInDBCallback();
  14746. }
  14747. };
  14748. transaction.onabort = function (event) {
  14749. callback(-1);
  14750. };
  14751. var getRequest = transaction.objectStore("versions").get(url);
  14752. getRequest.onsuccess = function (event) {
  14753. version = (event.target).result;
  14754. };
  14755. getRequest.onerror = function (event) {
  14756. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  14757. callback(-1);
  14758. };
  14759. }
  14760. catch (ex) {
  14761. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  14762. callback(-1);
  14763. }
  14764. }
  14765. else {
  14766. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14767. callback(-1);
  14768. }
  14769. };
  14770. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  14771. var _this = this;
  14772. if (this.isSupported && !this.hasReachedQuota) {
  14773. try {
  14774. // Open a transaction to the database
  14775. var transaction = this.db.transaction(["versions"], "readwrite");
  14776. // the transaction could abort because of a QuotaExceededError error
  14777. transaction.onabort = function (event) {
  14778. try {
  14779. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14780. _this.hasReachedQuota = true;
  14781. }
  14782. }
  14783. catch (ex) {
  14784. }
  14785. callback(-1);
  14786. };
  14787. transaction.oncomplete = function (event) {
  14788. callback(_this.manifestVersionFound);
  14789. };
  14790. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  14791. // Put the scene into the database
  14792. var addRequest = transaction.objectStore("versions").put(newVersion);
  14793. addRequest.onsuccess = function (event) {
  14794. };
  14795. addRequest.onerror = function (event) {
  14796. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  14797. };
  14798. }
  14799. catch (ex) {
  14800. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  14801. callback(-1);
  14802. }
  14803. }
  14804. else {
  14805. callback(-1);
  14806. }
  14807. };
  14808. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  14809. var _this = this;
  14810. var completeUrl = Database.ReturnFullUrlLocation(url);
  14811. var saveAndLoadFile = function (event) {
  14812. // the scene is not yet in the DB, let's try to save it
  14813. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  14814. };
  14815. this._checkVersionFromDB(completeUrl, function (version) {
  14816. if (version !== -1) {
  14817. if (!_this.mustUpdateRessources) {
  14818. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  14819. }
  14820. else {
  14821. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  14822. }
  14823. }
  14824. else {
  14825. errorCallback();
  14826. }
  14827. });
  14828. };
  14829. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  14830. if (this.isSupported) {
  14831. var targetStore;
  14832. if (url.indexOf(".babylon") !== -1) {
  14833. targetStore = "scenes";
  14834. }
  14835. else {
  14836. targetStore = "textures";
  14837. }
  14838. var file;
  14839. var transaction = this.db.transaction([targetStore]);
  14840. transaction.oncomplete = function (event) {
  14841. if (file) {
  14842. callback(file.data);
  14843. }
  14844. else {
  14845. notInDBCallback();
  14846. }
  14847. };
  14848. transaction.onabort = function (event) {
  14849. notInDBCallback();
  14850. };
  14851. var getRequest = transaction.objectStore(targetStore).get(url);
  14852. getRequest.onsuccess = function (event) {
  14853. file = (event.target).result;
  14854. };
  14855. getRequest.onerror = function (event) {
  14856. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  14857. notInDBCallback();
  14858. };
  14859. }
  14860. else {
  14861. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14862. callback();
  14863. }
  14864. };
  14865. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  14866. var _this = this;
  14867. if (this.isSupported) {
  14868. var targetStore;
  14869. if (url.indexOf(".babylon") !== -1) {
  14870. targetStore = "scenes";
  14871. }
  14872. else {
  14873. targetStore = "textures";
  14874. }
  14875. // Create XHR
  14876. var xhr = new XMLHttpRequest(), fileData;
  14877. xhr.open("GET", url, true);
  14878. if (useArrayBuffer) {
  14879. xhr.responseType = "arraybuffer";
  14880. }
  14881. xhr.onprogress = progressCallback;
  14882. xhr.addEventListener("load", function () {
  14883. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  14884. // Blob as response (XHR2)
  14885. //fileData = xhr.responseText;
  14886. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  14887. if (!_this.hasReachedQuota) {
  14888. // Open a transaction to the database
  14889. var transaction = _this.db.transaction([targetStore], "readwrite");
  14890. // the transaction could abort because of a QuotaExceededError error
  14891. transaction.onabort = function (event) {
  14892. try {
  14893. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  14894. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  14895. this.hasReachedQuota = true;
  14896. }
  14897. }
  14898. catch (ex) {
  14899. }
  14900. callback(fileData);
  14901. };
  14902. transaction.oncomplete = function (event) {
  14903. callback(fileData);
  14904. };
  14905. var newFile;
  14906. if (targetStore === "scenes") {
  14907. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  14908. }
  14909. else {
  14910. newFile = { textureUrl: url, data: fileData };
  14911. }
  14912. try {
  14913. // Put the scene into the database
  14914. var addRequest = transaction.objectStore(targetStore).put(newFile);
  14915. addRequest.onsuccess = function (event) {
  14916. };
  14917. addRequest.onerror = function (event) {
  14918. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  14919. };
  14920. }
  14921. catch (ex) {
  14922. callback(fileData);
  14923. }
  14924. }
  14925. else {
  14926. callback(fileData);
  14927. }
  14928. }
  14929. else {
  14930. callback();
  14931. }
  14932. }, false);
  14933. xhr.addEventListener("error", function (event) {
  14934. BABYLON.Tools.Error("error on XHR request.");
  14935. callback();
  14936. }, false);
  14937. xhr.send();
  14938. }
  14939. else {
  14940. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  14941. callback();
  14942. }
  14943. };
  14944. Database.isUASupportingBlobStorage = true;
  14945. Database.parseURL = function (url) {
  14946. var a = document.createElement('a');
  14947. a.href = url;
  14948. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  14949. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  14950. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  14951. return absLocation;
  14952. };
  14953. Database.ReturnFullUrlLocation = function (url) {
  14954. if (url.indexOf("http:/") === -1) {
  14955. return (BABYLON.Database.parseURL(window.location.href) + url);
  14956. }
  14957. else {
  14958. return url;
  14959. }
  14960. };
  14961. return Database;
  14962. })();
  14963. BABYLON.Database = Database;
  14964. })(BABYLON || (BABYLON = {}));
  14965. //# sourceMappingURL=babylon.database.js.mapvar BABYLON;
  14966. (function (BABYLON) {
  14967. var SpriteManager = (function () {
  14968. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon) {
  14969. this.name = name;
  14970. this.cellSize = cellSize;
  14971. this.sprites = new Array();
  14972. this.renderingGroupId = 0;
  14973. this.fogEnabled = true;
  14974. this._vertexDeclaration = [3, 4, 4, 4];
  14975. this._vertexStrideSize = 15 * 4; // 15 floats per sprite (x, y, z, angle, size, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color)
  14976. this._capacity = capacity;
  14977. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false);
  14978. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14979. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  14980. this._epsilon = epsilon === undefined ? 0.01 : epsilon;
  14981. this._scene = scene;
  14982. this._scene.spriteManagers.push(this);
  14983. // VBO
  14984. this._vertexDeclaration = [3, 4, 4, 4];
  14985. this._vertexStrideSize = 15 * 4;
  14986. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  14987. var indices = [];
  14988. var index = 0;
  14989. for (var count = 0; count < capacity; count++) {
  14990. indices.push(index);
  14991. indices.push(index + 1);
  14992. indices.push(index + 2);
  14993. indices.push(index);
  14994. indices.push(index + 2);
  14995. indices.push(index + 3);
  14996. index += 4;
  14997. }
  14998. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  14999. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15000. // Effects
  15001. this._effectBase = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  15002. this._effectFog = this._scene.getEngine().createEffect("sprites", ["position", "options", "cellInfo", "color"], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  15003. }
  15004. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  15005. var arrayOffset = index * 15;
  15006. if (offsetX == 0)
  15007. offsetX = this._epsilon;
  15008. else if (offsetX == 1)
  15009. offsetX = 1 - this._epsilon;
  15010. if (offsetY == 0)
  15011. offsetY = this._epsilon;
  15012. else if (offsetY == 1)
  15013. offsetY = 1 - this._epsilon;
  15014. this._vertices[arrayOffset] = sprite.position.x;
  15015. this._vertices[arrayOffset + 1] = sprite.position.y;
  15016. this._vertices[arrayOffset + 2] = sprite.position.z;
  15017. this._vertices[arrayOffset + 3] = sprite.angle;
  15018. this._vertices[arrayOffset + 4] = sprite.size;
  15019. this._vertices[arrayOffset + 5] = offsetX;
  15020. this._vertices[arrayOffset + 6] = offsetY;
  15021. this._vertices[arrayOffset + 7] = sprite.invertU ? 1 : 0;
  15022. this._vertices[arrayOffset + 8] = sprite.invertV ? 1 : 0;
  15023. var offset = (sprite.cellIndex / rowSize) >> 0;
  15024. this._vertices[arrayOffset + 9] = sprite.cellIndex - offset * rowSize;
  15025. this._vertices[arrayOffset + 10] = offset;
  15026. // Color
  15027. this._vertices[arrayOffset + 11] = sprite.color.r;
  15028. this._vertices[arrayOffset + 12] = sprite.color.g;
  15029. this._vertices[arrayOffset + 13] = sprite.color.b;
  15030. this._vertices[arrayOffset + 14] = sprite.color.a;
  15031. };
  15032. SpriteManager.prototype.render = function () {
  15033. // Check
  15034. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  15035. return;
  15036. var engine = this._scene.getEngine();
  15037. var baseSize = this._spriteTexture.getBaseSize();
  15038. // Sprites
  15039. var deltaTime = engine.getDeltaTime();
  15040. var max = Math.min(this._capacity, this.sprites.length);
  15041. var rowSize = baseSize.width / this.cellSize;
  15042. var offset = 0;
  15043. for (var index = 0; index < max; index++) {
  15044. var sprite = this.sprites[index];
  15045. if (!sprite) {
  15046. continue;
  15047. }
  15048. sprite._animate(deltaTime);
  15049. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  15050. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  15051. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  15052. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  15053. }
  15054. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15055. // Render
  15056. var effect = this._effectBase;
  15057. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15058. effect = this._effectFog;
  15059. }
  15060. engine.enableEffect(effect);
  15061. var viewMatrix = this._scene.getViewMatrix();
  15062. effect.setTexture("diffuseSampler", this._spriteTexture);
  15063. effect.setMatrix("view", viewMatrix);
  15064. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15065. effect.setFloat2("textureInfos", this.cellSize / baseSize.width, this.cellSize / baseSize.height);
  15066. // Fog
  15067. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  15068. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  15069. effect.setColor3("vFogColor", this._scene.fogColor);
  15070. }
  15071. // VBOs
  15072. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15073. // Draw order
  15074. effect.setBool("alphaTest", true);
  15075. engine.setColorWrite(false);
  15076. engine.draw(true, 0, max * 6);
  15077. engine.setColorWrite(true);
  15078. effect.setBool("alphaTest", false);
  15079. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15080. engine.draw(true, 0, max * 6);
  15081. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15082. };
  15083. SpriteManager.prototype.dispose = function () {
  15084. if (this._vertexBuffer) {
  15085. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15086. this._vertexBuffer = null;
  15087. }
  15088. if (this._indexBuffer) {
  15089. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15090. this._indexBuffer = null;
  15091. }
  15092. if (this._spriteTexture) {
  15093. this._spriteTexture.dispose();
  15094. this._spriteTexture = null;
  15095. }
  15096. // Remove from scene
  15097. var index = this._scene.spriteManagers.indexOf(this);
  15098. this._scene.spriteManagers.splice(index, 1);
  15099. // Callback
  15100. if (this.onDispose) {
  15101. this.onDispose();
  15102. }
  15103. };
  15104. return SpriteManager;
  15105. })();
  15106. BABYLON.SpriteManager = SpriteManager;
  15107. })(BABYLON || (BABYLON = {}));
  15108. //# sourceMappingURL=babylon.spriteManager.js.mapvar BABYLON;
  15109. (function (BABYLON) {
  15110. var Sprite = (function () {
  15111. function Sprite(name, manager) {
  15112. this.name = name;
  15113. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15114. this.size = 1.0;
  15115. this.angle = 0;
  15116. this.cellIndex = 0;
  15117. this.invertU = 0;
  15118. this.invertV = 0;
  15119. this.animations = new Array();
  15120. this._animationStarted = false;
  15121. this._loopAnimation = false;
  15122. this._fromIndex = 0;
  15123. this._toIndex = 0;
  15124. this._delay = 0;
  15125. this._direction = 1;
  15126. this._frameCount = 0;
  15127. this._time = 0;
  15128. this._manager = manager;
  15129. this._manager.sprites.push(this);
  15130. this.position = BABYLON.Vector3.Zero();
  15131. }
  15132. Sprite.prototype.playAnimation = function (from, to, loop, delay) {
  15133. this._fromIndex = from;
  15134. this._toIndex = to;
  15135. this._loopAnimation = loop;
  15136. this._delay = delay;
  15137. this._animationStarted = true;
  15138. this._direction = from < to ? 1 : -1;
  15139. this.cellIndex = from;
  15140. this._time = 0;
  15141. };
  15142. Sprite.prototype.stopAnimation = function () {
  15143. this._animationStarted = false;
  15144. };
  15145. Sprite.prototype._animate = function (deltaTime) {
  15146. if (!this._animationStarted)
  15147. return;
  15148. this._time += deltaTime;
  15149. if (this._time > this._delay) {
  15150. this._time = this._time % this._delay;
  15151. this.cellIndex += this._direction;
  15152. if (this.cellIndex == this._toIndex) {
  15153. if (this._loopAnimation) {
  15154. this.cellIndex = this._fromIndex;
  15155. }
  15156. else {
  15157. this._animationStarted = false;
  15158. if (this.disposeWhenFinishedAnimating) {
  15159. this.dispose();
  15160. }
  15161. }
  15162. }
  15163. }
  15164. };
  15165. Sprite.prototype.dispose = function () {
  15166. for (var i = 0; i < this._manager.sprites.length; i++) {
  15167. if (this._manager.sprites[i] == this) {
  15168. this._manager.sprites.splice(i, 1);
  15169. }
  15170. }
  15171. };
  15172. return Sprite;
  15173. })();
  15174. BABYLON.Sprite = Sprite;
  15175. })(BABYLON || (BABYLON = {}));
  15176. //# sourceMappingURL=babylon.sprite.js.mapvar BABYLON;
  15177. (function (BABYLON) {
  15178. var Layer = (function () {
  15179. function Layer(name, imgUrl, scene, isBackground, color) {
  15180. this.name = name;
  15181. this._vertexDeclaration = [2];
  15182. this._vertexStrideSize = 2 * 4;
  15183. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  15184. this.isBackground = isBackground === undefined ? true : isBackground;
  15185. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  15186. this._scene = scene;
  15187. this._scene.layers.push(this);
  15188. // VBO
  15189. var vertices = [];
  15190. vertices.push(1, 1);
  15191. vertices.push(-1, 1);
  15192. vertices.push(-1, -1);
  15193. vertices.push(1, -1);
  15194. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  15195. // Indices
  15196. var indices = [];
  15197. indices.push(0);
  15198. indices.push(1);
  15199. indices.push(2);
  15200. indices.push(0);
  15201. indices.push(2);
  15202. indices.push(3);
  15203. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15204. // Effects
  15205. this._effect = this._scene.getEngine().createEffect("layer", ["position"], ["textureMatrix", "color"], ["textureSampler"], "");
  15206. }
  15207. Layer.prototype.render = function () {
  15208. // Check
  15209. if (!this._effect.isReady() || !this.texture || !this.texture.isReady())
  15210. return;
  15211. var engine = this._scene.getEngine();
  15212. // Render
  15213. engine.enableEffect(this._effect);
  15214. engine.setState(false);
  15215. // Texture
  15216. this._effect.setTexture("textureSampler", this.texture);
  15217. this._effect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  15218. // Color
  15219. this._effect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  15220. // VBOs
  15221. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  15222. // Draw order
  15223. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15224. engine.draw(true, 0, 6);
  15225. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15226. };
  15227. Layer.prototype.dispose = function () {
  15228. if (this._vertexBuffer) {
  15229. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15230. this._vertexBuffer = null;
  15231. }
  15232. if (this._indexBuffer) {
  15233. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15234. this._indexBuffer = null;
  15235. }
  15236. if (this.texture) {
  15237. this.texture.dispose();
  15238. this.texture = null;
  15239. }
  15240. // Remove from scene
  15241. var index = this._scene.layers.indexOf(this);
  15242. this._scene.layers.splice(index, 1);
  15243. // Callback
  15244. if (this.onDispose) {
  15245. this.onDispose();
  15246. }
  15247. };
  15248. return Layer;
  15249. })();
  15250. BABYLON.Layer = Layer;
  15251. })(BABYLON || (BABYLON = {}));
  15252. //# sourceMappingURL=babylon.layer.js.mapvar BABYLON;
  15253. (function (BABYLON) {
  15254. var Particle = (function () {
  15255. function Particle() {
  15256. this.position = BABYLON.Vector3.Zero();
  15257. this.direction = BABYLON.Vector3.Zero();
  15258. this.color = new BABYLON.Color4(0, 0, 0, 0);
  15259. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  15260. this.lifeTime = 1.0;
  15261. this.age = 0;
  15262. this.size = 0;
  15263. this.angle = 0;
  15264. this.angularSpeed = 0;
  15265. }
  15266. Particle.prototype.copyTo = function (other) {
  15267. other.position.copyFrom(this.position);
  15268. other.direction.copyFrom(this.direction);
  15269. other.color.copyFrom(this.color);
  15270. other.colorStep.copyFrom(this.colorStep);
  15271. other.lifeTime = this.lifeTime;
  15272. other.age = this.age;
  15273. other.size = this.size;
  15274. other.angle = this.angle;
  15275. other.angularSpeed = this.angularSpeed;
  15276. };
  15277. return Particle;
  15278. })();
  15279. BABYLON.Particle = Particle;
  15280. })(BABYLON || (BABYLON = {}));
  15281. //# sourceMappingURL=babylon.particle.js.mapvar BABYLON;
  15282. (function (BABYLON) {
  15283. var randomNumber = function (min, max) {
  15284. if (min === max) {
  15285. return (min);
  15286. }
  15287. var random = Math.random();
  15288. return ((random * (max - min)) + min);
  15289. };
  15290. var ParticleSystem = (function () {
  15291. function ParticleSystem(name, capacity, scene, customEffect) {
  15292. var _this = this;
  15293. this.name = name;
  15294. this.renderingGroupId = 0;
  15295. this.emitter = null;
  15296. this.emitRate = 10;
  15297. this.manualEmitCount = -1;
  15298. this.updateSpeed = 0.01;
  15299. this.targetStopDuration = 0;
  15300. this.disposeOnStop = false;
  15301. this.minEmitPower = 1;
  15302. this.maxEmitPower = 1;
  15303. this.minLifeTime = 1;
  15304. this.maxLifeTime = 1;
  15305. this.minSize = 1;
  15306. this.maxSize = 1;
  15307. this.minAngularSpeed = 0;
  15308. this.maxAngularSpeed = 0;
  15309. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  15310. this.forceDepthWrite = false;
  15311. this.gravity = BABYLON.Vector3.Zero();
  15312. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  15313. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  15314. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  15315. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15316. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15317. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15318. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  15319. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  15320. this.particles = new Array();
  15321. this._vertexDeclaration = [3, 4, 4];
  15322. this._vertexStrideSize = 11 * 4; // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY)
  15323. this._stockParticles = new Array();
  15324. this._newPartsExcess = 0;
  15325. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  15326. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  15327. this._scaledDirection = BABYLON.Vector3.Zero();
  15328. this._scaledGravity = BABYLON.Vector3.Zero();
  15329. this._currentRenderId = -1;
  15330. this._started = false;
  15331. this._stopped = false;
  15332. this._actualFrame = 0;
  15333. this.id = name;
  15334. this._capacity = capacity;
  15335. this._scene = scene;
  15336. this._customEffect = customEffect;
  15337. scene.particleSystems.push(this);
  15338. // VBO
  15339. this._vertexBuffer = scene.getEngine().createDynamicVertexBuffer(capacity * this._vertexStrideSize * 4);
  15340. var indices = [];
  15341. var index = 0;
  15342. for (var count = 0; count < capacity; count++) {
  15343. indices.push(index);
  15344. indices.push(index + 1);
  15345. indices.push(index + 2);
  15346. indices.push(index);
  15347. indices.push(index + 2);
  15348. indices.push(index + 3);
  15349. index += 4;
  15350. }
  15351. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  15352. this._vertices = new Float32Array(capacity * this._vertexStrideSize);
  15353. // Default behaviors
  15354. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate) {
  15355. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  15356. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  15357. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  15358. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  15359. };
  15360. this.startPositionFunction = function (worldMatrix, positionToUpdate) {
  15361. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  15362. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  15363. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  15364. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  15365. };
  15366. this.updateFunction = function (particles) {
  15367. for (var index = 0; index < particles.length; index++) {
  15368. var particle = particles[index];
  15369. particle.age += _this._scaledUpdateSpeed;
  15370. if (particle.age >= particle.lifeTime) {
  15371. _this.recycleParticle(particle);
  15372. index--;
  15373. continue;
  15374. }
  15375. else {
  15376. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  15377. particle.color.addInPlace(_this._scaledColorStep);
  15378. if (particle.color.a < 0)
  15379. particle.color.a = 0;
  15380. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  15381. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  15382. particle.position.addInPlace(_this._scaledDirection);
  15383. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  15384. particle.direction.addInPlace(_this._scaledGravity);
  15385. }
  15386. }
  15387. };
  15388. }
  15389. ParticleSystem.prototype.recycleParticle = function (particle) {
  15390. var lastParticle = this.particles.pop();
  15391. if (lastParticle !== particle) {
  15392. lastParticle.copyTo(particle);
  15393. this._stockParticles.push(lastParticle);
  15394. }
  15395. };
  15396. ParticleSystem.prototype.getCapacity = function () {
  15397. return this._capacity;
  15398. };
  15399. ParticleSystem.prototype.isAlive = function () {
  15400. return this._alive;
  15401. };
  15402. ParticleSystem.prototype.isStarted = function () {
  15403. return this._started;
  15404. };
  15405. ParticleSystem.prototype.start = function () {
  15406. this._started = true;
  15407. this._stopped = false;
  15408. this._actualFrame = 0;
  15409. };
  15410. ParticleSystem.prototype.stop = function () {
  15411. this._stopped = true;
  15412. };
  15413. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  15414. var offset = index * 11;
  15415. this._vertices[offset] = particle.position.x;
  15416. this._vertices[offset + 1] = particle.position.y;
  15417. this._vertices[offset + 2] = particle.position.z;
  15418. this._vertices[offset + 3] = particle.color.r;
  15419. this._vertices[offset + 4] = particle.color.g;
  15420. this._vertices[offset + 5] = particle.color.b;
  15421. this._vertices[offset + 6] = particle.color.a;
  15422. this._vertices[offset + 7] = particle.angle;
  15423. this._vertices[offset + 8] = particle.size;
  15424. this._vertices[offset + 9] = offsetX;
  15425. this._vertices[offset + 10] = offsetY;
  15426. };
  15427. ParticleSystem.prototype._update = function (newParticles) {
  15428. // Update current
  15429. this._alive = this.particles.length > 0;
  15430. this.updateFunction(this.particles);
  15431. // Add new ones
  15432. var worldMatrix;
  15433. if (this.emitter.position) {
  15434. worldMatrix = this.emitter.getWorldMatrix();
  15435. }
  15436. else {
  15437. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  15438. }
  15439. for (var index = 0; index < newParticles; index++) {
  15440. if (this.particles.length === this._capacity) {
  15441. break;
  15442. }
  15443. if (this._stockParticles.length !== 0) {
  15444. var particle = this._stockParticles.pop();
  15445. particle.age = 0;
  15446. }
  15447. else {
  15448. particle = new BABYLON.Particle();
  15449. }
  15450. this.particles.push(particle);
  15451. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  15452. this.startDirectionFunction(emitPower, worldMatrix, particle.direction);
  15453. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  15454. particle.size = randomNumber(this.minSize, this.maxSize);
  15455. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  15456. this.startPositionFunction(worldMatrix, particle.position);
  15457. var step = randomNumber(0, 1.0);
  15458. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  15459. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  15460. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  15461. }
  15462. };
  15463. ParticleSystem.prototype._getEffect = function () {
  15464. if (this._customEffect) {
  15465. return this._customEffect;
  15466. }
  15467. ;
  15468. var defines = [];
  15469. if (this._scene.clipPlane) {
  15470. defines.push("#define CLIPPLANE");
  15471. }
  15472. // Effect
  15473. var join = defines.join("\n");
  15474. if (this._cachedDefines !== join) {
  15475. this._cachedDefines = join;
  15476. this._effect = this._scene.getEngine().createEffect("particles", ["position", "color", "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  15477. }
  15478. return this._effect;
  15479. };
  15480. ParticleSystem.prototype.animate = function () {
  15481. if (!this._started)
  15482. return;
  15483. var effect = this._getEffect();
  15484. // Check
  15485. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  15486. return;
  15487. if (this._currentRenderId === this._scene.getRenderId()) {
  15488. return;
  15489. }
  15490. this._currentRenderId = this._scene.getRenderId();
  15491. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  15492. // determine the number of particles we need to create
  15493. var emitCout;
  15494. if (this.manualEmitCount > -1) {
  15495. emitCout = this.manualEmitCount;
  15496. this.manualEmitCount = 0;
  15497. }
  15498. else {
  15499. emitCout = this.emitRate;
  15500. }
  15501. var newParticles = ((emitCout * this._scaledUpdateSpeed) >> 0);
  15502. this._newPartsExcess += emitCout * this._scaledUpdateSpeed - newParticles;
  15503. if (this._newPartsExcess > 1.0) {
  15504. newParticles += this._newPartsExcess >> 0;
  15505. this._newPartsExcess -= this._newPartsExcess >> 0;
  15506. }
  15507. this._alive = false;
  15508. if (!this._stopped) {
  15509. this._actualFrame += this._scaledUpdateSpeed;
  15510. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  15511. this.stop();
  15512. }
  15513. else {
  15514. newParticles = 0;
  15515. }
  15516. this._update(newParticles);
  15517. // Stopped?
  15518. if (this._stopped) {
  15519. if (!this._alive) {
  15520. this._started = false;
  15521. if (this.disposeOnStop) {
  15522. this._scene._toBeDisposed.push(this);
  15523. }
  15524. }
  15525. }
  15526. // Update VBO
  15527. var offset = 0;
  15528. for (var index = 0; index < this.particles.length; index++) {
  15529. var particle = this.particles[index];
  15530. this._appendParticleVertex(offset++, particle, 0, 0);
  15531. this._appendParticleVertex(offset++, particle, 1, 0);
  15532. this._appendParticleVertex(offset++, particle, 1, 1);
  15533. this._appendParticleVertex(offset++, particle, 0, 1);
  15534. }
  15535. var engine = this._scene.getEngine();
  15536. engine.updateDynamicVertexBuffer(this._vertexBuffer, this._vertices);
  15537. };
  15538. ParticleSystem.prototype.render = function () {
  15539. var effect = this._getEffect();
  15540. // Check
  15541. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  15542. return 0;
  15543. var engine = this._scene.getEngine();
  15544. // Render
  15545. engine.enableEffect(effect);
  15546. engine.setState(false);
  15547. var viewMatrix = this._scene.getViewMatrix();
  15548. effect.setTexture("diffuseSampler", this.particleTexture);
  15549. effect.setMatrix("view", viewMatrix);
  15550. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  15551. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  15552. if (this._scene.clipPlane) {
  15553. var clipPlane = this._scene.clipPlane;
  15554. var invView = viewMatrix.clone();
  15555. invView.invert();
  15556. effect.setMatrix("invView", invView);
  15557. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  15558. }
  15559. // VBOs
  15560. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  15561. // Draw order
  15562. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  15563. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  15564. }
  15565. else {
  15566. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  15567. }
  15568. if (this.forceDepthWrite) {
  15569. engine.setDepthWrite(true);
  15570. }
  15571. engine.draw(true, 0, this.particles.length * 6);
  15572. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15573. return this.particles.length;
  15574. };
  15575. ParticleSystem.prototype.dispose = function () {
  15576. if (this._vertexBuffer) {
  15577. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  15578. this._vertexBuffer = null;
  15579. }
  15580. if (this._indexBuffer) {
  15581. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  15582. this._indexBuffer = null;
  15583. }
  15584. if (this.particleTexture) {
  15585. this.particleTexture.dispose();
  15586. this.particleTexture = null;
  15587. }
  15588. // Remove from scene
  15589. var index = this._scene.particleSystems.indexOf(this);
  15590. this._scene.particleSystems.splice(index, 1);
  15591. // Callback
  15592. if (this.onDispose) {
  15593. this.onDispose();
  15594. }
  15595. };
  15596. // Clone
  15597. ParticleSystem.prototype.clone = function (name, newEmitter) {
  15598. var result = new ParticleSystem(name, this._capacity, this._scene);
  15599. BABYLON.Tools.DeepCopy(this, result, ["particles"], ["_vertexDeclaration", "_vertexStrideSize"]);
  15600. if (newEmitter === undefined) {
  15601. newEmitter = this.emitter;
  15602. }
  15603. result.emitter = newEmitter;
  15604. if (this.particleTexture) {
  15605. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  15606. }
  15607. result.start();
  15608. return result;
  15609. };
  15610. // Statics
  15611. ParticleSystem.BLENDMODE_ONEONE = 0;
  15612. ParticleSystem.BLENDMODE_STANDARD = 1;
  15613. return ParticleSystem;
  15614. })();
  15615. BABYLON.ParticleSystem = ParticleSystem;
  15616. })(BABYLON || (BABYLON = {}));
  15617. //# sourceMappingURL=babylon.particleSystem.js.mapvar BABYLON;
  15618. (function (BABYLON) {
  15619. var Animation = (function () {
  15620. function Animation(name, targetProperty, framePerSecond, dataType, loopMode) {
  15621. this.name = name;
  15622. this.targetProperty = targetProperty;
  15623. this.framePerSecond = framePerSecond;
  15624. this.dataType = dataType;
  15625. this.loopMode = loopMode;
  15626. this._offsetsCache = {};
  15627. this._highLimitsCache = {};
  15628. this._stopped = false;
  15629. this.targetPropertyPath = targetProperty.split(".");
  15630. this.dataType = dataType;
  15631. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  15632. }
  15633. Animation.CreateAndStartAnimation = function (name, mesh, tartgetProperty, framePerSecond, totalFrame, from, to, loopMode) {
  15634. var dataType = undefined;
  15635. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  15636. dataType = Animation.ANIMATIONTYPE_FLOAT;
  15637. }
  15638. else if (from instanceof BABYLON.Quaternion) {
  15639. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  15640. }
  15641. else if (from instanceof BABYLON.Vector3) {
  15642. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  15643. }
  15644. else if (from instanceof BABYLON.Vector2) {
  15645. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  15646. }
  15647. else if (from instanceof BABYLON.Color3) {
  15648. dataType = Animation.ANIMATIONTYPE_COLOR3;
  15649. }
  15650. if (dataType == undefined) {
  15651. return null;
  15652. }
  15653. var animation = new Animation(name, tartgetProperty, framePerSecond, dataType, loopMode);
  15654. var keys = [];
  15655. keys.push({ frame: 0, value: from });
  15656. keys.push({ frame: totalFrame, value: to });
  15657. animation.setKeys(keys);
  15658. mesh.animations.push(animation);
  15659. return mesh.getScene().beginAnimation(mesh, 0, totalFrame, (animation.loopMode === 1));
  15660. };
  15661. // Methods
  15662. Animation.prototype.isStopped = function () {
  15663. return this._stopped;
  15664. };
  15665. Animation.prototype.getKeys = function () {
  15666. return this._keys;
  15667. };
  15668. Animation.prototype.getEasingFunction = function () {
  15669. return this._easingFunction;
  15670. };
  15671. Animation.prototype.setEasingFunction = function (easingFunction) {
  15672. this._easingFunction = easingFunction;
  15673. };
  15674. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  15675. return startValue + (endValue - startValue) * gradient;
  15676. };
  15677. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  15678. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  15679. };
  15680. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  15681. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  15682. };
  15683. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  15684. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  15685. };
  15686. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  15687. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  15688. };
  15689. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  15690. var startScale = new BABYLON.Vector3(0, 0, 0);
  15691. var startRotation = new BABYLON.Quaternion();
  15692. var startTranslation = new BABYLON.Vector3(0, 0, 0);
  15693. startValue.decompose(startScale, startRotation, startTranslation);
  15694. var endScale = new BABYLON.Vector3(0, 0, 0);
  15695. var endRotation = new BABYLON.Quaternion();
  15696. var endTranslation = new BABYLON.Vector3(0, 0, 0);
  15697. endValue.decompose(endScale, endRotation, endTranslation);
  15698. var resultScale = this.vector3InterpolateFunction(startScale, endScale, gradient);
  15699. var resultRotation = this.quaternionInterpolateFunction(startRotation, endRotation, gradient);
  15700. var resultTranslation = this.vector3InterpolateFunction(startTranslation, endTranslation, gradient);
  15701. var result = BABYLON.Matrix.Compose(resultScale, resultRotation, resultTranslation);
  15702. return result;
  15703. };
  15704. Animation.prototype.clone = function () {
  15705. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  15706. clone.setKeys(this._keys);
  15707. return clone;
  15708. };
  15709. Animation.prototype.setKeys = function (values) {
  15710. this._keys = values.slice(0);
  15711. this._offsetsCache = {};
  15712. this._highLimitsCache = {};
  15713. };
  15714. Animation.prototype._getKeyValue = function (value) {
  15715. if (typeof value === "function") {
  15716. return value();
  15717. }
  15718. return value;
  15719. };
  15720. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  15721. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  15722. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  15723. }
  15724. this.currentFrame = currentFrame;
  15725. for (var key = 0; key < this._keys.length; key++) {
  15726. // for each frame, we need the key just before the frame superior
  15727. if (this._keys[key + 1].frame >= currentFrame) {
  15728. var startValue = this._getKeyValue(this._keys[key].value);
  15729. var endValue = this._getKeyValue(this._keys[key + 1].value);
  15730. // gradient : percent of currentFrame between the frame inf and the frame sup
  15731. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  15732. // check for easingFunction and correction of gradient
  15733. if (this._easingFunction != null) {
  15734. gradient = this._easingFunction.ease(gradient);
  15735. }
  15736. switch (this.dataType) {
  15737. case Animation.ANIMATIONTYPE_FLOAT:
  15738. switch (loopMode) {
  15739. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15740. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15741. return this.floatInterpolateFunction(startValue, endValue, gradient);
  15742. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15743. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  15744. }
  15745. break;
  15746. case Animation.ANIMATIONTYPE_QUATERNION:
  15747. var quaternion = null;
  15748. switch (loopMode) {
  15749. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15750. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15751. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  15752. break;
  15753. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15754. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15755. break;
  15756. }
  15757. return quaternion;
  15758. case Animation.ANIMATIONTYPE_VECTOR3:
  15759. switch (loopMode) {
  15760. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15761. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15762. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  15763. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15764. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15765. }
  15766. case Animation.ANIMATIONTYPE_VECTOR2:
  15767. switch (loopMode) {
  15768. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15769. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15770. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  15771. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15772. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15773. }
  15774. case Animation.ANIMATIONTYPE_COLOR3:
  15775. switch (loopMode) {
  15776. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15777. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15778. return this.color3InterpolateFunction(startValue, endValue, gradient);
  15779. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15780. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  15781. }
  15782. case Animation.ANIMATIONTYPE_MATRIX:
  15783. switch (loopMode) {
  15784. case Animation.ANIMATIONLOOPMODE_CYCLE:
  15785. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  15786. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  15787. return startValue;
  15788. }
  15789. default:
  15790. break;
  15791. }
  15792. break;
  15793. }
  15794. }
  15795. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  15796. };
  15797. Animation.prototype.animate = function (delay, from, to, loop, speedRatio) {
  15798. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  15799. this._stopped = true;
  15800. return false;
  15801. }
  15802. var returnValue = true;
  15803. // Adding a start key at frame 0 if missing
  15804. if (this._keys[0].frame !== 0) {
  15805. var newKey = { frame: 0, value: this._keys[0].value };
  15806. this._keys.splice(0, 0, newKey);
  15807. }
  15808. // Check limits
  15809. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  15810. from = this._keys[0].frame;
  15811. }
  15812. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  15813. to = this._keys[this._keys.length - 1].frame;
  15814. }
  15815. // Compute ratio
  15816. var range = to - from;
  15817. var offsetValue;
  15818. // ratio represents the frame delta between from and to
  15819. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  15820. var highLimitValue = 0;
  15821. if (ratio > range && !loop) {
  15822. returnValue = false;
  15823. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  15824. }
  15825. else {
  15826. // Get max value if required
  15827. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  15828. var keyOffset = to.toString() + from.toString();
  15829. if (!this._offsetsCache[keyOffset]) {
  15830. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15831. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  15832. switch (this.dataType) {
  15833. case Animation.ANIMATIONTYPE_FLOAT:
  15834. this._offsetsCache[keyOffset] = toValue - fromValue;
  15835. break;
  15836. case Animation.ANIMATIONTYPE_QUATERNION:
  15837. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15838. break;
  15839. case Animation.ANIMATIONTYPE_VECTOR3:
  15840. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15841. case Animation.ANIMATIONTYPE_VECTOR2:
  15842. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15843. case Animation.ANIMATIONTYPE_COLOR3:
  15844. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  15845. default:
  15846. break;
  15847. }
  15848. this._highLimitsCache[keyOffset] = toValue;
  15849. }
  15850. highLimitValue = this._highLimitsCache[keyOffset];
  15851. offsetValue = this._offsetsCache[keyOffset];
  15852. }
  15853. }
  15854. if (offsetValue === undefined) {
  15855. switch (this.dataType) {
  15856. case Animation.ANIMATIONTYPE_FLOAT:
  15857. offsetValue = 0;
  15858. break;
  15859. case Animation.ANIMATIONTYPE_QUATERNION:
  15860. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  15861. break;
  15862. case Animation.ANIMATIONTYPE_VECTOR3:
  15863. offsetValue = BABYLON.Vector3.Zero();
  15864. break;
  15865. case Animation.ANIMATIONTYPE_VECTOR2:
  15866. offsetValue = BABYLON.Vector2.Zero();
  15867. break;
  15868. case Animation.ANIMATIONTYPE_COLOR3:
  15869. offsetValue = BABYLON.Color3.Black();
  15870. }
  15871. }
  15872. // Compute value
  15873. var repeatCount = (ratio / range) >> 0;
  15874. var currentFrame = returnValue ? from + ratio % range : to;
  15875. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  15876. // Set value
  15877. if (this.targetPropertyPath.length > 1) {
  15878. var property = this._target[this.targetPropertyPath[0]];
  15879. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  15880. property = property[this.targetPropertyPath[index]];
  15881. }
  15882. property[this.targetPropertyPath[this.targetPropertyPath.length - 1]] = currentValue;
  15883. }
  15884. else {
  15885. this._target[this.targetPropertyPath[0]] = currentValue;
  15886. }
  15887. if (this._target.markAsDirty) {
  15888. this._target.markAsDirty(this.targetProperty);
  15889. }
  15890. if (!returnValue) {
  15891. this._stopped = true;
  15892. }
  15893. return returnValue;
  15894. };
  15895. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  15896. get: function () {
  15897. return Animation._ANIMATIONTYPE_FLOAT;
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  15903. get: function () {
  15904. return Animation._ANIMATIONTYPE_VECTOR3;
  15905. },
  15906. enumerable: true,
  15907. configurable: true
  15908. });
  15909. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  15910. get: function () {
  15911. return Animation._ANIMATIONTYPE_VECTOR2;
  15912. },
  15913. enumerable: true,
  15914. configurable: true
  15915. });
  15916. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  15917. get: function () {
  15918. return Animation._ANIMATIONTYPE_QUATERNION;
  15919. },
  15920. enumerable: true,
  15921. configurable: true
  15922. });
  15923. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  15924. get: function () {
  15925. return Animation._ANIMATIONTYPE_MATRIX;
  15926. },
  15927. enumerable: true,
  15928. configurable: true
  15929. });
  15930. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  15931. get: function () {
  15932. return Animation._ANIMATIONTYPE_COLOR3;
  15933. },
  15934. enumerable: true,
  15935. configurable: true
  15936. });
  15937. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  15938. get: function () {
  15939. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  15940. },
  15941. enumerable: true,
  15942. configurable: true
  15943. });
  15944. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  15945. get: function () {
  15946. return Animation._ANIMATIONLOOPMODE_CYCLE;
  15947. },
  15948. enumerable: true,
  15949. configurable: true
  15950. });
  15951. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  15952. get: function () {
  15953. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  15954. },
  15955. enumerable: true,
  15956. configurable: true
  15957. });
  15958. // Statics
  15959. Animation._ANIMATIONTYPE_FLOAT = 0;
  15960. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  15961. Animation._ANIMATIONTYPE_QUATERNION = 2;
  15962. Animation._ANIMATIONTYPE_MATRIX = 3;
  15963. Animation._ANIMATIONTYPE_COLOR3 = 4;
  15964. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  15965. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  15966. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  15967. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  15968. return Animation;
  15969. })();
  15970. BABYLON.Animation = Animation;
  15971. })(BABYLON || (BABYLON = {}));
  15972. //# sourceMappingURL=babylon.animation.js.mapvar BABYLON;
  15973. (function (BABYLON) {
  15974. var Animatable = (function () {
  15975. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  15976. if (fromFrame === void 0) { fromFrame = 0; }
  15977. if (toFrame === void 0) { toFrame = 100; }
  15978. if (loopAnimation === void 0) { loopAnimation = false; }
  15979. if (speedRatio === void 0) { speedRatio = 1.0; }
  15980. this.target = target;
  15981. this.fromFrame = fromFrame;
  15982. this.toFrame = toFrame;
  15983. this.loopAnimation = loopAnimation;
  15984. this.speedRatio = speedRatio;
  15985. this.onAnimationEnd = onAnimationEnd;
  15986. this._animations = new Array();
  15987. this._paused = false;
  15988. this.animationStarted = false;
  15989. if (animations) {
  15990. this.appendAnimations(target, animations);
  15991. }
  15992. this._scene = scene;
  15993. scene._activeAnimatables.push(this);
  15994. }
  15995. // Methods
  15996. Animatable.prototype.appendAnimations = function (target, animations) {
  15997. for (var index = 0; index < animations.length; index++) {
  15998. var animation = animations[index];
  15999. animation._target = target;
  16000. this._animations.push(animation);
  16001. }
  16002. };
  16003. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  16004. var animations = this._animations;
  16005. for (var index = 0; index < animations.length; index++) {
  16006. if (animations[index].targetProperty === property) {
  16007. return animations[index];
  16008. }
  16009. }
  16010. return null;
  16011. };
  16012. Animatable.prototype.pause = function () {
  16013. if (this._paused) {
  16014. return;
  16015. }
  16016. this._paused = true;
  16017. };
  16018. Animatable.prototype.restart = function () {
  16019. this._paused = false;
  16020. };
  16021. Animatable.prototype.stop = function () {
  16022. var index = this._scene._activeAnimatables.indexOf(this);
  16023. if (index > -1) {
  16024. this._scene._activeAnimatables.splice(index, 1);
  16025. }
  16026. if (this.onAnimationEnd) {
  16027. this.onAnimationEnd();
  16028. }
  16029. };
  16030. Animatable.prototype._animate = function (delay) {
  16031. if (this._paused) {
  16032. if (!this._pausedDelay) {
  16033. this._pausedDelay = delay;
  16034. }
  16035. return true;
  16036. }
  16037. if (!this._localDelayOffset) {
  16038. this._localDelayOffset = delay;
  16039. }
  16040. else if (this._pausedDelay) {
  16041. this._localDelayOffset += delay - this._pausedDelay;
  16042. this._pausedDelay = null;
  16043. }
  16044. // Animating
  16045. var running = false;
  16046. var animations = this._animations;
  16047. for (var index = 0; index < animations.length; index++) {
  16048. var animation = animations[index];
  16049. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  16050. running = running || isRunning;
  16051. }
  16052. if (!running && this.onAnimationEnd) {
  16053. this.onAnimationEnd();
  16054. }
  16055. return running;
  16056. };
  16057. return Animatable;
  16058. })();
  16059. BABYLON.Animatable = Animatable;
  16060. })(BABYLON || (BABYLON = {}));
  16061. //# sourceMappingURL=babylon.animatable.js.map
  16062. var BABYLON;
  16063. (function (BABYLON) {
  16064. var EasingFunction = (function () {
  16065. function EasingFunction() {
  16066. // Properties
  16067. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  16068. }
  16069. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  16070. get: function () {
  16071. return EasingFunction._EASINGMODE_EASEIN;
  16072. },
  16073. enumerable: true,
  16074. configurable: true
  16075. });
  16076. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  16077. get: function () {
  16078. return EasingFunction._EASINGMODE_EASEOUT;
  16079. },
  16080. enumerable: true,
  16081. configurable: true
  16082. });
  16083. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  16084. get: function () {
  16085. return EasingFunction._EASINGMODE_EASEINOUT;
  16086. },
  16087. enumerable: true,
  16088. configurable: true
  16089. });
  16090. EasingFunction.prototype.setEasingMode = function (easingMode) {
  16091. var n = Math.min(Math.max(easingMode, 0), 2);
  16092. this._easingMode = n;
  16093. };
  16094. EasingFunction.prototype.getEasingMode = function () {
  16095. return this._easingMode;
  16096. };
  16097. EasingFunction.prototype.easeInCore = function (gradient) {
  16098. throw new Error('You must implement this method');
  16099. };
  16100. EasingFunction.prototype.ease = function (gradient) {
  16101. switch (this._easingMode) {
  16102. case EasingFunction.EASINGMODE_EASEIN:
  16103. return this.easeInCore(gradient);
  16104. case EasingFunction.EASINGMODE_EASEOUT:
  16105. return (1 - this.easeInCore(1 - gradient));
  16106. }
  16107. if (gradient >= 0.5) {
  16108. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  16109. }
  16110. return (this.easeInCore(gradient * 2) * 0.5);
  16111. };
  16112. //Statics
  16113. EasingFunction._EASINGMODE_EASEIN = 0;
  16114. EasingFunction._EASINGMODE_EASEOUT = 1;
  16115. EasingFunction._EASINGMODE_EASEINOUT = 2;
  16116. return EasingFunction;
  16117. })();
  16118. BABYLON.EasingFunction = EasingFunction;
  16119. var CircleEase = (function (_super) {
  16120. __extends(CircleEase, _super);
  16121. function CircleEase() {
  16122. _super.apply(this, arguments);
  16123. }
  16124. CircleEase.prototype.easeInCore = function (gradient) {
  16125. gradient = Math.max(0, Math.min(1, gradient));
  16126. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  16127. };
  16128. return CircleEase;
  16129. })(EasingFunction);
  16130. BABYLON.CircleEase = CircleEase;
  16131. var BackEase = (function (_super) {
  16132. __extends(BackEase, _super);
  16133. function BackEase(amplitude) {
  16134. if (amplitude === void 0) { amplitude = 1; }
  16135. _super.call(this);
  16136. this.amplitude = amplitude;
  16137. }
  16138. BackEase.prototype.easeInCore = function (gradient) {
  16139. var num = Math.max(0, this.amplitude);
  16140. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  16141. };
  16142. return BackEase;
  16143. })(EasingFunction);
  16144. BABYLON.BackEase = BackEase;
  16145. var BounceEase = (function (_super) {
  16146. __extends(BounceEase, _super);
  16147. function BounceEase(bounces, bounciness) {
  16148. if (bounces === void 0) { bounces = 3; }
  16149. if (bounciness === void 0) { bounciness = 2; }
  16150. _super.call(this);
  16151. this.bounces = bounces;
  16152. this.bounciness = bounciness;
  16153. }
  16154. BounceEase.prototype.easeInCore = function (gradient) {
  16155. var y = Math.max(0.0, this.bounces);
  16156. var bounciness = this.bounciness;
  16157. if (bounciness <= 1.0) {
  16158. bounciness = 1.001;
  16159. }
  16160. var num9 = Math.pow(bounciness, y);
  16161. var num5 = 1.0 - bounciness;
  16162. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  16163. var num15 = gradient * num4;
  16164. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  16165. var num3 = Math.floor(num65);
  16166. var num13 = num3 + 1.0;
  16167. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  16168. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  16169. var num7 = (num8 + num12) * 0.5;
  16170. var num6 = gradient - num7;
  16171. var num2 = num7 - num8;
  16172. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  16173. };
  16174. return BounceEase;
  16175. })(EasingFunction);
  16176. BABYLON.BounceEase = BounceEase;
  16177. var CubicEase = (function (_super) {
  16178. __extends(CubicEase, _super);
  16179. function CubicEase() {
  16180. _super.apply(this, arguments);
  16181. }
  16182. CubicEase.prototype.easeInCore = function (gradient) {
  16183. return (gradient * gradient * gradient);
  16184. };
  16185. return CubicEase;
  16186. })(EasingFunction);
  16187. BABYLON.CubicEase = CubicEase;
  16188. var ElasticEase = (function (_super) {
  16189. __extends(ElasticEase, _super);
  16190. function ElasticEase(oscillations, springiness) {
  16191. if (oscillations === void 0) { oscillations = 3; }
  16192. if (springiness === void 0) { springiness = 3; }
  16193. _super.call(this);
  16194. this.oscillations = oscillations;
  16195. this.springiness = springiness;
  16196. }
  16197. ElasticEase.prototype.easeInCore = function (gradient) {
  16198. var num2;
  16199. var num3 = Math.max(0.0, this.oscillations);
  16200. var num = Math.max(0.0, this.springiness);
  16201. if (num == 0) {
  16202. num2 = gradient;
  16203. }
  16204. else {
  16205. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  16206. }
  16207. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  16208. };
  16209. return ElasticEase;
  16210. })(EasingFunction);
  16211. BABYLON.ElasticEase = ElasticEase;
  16212. var ExponentialEase = (function (_super) {
  16213. __extends(ExponentialEase, _super);
  16214. function ExponentialEase(exponent) {
  16215. if (exponent === void 0) { exponent = 2; }
  16216. _super.call(this);
  16217. this.exponent = exponent;
  16218. }
  16219. ExponentialEase.prototype.easeInCore = function (gradient) {
  16220. if (this.exponent <= 0) {
  16221. return gradient;
  16222. }
  16223. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  16224. };
  16225. return ExponentialEase;
  16226. })(EasingFunction);
  16227. BABYLON.ExponentialEase = ExponentialEase;
  16228. var PowerEase = (function (_super) {
  16229. __extends(PowerEase, _super);
  16230. function PowerEase(power) {
  16231. if (power === void 0) { power = 2; }
  16232. _super.call(this);
  16233. this.power = power;
  16234. }
  16235. PowerEase.prototype.easeInCore = function (gradient) {
  16236. var y = Math.max(0.0, this.power);
  16237. return Math.pow(gradient, y);
  16238. };
  16239. return PowerEase;
  16240. })(EasingFunction);
  16241. BABYLON.PowerEase = PowerEase;
  16242. var QuadraticEase = (function (_super) {
  16243. __extends(QuadraticEase, _super);
  16244. function QuadraticEase() {
  16245. _super.apply(this, arguments);
  16246. }
  16247. QuadraticEase.prototype.easeInCore = function (gradient) {
  16248. return (gradient * gradient);
  16249. };
  16250. return QuadraticEase;
  16251. })(EasingFunction);
  16252. BABYLON.QuadraticEase = QuadraticEase;
  16253. var QuarticEase = (function (_super) {
  16254. __extends(QuarticEase, _super);
  16255. function QuarticEase() {
  16256. _super.apply(this, arguments);
  16257. }
  16258. QuarticEase.prototype.easeInCore = function (gradient) {
  16259. return (gradient * gradient * gradient * gradient);
  16260. };
  16261. return QuarticEase;
  16262. })(EasingFunction);
  16263. BABYLON.QuarticEase = QuarticEase;
  16264. var QuinticEase = (function (_super) {
  16265. __extends(QuinticEase, _super);
  16266. function QuinticEase() {
  16267. _super.apply(this, arguments);
  16268. }
  16269. QuinticEase.prototype.easeInCore = function (gradient) {
  16270. return (gradient * gradient * gradient * gradient * gradient);
  16271. };
  16272. return QuinticEase;
  16273. })(EasingFunction);
  16274. BABYLON.QuinticEase = QuinticEase;
  16275. var SineEase = (function (_super) {
  16276. __extends(SineEase, _super);
  16277. function SineEase() {
  16278. _super.apply(this, arguments);
  16279. }
  16280. SineEase.prototype.easeInCore = function (gradient) {
  16281. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  16282. };
  16283. return SineEase;
  16284. })(EasingFunction);
  16285. BABYLON.SineEase = SineEase;
  16286. var BezierCurveEase = (function (_super) {
  16287. __extends(BezierCurveEase, _super);
  16288. function BezierCurveEase(x1, y1, x2, y2) {
  16289. if (x1 === void 0) { x1 = 0; }
  16290. if (y1 === void 0) { y1 = 0; }
  16291. if (x2 === void 0) { x2 = 1; }
  16292. if (y2 === void 0) { y2 = 1; }
  16293. _super.call(this);
  16294. this.x1 = x1;
  16295. this.y1 = y1;
  16296. this.x2 = x2;
  16297. this.y2 = y2;
  16298. }
  16299. BezierCurveEase.prototype.easeInCore = function (gradient) {
  16300. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  16301. };
  16302. return BezierCurveEase;
  16303. })(EasingFunction);
  16304. BABYLON.BezierCurveEase = BezierCurveEase;
  16305. })(BABYLON || (BABYLON = {}));
  16306. //# sourceMappingURL=babylon.easing.js.mapvar BABYLON;
  16307. (function (BABYLON) {
  16308. var Octree = (function () {
  16309. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  16310. if (maxDepth === void 0) { maxDepth = 2; }
  16311. this.maxDepth = maxDepth;
  16312. this.dynamicContent = new Array();
  16313. this._maxBlockCapacity = maxBlockCapacity || 64;
  16314. this._selectionContent = new BABYLON.SmartArray(1024);
  16315. this._creationFunc = creationFunc;
  16316. }
  16317. // Methods
  16318. Octree.prototype.update = function (worldMin, worldMax, entries) {
  16319. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  16320. };
  16321. Octree.prototype.addMesh = function (entry) {
  16322. for (var index = 0; index < this.blocks.length; index++) {
  16323. var block = this.blocks[index];
  16324. block.addEntry(entry);
  16325. }
  16326. };
  16327. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  16328. this._selectionContent.reset();
  16329. for (var index = 0; index < this.blocks.length; index++) {
  16330. var block = this.blocks[index];
  16331. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  16332. }
  16333. if (allowDuplicate) {
  16334. this._selectionContent.concat(this.dynamicContent);
  16335. }
  16336. else {
  16337. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16338. }
  16339. return this._selectionContent;
  16340. };
  16341. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  16342. this._selectionContent.reset();
  16343. for (var index = 0; index < this.blocks.length; index++) {
  16344. var block = this.blocks[index];
  16345. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  16346. }
  16347. if (allowDuplicate) {
  16348. this._selectionContent.concat(this.dynamicContent);
  16349. }
  16350. else {
  16351. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16352. }
  16353. return this._selectionContent;
  16354. };
  16355. Octree.prototype.intersectsRay = function (ray) {
  16356. this._selectionContent.reset();
  16357. for (var index = 0; index < this.blocks.length; index++) {
  16358. var block = this.blocks[index];
  16359. block.intersectsRay(ray, this._selectionContent);
  16360. }
  16361. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  16362. return this._selectionContent;
  16363. };
  16364. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  16365. target.blocks = new Array();
  16366. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  16367. for (var x = 0; x < 2; x++) {
  16368. for (var y = 0; y < 2; y++) {
  16369. for (var z = 0; z < 2; z++) {
  16370. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  16371. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  16372. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  16373. block.addEntries(entries);
  16374. target.blocks.push(block);
  16375. }
  16376. }
  16377. }
  16378. };
  16379. Octree.CreationFuncForMeshes = function (entry, block) {
  16380. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16381. block.entries.push(entry);
  16382. }
  16383. };
  16384. Octree.CreationFuncForSubMeshes = function (entry, block) {
  16385. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  16386. block.entries.push(entry);
  16387. }
  16388. };
  16389. return Octree;
  16390. })();
  16391. BABYLON.Octree = Octree;
  16392. })(BABYLON || (BABYLON = {}));
  16393. //# sourceMappingURL=babylon.octree.js.mapvar BABYLON;
  16394. (function (BABYLON) {
  16395. var OctreeBlock = (function () {
  16396. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  16397. this.entries = new Array();
  16398. this._boundingVectors = new Array();
  16399. this._capacity = capacity;
  16400. this._depth = depth;
  16401. this._maxDepth = maxDepth;
  16402. this._creationFunc = creationFunc;
  16403. this._minPoint = minPoint;
  16404. this._maxPoint = maxPoint;
  16405. this._boundingVectors.push(minPoint.clone());
  16406. this._boundingVectors.push(maxPoint.clone());
  16407. this._boundingVectors.push(minPoint.clone());
  16408. this._boundingVectors[2].x = maxPoint.x;
  16409. this._boundingVectors.push(minPoint.clone());
  16410. this._boundingVectors[3].y = maxPoint.y;
  16411. this._boundingVectors.push(minPoint.clone());
  16412. this._boundingVectors[4].z = maxPoint.z;
  16413. this._boundingVectors.push(maxPoint.clone());
  16414. this._boundingVectors[5].z = minPoint.z;
  16415. this._boundingVectors.push(maxPoint.clone());
  16416. this._boundingVectors[6].x = minPoint.x;
  16417. this._boundingVectors.push(maxPoint.clone());
  16418. this._boundingVectors[7].y = minPoint.y;
  16419. }
  16420. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  16421. // Property
  16422. get: function () {
  16423. return this._capacity;
  16424. },
  16425. enumerable: true,
  16426. configurable: true
  16427. });
  16428. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  16429. get: function () {
  16430. return this._minPoint;
  16431. },
  16432. enumerable: true,
  16433. configurable: true
  16434. });
  16435. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  16436. get: function () {
  16437. return this._maxPoint;
  16438. },
  16439. enumerable: true,
  16440. configurable: true
  16441. });
  16442. // Methods
  16443. OctreeBlock.prototype.addEntry = function (entry) {
  16444. if (this.blocks) {
  16445. for (var index = 0; index < this.blocks.length; index++) {
  16446. var block = this.blocks[index];
  16447. block.addEntry(entry);
  16448. }
  16449. return;
  16450. }
  16451. this._creationFunc(entry, this);
  16452. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  16453. this.createInnerBlocks();
  16454. }
  16455. };
  16456. OctreeBlock.prototype.addEntries = function (entries) {
  16457. for (var index = 0; index < entries.length; index++) {
  16458. var mesh = entries[index];
  16459. this.addEntry(mesh);
  16460. }
  16461. };
  16462. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  16463. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  16464. if (this.blocks) {
  16465. for (var index = 0; index < this.blocks.length; index++) {
  16466. var block = this.blocks[index];
  16467. block.select(frustumPlanes, selection, allowDuplicate);
  16468. }
  16469. return;
  16470. }
  16471. if (allowDuplicate) {
  16472. selection.concat(this.entries);
  16473. }
  16474. else {
  16475. selection.concatWithNoDuplicate(this.entries);
  16476. }
  16477. }
  16478. };
  16479. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  16480. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  16481. if (this.blocks) {
  16482. for (var index = 0; index < this.blocks.length; index++) {
  16483. var block = this.blocks[index];
  16484. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  16485. }
  16486. return;
  16487. }
  16488. if (allowDuplicate) {
  16489. selection.concat(this.entries);
  16490. }
  16491. else {
  16492. selection.concatWithNoDuplicate(this.entries);
  16493. }
  16494. }
  16495. };
  16496. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  16497. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  16498. if (this.blocks) {
  16499. for (var index = 0; index < this.blocks.length; index++) {
  16500. var block = this.blocks[index];
  16501. block.intersectsRay(ray, selection);
  16502. }
  16503. return;
  16504. }
  16505. selection.concatWithNoDuplicate(this.entries);
  16506. }
  16507. };
  16508. OctreeBlock.prototype.createInnerBlocks = function () {
  16509. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  16510. };
  16511. return OctreeBlock;
  16512. })();
  16513. BABYLON.OctreeBlock = OctreeBlock;
  16514. })(BABYLON || (BABYLON = {}));
  16515. //# sourceMappingURL=babylon.octreeBlock.js.mapvar BABYLON;
  16516. (function (BABYLON) {
  16517. var Bone = (function () {
  16518. function Bone(name, skeleton, parentBone, matrix) {
  16519. this.name = name;
  16520. this.children = new Array();
  16521. this.animations = new Array();
  16522. this._worldTransform = new BABYLON.Matrix();
  16523. this._absoluteTransform = new BABYLON.Matrix();
  16524. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  16525. this._skeleton = skeleton;
  16526. this._matrix = matrix;
  16527. this._baseMatrix = matrix;
  16528. skeleton.bones.push(this);
  16529. if (parentBone) {
  16530. this._parent = parentBone;
  16531. parentBone.children.push(this);
  16532. }
  16533. else {
  16534. this._parent = null;
  16535. }
  16536. this._updateDifferenceMatrix();
  16537. }
  16538. // Members
  16539. Bone.prototype.getParent = function () {
  16540. return this._parent;
  16541. };
  16542. Bone.prototype.getLocalMatrix = function () {
  16543. return this._matrix;
  16544. };
  16545. Bone.prototype.getBaseMatrix = function () {
  16546. return this._baseMatrix;
  16547. };
  16548. Bone.prototype.getWorldMatrix = function () {
  16549. return this._worldTransform;
  16550. };
  16551. Bone.prototype.getInvertedAbsoluteTransform = function () {
  16552. return this._invertedAbsoluteTransform;
  16553. };
  16554. Bone.prototype.getAbsoluteMatrix = function () {
  16555. var matrix = this._matrix.clone();
  16556. var parent = this._parent;
  16557. while (parent) {
  16558. matrix = matrix.multiply(parent.getLocalMatrix());
  16559. parent = parent.getParent();
  16560. }
  16561. return matrix;
  16562. };
  16563. // Methods
  16564. Bone.prototype.updateMatrix = function (matrix) {
  16565. this._matrix = matrix;
  16566. this._skeleton._markAsDirty();
  16567. this._updateDifferenceMatrix();
  16568. };
  16569. Bone.prototype._updateDifferenceMatrix = function () {
  16570. if (this._parent) {
  16571. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  16572. }
  16573. else {
  16574. this._absoluteTransform.copyFrom(this._matrix);
  16575. }
  16576. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  16577. for (var index = 0; index < this.children.length; index++) {
  16578. this.children[index]._updateDifferenceMatrix();
  16579. }
  16580. };
  16581. Bone.prototype.markAsDirty = function () {
  16582. this._skeleton._markAsDirty();
  16583. };
  16584. return Bone;
  16585. })();
  16586. BABYLON.Bone = Bone;
  16587. })(BABYLON || (BABYLON = {}));
  16588. //# sourceMappingURL=babylon.bone.js.mapvar BABYLON;
  16589. (function (BABYLON) {
  16590. var Skeleton = (function () {
  16591. function Skeleton(name, id, scene) {
  16592. this.name = name;
  16593. this.id = id;
  16594. this.bones = new Array();
  16595. this._isDirty = true;
  16596. this._identity = BABYLON.Matrix.Identity();
  16597. this.bones = [];
  16598. this._scene = scene;
  16599. scene.skeletons.push(this);
  16600. }
  16601. // Members
  16602. Skeleton.prototype.getTransformMatrices = function () {
  16603. return this._transformMatrices;
  16604. };
  16605. // Methods
  16606. Skeleton.prototype._markAsDirty = function () {
  16607. this._isDirty = true;
  16608. };
  16609. Skeleton.prototype.prepare = function () {
  16610. if (!this._isDirty) {
  16611. return;
  16612. }
  16613. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  16614. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  16615. }
  16616. for (var index = 0; index < this.bones.length; index++) {
  16617. var bone = this.bones[index];
  16618. var parentBone = bone.getParent();
  16619. if (parentBone) {
  16620. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  16621. }
  16622. else {
  16623. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  16624. }
  16625. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), this._transformMatrices, index * 16);
  16626. }
  16627. this._identity.copyToArray(this._transformMatrices, this.bones.length * 16);
  16628. this._isDirty = false;
  16629. this._scene._activeBones += this.bones.length;
  16630. };
  16631. Skeleton.prototype.getAnimatables = function () {
  16632. if (!this._animatables || this._animatables.length !== this.bones.length) {
  16633. this._animatables = [];
  16634. for (var index = 0; index < this.bones.length; index++) {
  16635. this._animatables.push(this.bones[index]);
  16636. }
  16637. }
  16638. return this._animatables;
  16639. };
  16640. Skeleton.prototype.clone = function (name, id) {
  16641. var result = new Skeleton(name, id || name, this._scene);
  16642. for (var index = 0; index < this.bones.length; index++) {
  16643. var source = this.bones[index];
  16644. var parentBone = null;
  16645. if (source.getParent()) {
  16646. var parentIndex = this.bones.indexOf(source.getParent());
  16647. parentBone = result.bones[parentIndex];
  16648. }
  16649. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix());
  16650. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  16651. }
  16652. return result;
  16653. };
  16654. return Skeleton;
  16655. })();
  16656. BABYLON.Skeleton = Skeleton;
  16657. })(BABYLON || (BABYLON = {}));
  16658. //# sourceMappingURL=babylon.skeleton.js.mapvar BABYLON;
  16659. (function (BABYLON) {
  16660. var PostProcess = (function () {
  16661. function PostProcess(name, fragmentUrl, parameters, samplers, ratio, camera, samplingMode, engine, reusable, defines) {
  16662. this.name = name;
  16663. this.width = -1;
  16664. this.height = -1;
  16665. this._reusable = false;
  16666. this._textures = new BABYLON.SmartArray(2);
  16667. this._currentRenderTextureInd = 0;
  16668. if (camera != null) {
  16669. this._camera = camera;
  16670. this._scene = camera.getScene();
  16671. camera.attachPostProcess(this);
  16672. this._engine = this._scene.getEngine();
  16673. }
  16674. else {
  16675. this._engine = engine;
  16676. }
  16677. this._renderRatio = ratio;
  16678. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  16679. this._reusable = reusable || false;
  16680. samplers = samplers || [];
  16681. samplers.push("textureSampler");
  16682. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: fragmentUrl }, ["position"], parameters || [], samplers, defines !== undefined ? defines : "");
  16683. }
  16684. PostProcess.prototype.isReusable = function () {
  16685. return this._reusable;
  16686. };
  16687. PostProcess.prototype.activate = function (camera, sourceTexture) {
  16688. camera = camera || this._camera;
  16689. var scene = camera.getScene();
  16690. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  16691. var desiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._renderRatio) | 0;
  16692. var desiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._renderRatio) | 0;
  16693. desiredWidth = BABYLON.Tools.GetExponantOfTwo(desiredWidth, maxSize);
  16694. desiredHeight = BABYLON.Tools.GetExponantOfTwo(desiredHeight, maxSize);
  16695. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  16696. if (this._textures.length > 0) {
  16697. for (var i = 0; i < this._textures.length; i++) {
  16698. this._engine._releaseTexture(this._textures.data[i]);
  16699. }
  16700. this._textures.reset();
  16701. }
  16702. this.width = desiredWidth;
  16703. this.height = desiredHeight;
  16704. 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 }));
  16705. if (this._reusable) {
  16706. 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 }));
  16707. }
  16708. if (this.onSizeChanged) {
  16709. this.onSizeChanged();
  16710. }
  16711. }
  16712. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  16713. if (this.onActivate) {
  16714. this.onActivate(camera);
  16715. }
  16716. // Clear
  16717. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true);
  16718. if (this._reusable) {
  16719. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  16720. }
  16721. };
  16722. PostProcess.prototype.apply = function () {
  16723. // Check
  16724. if (!this._effect.isReady())
  16725. return null;
  16726. // States
  16727. this._engine.enableEffect(this._effect);
  16728. this._engine.setState(false);
  16729. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16730. this._engine.setDepthBuffer(false);
  16731. this._engine.setDepthWrite(false);
  16732. // Texture
  16733. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  16734. // Parameters
  16735. if (this.onApply) {
  16736. this.onApply(this._effect);
  16737. }
  16738. return this._effect;
  16739. };
  16740. PostProcess.prototype.dispose = function (camera) {
  16741. camera = camera || this._camera;
  16742. if (this._textures.length > 0) {
  16743. for (var i = 0; i < this._textures.length; i++) {
  16744. this._engine._releaseTexture(this._textures.data[i]);
  16745. }
  16746. this._textures.reset();
  16747. }
  16748. camera.detachPostProcess(this);
  16749. var index = camera._postProcesses.indexOf(this);
  16750. if (index === camera._postProcessesTakenIndices[0] && camera._postProcessesTakenIndices.length > 0) {
  16751. this._camera._postProcesses[camera._postProcessesTakenIndices[0]].width = -1; // invalidate frameBuffer to hint the postprocess to create a depth buffer
  16752. }
  16753. };
  16754. return PostProcess;
  16755. })();
  16756. BABYLON.PostProcess = PostProcess;
  16757. })(BABYLON || (BABYLON = {}));
  16758. //# sourceMappingURL=babylon.postProcess.js.mapvar BABYLON;
  16759. (function (BABYLON) {
  16760. var PostProcessManager = (function () {
  16761. function PostProcessManager(scene) {
  16762. this._vertexDeclaration = [2];
  16763. this._vertexStrideSize = 2 * 4;
  16764. this._scene = scene;
  16765. // VBO
  16766. var vertices = [];
  16767. vertices.push(1, 1);
  16768. vertices.push(-1, 1);
  16769. vertices.push(-1, -1);
  16770. vertices.push(1, -1);
  16771. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  16772. // Indices
  16773. var indices = [];
  16774. indices.push(0);
  16775. indices.push(1);
  16776. indices.push(2);
  16777. indices.push(0);
  16778. indices.push(2);
  16779. indices.push(3);
  16780. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  16781. }
  16782. // Methods
  16783. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  16784. var postProcesses = this._scene.activeCamera._postProcesses;
  16785. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16786. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16787. return false;
  16788. }
  16789. postProcesses[this._scene.activeCamera._postProcessesTakenIndices[0]].activate(this._scene.activeCamera, sourceTexture);
  16790. return true;
  16791. };
  16792. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture) {
  16793. var postProcesses = this._scene.activeCamera._postProcesses;
  16794. var postProcessesTakenIndices = this._scene.activeCamera._postProcessesTakenIndices;
  16795. if (postProcessesTakenIndices.length === 0 || !this._scene.postProcessesEnabled) {
  16796. return;
  16797. }
  16798. var engine = this._scene.getEngine();
  16799. for (var index = 0; index < postProcessesTakenIndices.length; index++) {
  16800. if (index < postProcessesTakenIndices.length - 1) {
  16801. postProcesses[postProcessesTakenIndices[index + 1]].activate(this._scene.activeCamera);
  16802. }
  16803. else {
  16804. if (targetTexture) {
  16805. engine.bindFramebuffer(targetTexture);
  16806. }
  16807. else {
  16808. engine.restoreDefaultFramebuffer();
  16809. }
  16810. }
  16811. if (doNotPresent) {
  16812. break;
  16813. }
  16814. var pp = postProcesses[postProcessesTakenIndices[index]];
  16815. var effect = pp.apply();
  16816. if (effect) {
  16817. if (pp.onBeforeRender) {
  16818. pp.onBeforeRender(effect);
  16819. }
  16820. // VBOs
  16821. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, effect);
  16822. // Draw order
  16823. engine.draw(true, 0, 6);
  16824. }
  16825. }
  16826. // Restore depth buffer
  16827. engine.setDepthBuffer(true);
  16828. engine.setDepthWrite(true);
  16829. };
  16830. PostProcessManager.prototype.dispose = function () {
  16831. if (this._vertexBuffer) {
  16832. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  16833. this._vertexBuffer = null;
  16834. }
  16835. if (this._indexBuffer) {
  16836. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  16837. this._indexBuffer = null;
  16838. }
  16839. };
  16840. return PostProcessManager;
  16841. })();
  16842. BABYLON.PostProcessManager = PostProcessManager;
  16843. })(BABYLON || (BABYLON = {}));
  16844. //# sourceMappingURL=babylon.postProcessManager.js.map
  16845. var BABYLON;
  16846. (function (BABYLON) {
  16847. var PassPostProcess = (function (_super) {
  16848. __extends(PassPostProcess, _super);
  16849. function PassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16850. _super.call(this, name, "pass", null, null, ratio, camera, samplingMode, engine, reusable);
  16851. }
  16852. return PassPostProcess;
  16853. })(BABYLON.PostProcess);
  16854. BABYLON.PassPostProcess = PassPostProcess;
  16855. })(BABYLON || (BABYLON = {}));
  16856. //# sourceMappingURL=babylon.passPostProcess.js.map
  16857. var BABYLON;
  16858. (function (BABYLON) {
  16859. var BlurPostProcess = (function (_super) {
  16860. __extends(BlurPostProcess, _super);
  16861. function BlurPostProcess(name, direction, blurWidth, ratio, camera, samplingMode, engine, reusable) {
  16862. var _this = this;
  16863. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  16864. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, ratio, camera, samplingMode, engine, reusable);
  16865. this.direction = direction;
  16866. this.blurWidth = blurWidth;
  16867. this.onApply = function (effect) {
  16868. effect.setFloat2("screenSize", _this.width, _this.height);
  16869. effect.setVector2("direction", _this.direction);
  16870. effect.setFloat("blurWidth", _this.blurWidth);
  16871. };
  16872. }
  16873. return BlurPostProcess;
  16874. })(BABYLON.PostProcess);
  16875. BABYLON.BlurPostProcess = BlurPostProcess;
  16876. })(BABYLON || (BABYLON = {}));
  16877. //# sourceMappingURL=babylon.blurPostProcess.js.map
  16878. var BABYLON;
  16879. (function (BABYLON) {
  16880. var FilterPostProcess = (function (_super) {
  16881. __extends(FilterPostProcess, _super);
  16882. function FilterPostProcess(name, kernelMatrix, ratio, camera, samplingMode, engine, reusable) {
  16883. var _this = this;
  16884. _super.call(this, name, "filter", ["kernelMatrix"], null, ratio, camera, samplingMode, engine, reusable);
  16885. this.kernelMatrix = kernelMatrix;
  16886. this.onApply = function (effect) {
  16887. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  16888. };
  16889. }
  16890. return FilterPostProcess;
  16891. })(BABYLON.PostProcess);
  16892. BABYLON.FilterPostProcess = FilterPostProcess;
  16893. })(BABYLON || (BABYLON = {}));
  16894. //# sourceMappingURL=babylon.filterPostProcess.js.map
  16895. var BABYLON;
  16896. (function (BABYLON) {
  16897. var RefractionPostProcess = (function (_super) {
  16898. __extends(RefractionPostProcess, _super);
  16899. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, ratio, camera, samplingMode, engine, reusable) {
  16900. var _this = this;
  16901. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], ratio, camera, samplingMode, engine, reusable);
  16902. this.color = color;
  16903. this.depth = depth;
  16904. this.colorLevel = colorLevel;
  16905. this.onActivate = function (cam) {
  16906. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  16907. };
  16908. this.onApply = function (effect) {
  16909. effect.setColor3("baseColor", _this.color);
  16910. effect.setFloat("depth", _this.depth);
  16911. effect.setFloat("colorLevel", _this.colorLevel);
  16912. effect.setTexture("refractionSampler", _this._refRexture);
  16913. };
  16914. }
  16915. // Methods
  16916. RefractionPostProcess.prototype.dispose = function (camera) {
  16917. if (this._refRexture) {
  16918. this._refRexture.dispose();
  16919. }
  16920. _super.prototype.dispose.call(this, camera);
  16921. };
  16922. return RefractionPostProcess;
  16923. })(BABYLON.PostProcess);
  16924. BABYLON.RefractionPostProcess = RefractionPostProcess;
  16925. })(BABYLON || (BABYLON = {}));
  16926. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  16927. var BABYLON;
  16928. (function (BABYLON) {
  16929. var BlackAndWhitePostProcess = (function (_super) {
  16930. __extends(BlackAndWhitePostProcess, _super);
  16931. function BlackAndWhitePostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16932. _super.call(this, name, "blackAndWhite", null, null, ratio, camera, samplingMode, engine, reusable);
  16933. }
  16934. return BlackAndWhitePostProcess;
  16935. })(BABYLON.PostProcess);
  16936. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  16937. })(BABYLON || (BABYLON = {}));
  16938. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  16939. var BABYLON;
  16940. (function (BABYLON) {
  16941. var ConvolutionPostProcess = (function (_super) {
  16942. __extends(ConvolutionPostProcess, _super);
  16943. function ConvolutionPostProcess(name, kernel, ratio, camera, samplingMode, engine, reusable) {
  16944. var _this = this;
  16945. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, ratio, camera, samplingMode, engine, reusable);
  16946. this.kernel = kernel;
  16947. this.onApply = function (effect) {
  16948. effect.setFloat2("screenSize", _this.width, _this.height);
  16949. effect.setArray("kernel", _this.kernel);
  16950. };
  16951. }
  16952. // Statics
  16953. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  16954. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  16955. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  16956. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  16957. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  16958. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  16959. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  16960. return ConvolutionPostProcess;
  16961. })(BABYLON.PostProcess);
  16962. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  16963. })(BABYLON || (BABYLON = {}));
  16964. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  16965. var BABYLON;
  16966. (function (BABYLON) {
  16967. var FxaaPostProcess = (function (_super) {
  16968. __extends(FxaaPostProcess, _super);
  16969. function FxaaPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  16970. var _this = this;
  16971. _super.call(this, name, "fxaa", ["texelSize"], null, ratio, camera, samplingMode, engine, reusable);
  16972. this.onSizeChanged = function () {
  16973. _this.texelWidth = 1.0 / _this.width;
  16974. _this.texelHeight = 1.0 / _this.height;
  16975. };
  16976. this.onApply = function (effect) {
  16977. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  16978. };
  16979. }
  16980. return FxaaPostProcess;
  16981. })(BABYLON.PostProcess);
  16982. BABYLON.FxaaPostProcess = FxaaPostProcess;
  16983. })(BABYLON || (BABYLON = {}));
  16984. //# sourceMappingURL=babylon.fxaaPostProcess.js.mapvar BABYLON;
  16985. (function (BABYLON) {
  16986. var LensFlare = (function () {
  16987. function LensFlare(size, position, color, imgUrl, system) {
  16988. this.size = size;
  16989. this.position = position;
  16990. this.dispose = function () {
  16991. if (this.texture) {
  16992. this.texture.dispose();
  16993. }
  16994. // Remove from scene
  16995. var index = this._system.lensFlares.indexOf(this);
  16996. this._system.lensFlares.splice(index, 1);
  16997. };
  16998. this.color = color || new BABYLON.Color3(1, 1, 1);
  16999. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  17000. this._system = system;
  17001. system.lensFlares.push(this);
  17002. }
  17003. return LensFlare;
  17004. })();
  17005. BABYLON.LensFlare = LensFlare;
  17006. })(BABYLON || (BABYLON = {}));
  17007. //# sourceMappingURL=babylon.lensFlare.js.mapvar BABYLON;
  17008. (function (BABYLON) {
  17009. var LensFlareSystem = (function () {
  17010. function LensFlareSystem(name, emitter, scene) {
  17011. this.name = name;
  17012. this.lensFlares = new Array();
  17013. this.borderLimit = 300;
  17014. this._vertexDeclaration = [2];
  17015. this._vertexStrideSize = 2 * 4;
  17016. this._isEnabled = true;
  17017. this._scene = scene;
  17018. this._emitter = emitter;
  17019. scene.lensFlareSystems.push(this);
  17020. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  17021. // VBO
  17022. var vertices = [];
  17023. vertices.push(1, 1);
  17024. vertices.push(-1, 1);
  17025. vertices.push(-1, -1);
  17026. vertices.push(1, -1);
  17027. this._vertexBuffer = scene.getEngine().createVertexBuffer(vertices);
  17028. // Indices
  17029. var indices = [];
  17030. indices.push(0);
  17031. indices.push(1);
  17032. indices.push(2);
  17033. indices.push(0);
  17034. indices.push(2);
  17035. indices.push(3);
  17036. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  17037. // Effects
  17038. this._effect = this._scene.getEngine().createEffect("lensFlare", ["position"], ["color", "viewportMatrix"], ["textureSampler"], "");
  17039. }
  17040. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  17041. get: function () {
  17042. return this._isEnabled;
  17043. },
  17044. set: function (value) {
  17045. this._isEnabled = value;
  17046. },
  17047. enumerable: true,
  17048. configurable: true
  17049. });
  17050. LensFlareSystem.prototype.getScene = function () {
  17051. return this._scene;
  17052. };
  17053. LensFlareSystem.prototype.getEmitter = function () {
  17054. return this._emitter;
  17055. };
  17056. LensFlareSystem.prototype.getEmitterPosition = function () {
  17057. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  17058. };
  17059. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  17060. var position = this.getEmitterPosition();
  17061. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  17062. this._positionX = position.x;
  17063. this._positionY = position.y;
  17064. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  17065. if (position.z > 0) {
  17066. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  17067. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  17068. return true;
  17069. }
  17070. }
  17071. return false;
  17072. };
  17073. LensFlareSystem.prototype._isVisible = function () {
  17074. if (!this._isEnabled) {
  17075. return false;
  17076. }
  17077. var emitterPosition = this.getEmitterPosition();
  17078. var direction = emitterPosition.subtract(this._scene.activeCamera.position);
  17079. var distance = direction.length();
  17080. direction.normalize();
  17081. var ray = new BABYLON.Ray(this._scene.activeCamera.position, direction);
  17082. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  17083. return !pickInfo.hit || pickInfo.distance > distance;
  17084. };
  17085. LensFlareSystem.prototype.render = function () {
  17086. if (!this._effect.isReady())
  17087. return false;
  17088. var engine = this._scene.getEngine();
  17089. var viewport = this._scene.activeCamera.viewport;
  17090. var globalViewport = viewport.toGlobal(engine);
  17091. // Position
  17092. if (!this.computeEffectivePosition(globalViewport)) {
  17093. return false;
  17094. }
  17095. // Visibility
  17096. if (!this._isVisible()) {
  17097. return false;
  17098. }
  17099. // Intensity
  17100. var awayX;
  17101. var awayY;
  17102. if (this._positionX < this.borderLimit + globalViewport.x) {
  17103. awayX = this.borderLimit + globalViewport.x - this._positionX;
  17104. }
  17105. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  17106. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  17107. }
  17108. else {
  17109. awayX = 0;
  17110. }
  17111. if (this._positionY < this.borderLimit + globalViewport.y) {
  17112. awayY = this.borderLimit + globalViewport.y - this._positionY;
  17113. }
  17114. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  17115. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  17116. }
  17117. else {
  17118. awayY = 0;
  17119. }
  17120. var away = (awayX > awayY) ? awayX : awayY;
  17121. if (away > this.borderLimit) {
  17122. away = this.borderLimit;
  17123. }
  17124. var intensity = 1.0 - (away / this.borderLimit);
  17125. if (intensity < 0) {
  17126. return false;
  17127. }
  17128. if (intensity > 1.0) {
  17129. intensity = 1.0;
  17130. }
  17131. // Position
  17132. var centerX = globalViewport.x + globalViewport.width / 2;
  17133. var centerY = globalViewport.y + globalViewport.height / 2;
  17134. var distX = centerX - this._positionX;
  17135. var distY = centerY - this._positionY;
  17136. // Effects
  17137. engine.enableEffect(this._effect);
  17138. engine.setState(false);
  17139. engine.setDepthBuffer(false);
  17140. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  17141. // VBOs
  17142. engine.bindBuffers(this._vertexBuffer, this._indexBuffer, this._vertexDeclaration, this._vertexStrideSize, this._effect);
  17143. for (var index = 0; index < this.lensFlares.length; index++) {
  17144. var flare = this.lensFlares[index];
  17145. var x = centerX - (distX * flare.position);
  17146. var y = centerY - (distY * flare.position);
  17147. var cw = flare.size;
  17148. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera);
  17149. var cx = 2 * (x / globalViewport.width) - 1.0;
  17150. var cy = 1.0 - 2 * (y / globalViewport.height);
  17151. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  17152. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  17153. // Texture
  17154. this._effect.setTexture("textureSampler", flare.texture);
  17155. // Color
  17156. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  17157. // Draw order
  17158. engine.draw(true, 0, 6);
  17159. }
  17160. engine.setDepthBuffer(true);
  17161. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17162. return true;
  17163. };
  17164. LensFlareSystem.prototype.dispose = function () {
  17165. if (this._vertexBuffer) {
  17166. this._scene.getEngine()._releaseBuffer(this._vertexBuffer);
  17167. this._vertexBuffer = null;
  17168. }
  17169. if (this._indexBuffer) {
  17170. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  17171. this._indexBuffer = null;
  17172. }
  17173. while (this.lensFlares.length) {
  17174. this.lensFlares[0].dispose();
  17175. }
  17176. // Remove from scene
  17177. var index = this._scene.lensFlareSystems.indexOf(this);
  17178. this._scene.lensFlareSystems.splice(index, 1);
  17179. };
  17180. return LensFlareSystem;
  17181. })();
  17182. BABYLON.LensFlareSystem = LensFlareSystem;
  17183. })(BABYLON || (BABYLON = {}));
  17184. //# sourceMappingURL=babylon.lensFlareSystem.js.mapvar BABYLON;
  17185. (function (BABYLON) {
  17186. var IntersectionInfo = (function () {
  17187. function IntersectionInfo(bu, bv, distance) {
  17188. this.bu = bu;
  17189. this.bv = bv;
  17190. this.distance = distance;
  17191. this.faceId = 0;
  17192. this.subMeshId = 0;
  17193. }
  17194. return IntersectionInfo;
  17195. })();
  17196. BABYLON.IntersectionInfo = IntersectionInfo;
  17197. var PickingInfo = (function () {
  17198. function PickingInfo() {
  17199. this.hit = false;
  17200. this.distance = 0;
  17201. this.pickedPoint = null;
  17202. this.pickedMesh = null;
  17203. this.bu = 0;
  17204. this.bv = 0;
  17205. this.faceId = -1;
  17206. this.subMeshId = 0;
  17207. }
  17208. // Methods
  17209. PickingInfo.prototype.getNormal = function () {
  17210. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  17211. return null;
  17212. }
  17213. var indices = this.pickedMesh.getIndices();
  17214. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  17215. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  17216. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  17217. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  17218. normal0 = normal0.scale(this.bu);
  17219. normal1 = normal1.scale(this.bv);
  17220. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  17221. return new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  17222. };
  17223. PickingInfo.prototype.getTextureCoordinates = function () {
  17224. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  17225. return null;
  17226. }
  17227. var indices = this.pickedMesh.getIndices();
  17228. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  17229. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  17230. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  17231. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  17232. uv0 = uv0.scale(this.bu);
  17233. uv1 = uv1.scale(this.bv);
  17234. uv2 = uv2.scale(1.0 - this.bu - this.bv);
  17235. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  17236. };
  17237. return PickingInfo;
  17238. })();
  17239. BABYLON.PickingInfo = PickingInfo;
  17240. })(BABYLON || (BABYLON = {}));
  17241. //# sourceMappingURL=babylon.pickingInfo.js.mapvar BABYLON;
  17242. (function (BABYLON) {
  17243. var FilesInput = (function () {
  17244. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  17245. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  17246. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  17247. this._engine = p_engine;
  17248. this._canvas = p_canvas;
  17249. this._currentScene = p_scene;
  17250. this._sceneLoadedCallback = p_sceneLoadedCallback;
  17251. this._progressCallback = p_progressCallback;
  17252. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  17253. this._textureLoadingCallback = p_textureLoadingCallback;
  17254. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  17255. }
  17256. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  17257. var _this = this;
  17258. if (p_elementToMonitor) {
  17259. this._elementToMonitor = p_elementToMonitor;
  17260. this._elementToMonitor.addEventListener("dragenter", function (e) {
  17261. _this.drag(e);
  17262. }, false);
  17263. this._elementToMonitor.addEventListener("dragover", function (e) {
  17264. _this.drag(e);
  17265. }, false);
  17266. this._elementToMonitor.addEventListener("drop", function (e) {
  17267. _this.drop(e);
  17268. }, false);
  17269. }
  17270. };
  17271. FilesInput.prototype.renderFunction = function () {
  17272. if (this._additionnalRenderLoopLogicCallback) {
  17273. this._additionnalRenderLoopLogicCallback();
  17274. }
  17275. if (this._currentScene) {
  17276. if (this._textureLoadingCallback) {
  17277. var remaining = this._currentScene.getWaitingItemsCount();
  17278. if (remaining > 0) {
  17279. this._textureLoadingCallback(remaining);
  17280. }
  17281. }
  17282. this._currentScene.render();
  17283. }
  17284. };
  17285. FilesInput.prototype.drag = function (e) {
  17286. e.stopPropagation();
  17287. e.preventDefault();
  17288. };
  17289. FilesInput.prototype.drop = function (eventDrop) {
  17290. eventDrop.stopPropagation();
  17291. eventDrop.preventDefault();
  17292. this.loadFiles(eventDrop);
  17293. };
  17294. FilesInput.prototype.loadFiles = function (event) {
  17295. if (this._startingProcessingFilesCallback)
  17296. this._startingProcessingFilesCallback();
  17297. // Handling data transfer via drag'n'drop
  17298. if (event && event.dataTransfer && event.dataTransfer.files) {
  17299. this._filesToLoad = event.dataTransfer.files;
  17300. }
  17301. // Handling files from input files
  17302. if (event && event.target && event.target.files) {
  17303. this._filesToLoad = event.target.files;
  17304. }
  17305. if (this._filesToLoad && this._filesToLoad.length > 0) {
  17306. for (var i = 0; i < this._filesToLoad.length; i++) {
  17307. switch (this._filesToLoad[i].type) {
  17308. case "image/jpeg":
  17309. case "image/png":
  17310. case "image/bmp":
  17311. FilesInput.FilesTextures[this._filesToLoad[i].name] = this._filesToLoad[i];
  17312. break;
  17313. case "image/targa":
  17314. case "image/vnd.ms-dds":
  17315. case "audio/wav":
  17316. case "audio/x-wav":
  17317. case "audio/mp3":
  17318. case "audio/mpeg":
  17319. case "audio/mpeg3":
  17320. case "audio/x-mpeg-3":
  17321. case "audio/ogg":
  17322. FilesInput.FilesToLoad[this._filesToLoad[i].name] = this._filesToLoad[i];
  17323. break;
  17324. default:
  17325. 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) {
  17326. this._sceneFileToLoad = this._filesToLoad[i];
  17327. }
  17328. break;
  17329. }
  17330. }
  17331. this.reload();
  17332. }
  17333. };
  17334. FilesInput.prototype.reload = function () {
  17335. var _this = this;
  17336. var that = this;
  17337. // If a ".babylon" file has been provided
  17338. if (this._sceneFileToLoad) {
  17339. if (this._currentScene) {
  17340. this._engine.stopRenderLoop();
  17341. this._currentScene.dispose();
  17342. }
  17343. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  17344. that._currentScene = newScene;
  17345. // Wait for textures and shaders to be ready
  17346. that._currentScene.executeWhenReady(function () {
  17347. // Attach camera to canvas inputs
  17348. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  17349. that._currentScene.createDefaultCameraOrLight();
  17350. }
  17351. that._currentScene.activeCamera.attachControl(that._canvas);
  17352. if (that._sceneLoadedCallback) {
  17353. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  17354. }
  17355. that._engine.runRenderLoop(function () {
  17356. that.renderFunction();
  17357. });
  17358. });
  17359. }, function (progress) {
  17360. if (_this._progressCallback) {
  17361. _this._progressCallback(progress);
  17362. }
  17363. });
  17364. }
  17365. else {
  17366. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  17367. }
  17368. };
  17369. FilesInput.FilesTextures = new Array();
  17370. FilesInput.FilesToLoad = new Array();
  17371. return FilesInput;
  17372. })();
  17373. BABYLON.FilesInput = FilesInput;
  17374. })(BABYLON || (BABYLON = {}));
  17375. //# sourceMappingURL=babylon.filesInput.js.mapvar BABYLON;
  17376. (function (BABYLON) {
  17377. var OimoJSPlugin = (function () {
  17378. function OimoJSPlugin() {
  17379. this._registeredMeshes = [];
  17380. /**
  17381. * Update the body position according to the mesh position
  17382. * @param mesh
  17383. */
  17384. this.updateBodyPosition = function (mesh) {
  17385. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17386. var registeredMesh = this._registeredMeshes[index];
  17387. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17388. var body = registeredMesh.body.body;
  17389. mesh.computeWorldMatrix(true);
  17390. var center = mesh.getBoundingInfo().boundingBox.center;
  17391. body.setPosition(center.x, center.y, center.z);
  17392. body.setRotation(mesh.rotation.x, mesh.rotation.y, mesh.rotation.z);
  17393. return;
  17394. }
  17395. // Case where the parent has been updated
  17396. if (registeredMesh.mesh.parent === mesh) {
  17397. mesh.computeWorldMatrix(true);
  17398. registeredMesh.mesh.computeWorldMatrix(true);
  17399. var absolutePosition = registeredMesh.mesh.getAbsolutePosition();
  17400. var absoluteRotation = mesh.rotation;
  17401. body = registeredMesh.body.body;
  17402. body.setPosition(absolutePosition.x, absolutePosition.y, absolutePosition.z);
  17403. body.setRotation(absoluteRotation.x, absoluteRotation.y, absoluteRotation.z);
  17404. return;
  17405. }
  17406. }
  17407. };
  17408. }
  17409. OimoJSPlugin.prototype._checkWithEpsilon = function (value) {
  17410. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  17411. };
  17412. OimoJSPlugin.prototype.initialize = function (iterations) {
  17413. this._world = new OIMO.World();
  17414. this._world.clear();
  17415. };
  17416. OimoJSPlugin.prototype.setGravity = function (gravity) {
  17417. this._world.gravity = gravity;
  17418. };
  17419. OimoJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  17420. var body = null;
  17421. this.unregisterMesh(mesh);
  17422. mesh.computeWorldMatrix(true);
  17423. var initialRotation = null;
  17424. if (mesh.rotationQuaternion) {
  17425. initialRotation = mesh.rotationQuaternion.clone();
  17426. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17427. mesh.computeWorldMatrix(true);
  17428. }
  17429. var bbox = mesh.getBoundingInfo().boundingBox;
  17430. // The delta between the mesh position and the mesh bounding box center
  17431. var deltaPosition = mesh.position.subtract(bbox.center);
  17432. // Transform delta position with the rotation
  17433. if (initialRotation) {
  17434. var m = new BABYLON.Matrix();
  17435. initialRotation.toRotationMatrix(m);
  17436. deltaPosition = BABYLON.Vector3.TransformCoordinates(deltaPosition, m);
  17437. }
  17438. switch (impostor) {
  17439. case BABYLON.PhysicsEngine.SphereImpostor:
  17440. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17441. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17442. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17443. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17444. body = new OIMO.Body({
  17445. type: 'sphere',
  17446. size: [size],
  17447. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17448. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17449. move: options.mass != 0,
  17450. config: [options.mass, options.friction, options.restitution],
  17451. world: this._world
  17452. });
  17453. break;
  17454. case BABYLON.PhysicsEngine.PlaneImpostor:
  17455. case BABYLON.PhysicsEngine.CylinderImpostor:
  17456. case BABYLON.PhysicsEngine.BoxImpostor:
  17457. var min = bbox.minimumWorld;
  17458. var max = bbox.maximumWorld;
  17459. var box = max.subtract(min);
  17460. var sizeX = this._checkWithEpsilon(box.x);
  17461. var sizeY = this._checkWithEpsilon(box.y);
  17462. var sizeZ = this._checkWithEpsilon(box.z);
  17463. body = new OIMO.Body({
  17464. type: 'box',
  17465. size: [sizeX, sizeY, sizeZ],
  17466. pos: [bbox.center.x, bbox.center.y, bbox.center.z],
  17467. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD],
  17468. move: options.mass != 0,
  17469. config: [options.mass, options.friction, options.restitution],
  17470. world: this._world
  17471. });
  17472. break;
  17473. }
  17474. //If quaternion was set as the rotation of the object
  17475. if (initialRotation) {
  17476. //We have to access the rigid body's properties to set the quaternion.
  17477. //The setQuaternion function of Oimo only sets the newOrientation that is only set after an impulse is given or a collision.
  17478. body.body.orientation = new OIMO.Quat(initialRotation.w, initialRotation.x, initialRotation.y, initialRotation.z);
  17479. //update the internal rotation matrix
  17480. body.body.syncShapes();
  17481. }
  17482. this._registeredMeshes.push({
  17483. mesh: mesh,
  17484. body: body,
  17485. delta: deltaPosition
  17486. });
  17487. return body;
  17488. };
  17489. OimoJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  17490. var types = [], sizes = [], positions = [], rotations = [];
  17491. var initialMesh = parts[0].mesh;
  17492. for (var index = 0; index < parts.length; index++) {
  17493. var part = parts[index];
  17494. var bodyParameters = this._createBodyAsCompound(part, options, initialMesh);
  17495. types.push(bodyParameters.type);
  17496. sizes.push.apply(sizes, bodyParameters.size);
  17497. positions.push.apply(positions, bodyParameters.pos);
  17498. rotations.push.apply(rotations, bodyParameters.rot);
  17499. }
  17500. var body = new OIMO.Body({
  17501. type: types,
  17502. size: sizes,
  17503. pos: positions,
  17504. rot: rotations,
  17505. move: options.mass != 0,
  17506. config: [options.mass, options.friction, options.restitution],
  17507. world: this._world
  17508. });
  17509. this._registeredMeshes.push({
  17510. mesh: initialMesh,
  17511. body: body
  17512. });
  17513. return body;
  17514. };
  17515. OimoJSPlugin.prototype._createBodyAsCompound = function (part, options, initialMesh) {
  17516. var bodyParameters = null;
  17517. var mesh = part.mesh;
  17518. // We need the bounding box/sphere info to compute the physics body
  17519. mesh.computeWorldMatrix();
  17520. switch (part.impostor) {
  17521. case BABYLON.PhysicsEngine.SphereImpostor:
  17522. var bbox = mesh.getBoundingInfo().boundingBox;
  17523. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  17524. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  17525. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  17526. var size = Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2;
  17527. bodyParameters = {
  17528. type: 'sphere',
  17529. /* bug with oimo : sphere needs 3 sizes in this case */
  17530. size: [size, -1, -1],
  17531. pos: [mesh.position.x, mesh.position.y, mesh.position.z],
  17532. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17533. };
  17534. break;
  17535. case BABYLON.PhysicsEngine.PlaneImpostor:
  17536. case BABYLON.PhysicsEngine.BoxImpostor:
  17537. bbox = mesh.getBoundingInfo().boundingBox;
  17538. var min = bbox.minimumWorld;
  17539. var max = bbox.maximumWorld;
  17540. var box = max.subtract(min);
  17541. var sizeX = this._checkWithEpsilon(box.x);
  17542. var sizeY = this._checkWithEpsilon(box.y);
  17543. var sizeZ = this._checkWithEpsilon(box.z);
  17544. var relativePosition = mesh.position;
  17545. bodyParameters = {
  17546. type: 'box',
  17547. size: [sizeX, sizeY, sizeZ],
  17548. pos: [relativePosition.x, relativePosition.y, relativePosition.z],
  17549. rot: [mesh.rotation.x / OIMO.TO_RAD, mesh.rotation.y / OIMO.TO_RAD, mesh.rotation.z / OIMO.TO_RAD]
  17550. };
  17551. break;
  17552. }
  17553. return bodyParameters;
  17554. };
  17555. OimoJSPlugin.prototype.unregisterMesh = function (mesh) {
  17556. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17557. var registeredMesh = this._registeredMeshes[index];
  17558. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17559. if (registeredMesh.body) {
  17560. this._world.removeRigidBody(registeredMesh.body.body);
  17561. this._unbindBody(registeredMesh.body);
  17562. }
  17563. this._registeredMeshes.splice(index, 1);
  17564. return;
  17565. }
  17566. }
  17567. };
  17568. OimoJSPlugin.prototype._unbindBody = function (body) {
  17569. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17570. var registeredMesh = this._registeredMeshes[index];
  17571. if (registeredMesh.body === body) {
  17572. registeredMesh.body = null;
  17573. }
  17574. }
  17575. };
  17576. OimoJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  17577. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17578. var registeredMesh = this._registeredMeshes[index];
  17579. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  17580. // Get object mass to have a behaviour similar to cannon.js
  17581. var mass = registeredMesh.body.body.massInfo.mass;
  17582. // The force is scaled with the mass of object
  17583. registeredMesh.body.body.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  17584. return;
  17585. }
  17586. }
  17587. };
  17588. OimoJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17589. var body1 = null, body2 = null;
  17590. for (var index = 0; index < this._registeredMeshes.length; index++) {
  17591. var registeredMesh = this._registeredMeshes[index];
  17592. if (registeredMesh.mesh === mesh1) {
  17593. body1 = registeredMesh.body.body;
  17594. }
  17595. else if (registeredMesh.mesh === mesh2) {
  17596. body2 = registeredMesh.body.body;
  17597. }
  17598. }
  17599. if (!body1 || !body2) {
  17600. return false;
  17601. }
  17602. if (!options) {
  17603. options = {};
  17604. }
  17605. new OIMO.Link({
  17606. type: options.type,
  17607. body1: body1,
  17608. body2: body2,
  17609. min: options.min,
  17610. max: options.max,
  17611. axe1: options.axe1,
  17612. axe2: options.axe2,
  17613. pos1: [pivot1.x, pivot1.y, pivot1.z],
  17614. pos2: [pivot2.x, pivot2.y, pivot2.z],
  17615. collision: options.collision,
  17616. spring: options.spring,
  17617. world: this._world
  17618. });
  17619. return true;
  17620. };
  17621. OimoJSPlugin.prototype.dispose = function () {
  17622. this._world.clear();
  17623. while (this._registeredMeshes.length) {
  17624. this.unregisterMesh(this._registeredMeshes[0].mesh);
  17625. }
  17626. };
  17627. OimoJSPlugin.prototype.isSupported = function () {
  17628. return OIMO !== undefined;
  17629. };
  17630. OimoJSPlugin.prototype._getLastShape = function (body) {
  17631. var lastShape = body.shapes;
  17632. while (lastShape.next) {
  17633. lastShape = lastShape.next;
  17634. }
  17635. return lastShape;
  17636. };
  17637. OimoJSPlugin.prototype.runOneStep = function (time) {
  17638. this._world.step();
  17639. // Update the position of all registered meshes
  17640. var i = this._registeredMeshes.length;
  17641. var m;
  17642. while (i--) {
  17643. var body = this._registeredMeshes[i].body.body;
  17644. var mesh = this._registeredMeshes[i].mesh;
  17645. var delta = this._registeredMeshes[i].delta;
  17646. if (!body.sleeping) {
  17647. if (body.shapes.next) {
  17648. var parentShape = this._getLastShape(body);
  17649. mesh.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  17650. mesh.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  17651. mesh.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  17652. var mtx = BABYLON.Matrix.FromArray(body.getMatrix());
  17653. if (!mesh.rotationQuaternion) {
  17654. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17655. }
  17656. mesh.rotationQuaternion.fromRotationMatrix(mtx);
  17657. mesh.computeWorldMatrix();
  17658. }
  17659. else {
  17660. m = body.getMatrix();
  17661. mtx = BABYLON.Matrix.FromArray(m);
  17662. // Body position
  17663. var bodyX = mtx.m[12], bodyY = mtx.m[13], bodyZ = mtx.m[14];
  17664. if (!delta) {
  17665. mesh.position.x = bodyX;
  17666. mesh.position.y = bodyY;
  17667. mesh.position.z = bodyZ;
  17668. }
  17669. else {
  17670. mesh.position.x = bodyX + delta.x;
  17671. mesh.position.y = bodyY + delta.y;
  17672. mesh.position.z = bodyZ + delta.z;
  17673. }
  17674. if (!mesh.rotationQuaternion) {
  17675. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  17676. }
  17677. BABYLON.Quaternion.FromRotationMatrixToRef(mtx, mesh.rotationQuaternion);
  17678. mesh.computeWorldMatrix();
  17679. }
  17680. }
  17681. }
  17682. };
  17683. return OimoJSPlugin;
  17684. })();
  17685. BABYLON.OimoJSPlugin = OimoJSPlugin;
  17686. })(BABYLON || (BABYLON = {}));
  17687. //# sourceMappingURL=babylon.oimoJSPlugin.js.mapvar BABYLON;
  17688. (function (BABYLON) {
  17689. var PhysicsEngine = (function () {
  17690. function PhysicsEngine(plugin) {
  17691. this._currentPlugin = plugin || new BABYLON.OimoJSPlugin();
  17692. }
  17693. PhysicsEngine.prototype._initialize = function (gravity) {
  17694. this._currentPlugin.initialize();
  17695. this._setGravity(gravity);
  17696. };
  17697. PhysicsEngine.prototype._runOneStep = function (delta) {
  17698. if (delta > 0.1) {
  17699. delta = 0.1;
  17700. }
  17701. else if (delta <= 0) {
  17702. delta = 1.0 / 60.0;
  17703. }
  17704. this._currentPlugin.runOneStep(delta);
  17705. };
  17706. PhysicsEngine.prototype._setGravity = function (gravity) {
  17707. this.gravity = gravity || new BABYLON.Vector3(0, -9.82, 0);
  17708. this._currentPlugin.setGravity(this.gravity);
  17709. };
  17710. PhysicsEngine.prototype._registerMesh = function (mesh, impostor, options) {
  17711. return this._currentPlugin.registerMesh(mesh, impostor, options);
  17712. };
  17713. PhysicsEngine.prototype._registerMeshesAsCompound = function (parts, options) {
  17714. return this._currentPlugin.registerMeshesAsCompound(parts, options);
  17715. };
  17716. PhysicsEngine.prototype._unregisterMesh = function (mesh) {
  17717. this._currentPlugin.unregisterMesh(mesh);
  17718. };
  17719. PhysicsEngine.prototype._applyImpulse = function (mesh, force, contactPoint) {
  17720. this._currentPlugin.applyImpulse(mesh, force, contactPoint);
  17721. };
  17722. PhysicsEngine.prototype._createLink = function (mesh1, mesh2, pivot1, pivot2, options) {
  17723. return this._currentPlugin.createLink(mesh1, mesh2, pivot1, pivot2, options);
  17724. };
  17725. PhysicsEngine.prototype._updateBodyPosition = function (mesh) {
  17726. this._currentPlugin.updateBodyPosition(mesh);
  17727. };
  17728. PhysicsEngine.prototype.dispose = function () {
  17729. this._currentPlugin.dispose();
  17730. };
  17731. PhysicsEngine.prototype.isSupported = function () {
  17732. return this._currentPlugin.isSupported();
  17733. };
  17734. // Statics
  17735. PhysicsEngine.NoImpostor = 0;
  17736. PhysicsEngine.SphereImpostor = 1;
  17737. PhysicsEngine.BoxImpostor = 2;
  17738. PhysicsEngine.PlaneImpostor = 3;
  17739. PhysicsEngine.MeshImpostor = 4;
  17740. PhysicsEngine.CapsuleImpostor = 5;
  17741. PhysicsEngine.ConeImpostor = 6;
  17742. PhysicsEngine.CylinderImpostor = 7;
  17743. PhysicsEngine.ConvexHullImpostor = 8;
  17744. PhysicsEngine.Epsilon = 0.001;
  17745. return PhysicsEngine;
  17746. })();
  17747. BABYLON.PhysicsEngine = PhysicsEngine;
  17748. })(BABYLON || (BABYLON = {}));
  17749. //# sourceMappingURL=babylon.physicsEngine.js.mapvar BABYLON;
  17750. (function (BABYLON) {
  17751. var serializeLight = function (light) {
  17752. var serializationObject = {};
  17753. serializationObject.name = light.name;
  17754. serializationObject.id = light.id;
  17755. serializationObject.tags = BABYLON.Tags.GetTags(light);
  17756. if (light instanceof BABYLON.PointLight) {
  17757. serializationObject.type = 0;
  17758. serializationObject.position = light.position.asArray();
  17759. }
  17760. else if (light instanceof BABYLON.DirectionalLight) {
  17761. serializationObject.type = 1;
  17762. var directionalLight = light;
  17763. serializationObject.position = directionalLight.position.asArray();
  17764. serializationObject.direction = directionalLight.direction.asArray();
  17765. }
  17766. else if (light instanceof BABYLON.SpotLight) {
  17767. serializationObject.type = 2;
  17768. var spotLight = light;
  17769. serializationObject.position = spotLight.position.asArray();
  17770. serializationObject.direction = spotLight.position.asArray();
  17771. serializationObject.angle = spotLight.angle;
  17772. serializationObject.exponent = spotLight.exponent;
  17773. }
  17774. else if (light instanceof BABYLON.HemisphericLight) {
  17775. serializationObject.type = 3;
  17776. var hemisphericLight = light;
  17777. serializationObject.direction = hemisphericLight.direction.asArray();
  17778. serializationObject.groundColor = hemisphericLight.groundColor.asArray();
  17779. }
  17780. if (light.intensity) {
  17781. serializationObject.intensity = light.intensity;
  17782. }
  17783. serializationObject.range = light.range;
  17784. serializationObject.diffuse = light.diffuse.asArray();
  17785. serializationObject.specular = light.specular.asArray();
  17786. return serializationObject;
  17787. };
  17788. var serializeFresnelParameter = function (fresnelParameter) {
  17789. var serializationObject = {};
  17790. serializationObject.isEnabled = fresnelParameter.isEnabled;
  17791. serializationObject.leftColor = fresnelParameter.leftColor;
  17792. serializationObject.rightColor = fresnelParameter.rightColor;
  17793. serializationObject.bias = fresnelParameter.bias;
  17794. serializationObject.power = fresnelParameter.power;
  17795. return serializationObject;
  17796. };
  17797. var serializeCamera = function (camera) {
  17798. var serializationObject = {};
  17799. serializationObject.name = camera.name;
  17800. serializationObject.tags = BABYLON.Tags.GetTags(camera);
  17801. serializationObject.id = camera.id;
  17802. serializationObject.position = camera.position.asArray();
  17803. // Parent
  17804. if (camera.parent) {
  17805. serializationObject.parentId = camera.parent.id;
  17806. }
  17807. // Target
  17808. serializationObject.rotation = camera.rotation.asArray();
  17809. // Locked target
  17810. if (camera.lockedTarget && camera.lockedTarget.id) {
  17811. serializationObject.lockedTargetId = camera.lockedTarget.id;
  17812. }
  17813. serializationObject.fov = camera.fov;
  17814. serializationObject.minZ = camera.minZ;
  17815. serializationObject.maxZ = camera.maxZ;
  17816. serializationObject.speed = camera.speed;
  17817. serializationObject.inertia = camera.inertia;
  17818. serializationObject.checkCollisions = camera.checkCollisions;
  17819. serializationObject.applyGravity = camera.applyGravity;
  17820. if (camera.ellipsoid) {
  17821. serializationObject.ellipsoid = camera.ellipsoid.asArray();
  17822. }
  17823. // Animations
  17824. appendAnimations(camera, serializationObject);
  17825. // Layer mask
  17826. serializationObject.layerMask = camera.layerMask;
  17827. return serializationObject;
  17828. };
  17829. var appendAnimations = function (source, destination) {
  17830. if (source.animations) {
  17831. destination.animations = [];
  17832. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  17833. var animation = source.animations[animationIndex];
  17834. destination.animations.push(serializeAnimation(animation));
  17835. }
  17836. }
  17837. };
  17838. var serializeAnimation = function (animation) {
  17839. var serializationObject = {};
  17840. serializationObject.name = animation.name;
  17841. serializationObject.property = animation.targetProperty;
  17842. serializationObject.framePerSecond = animation.framePerSecond;
  17843. serializationObject.dataType = animation.dataType;
  17844. serializationObject.loopBehavior = animation.loopMode;
  17845. var dataType = animation.dataType;
  17846. serializationObject.keys = [];
  17847. var keys = animation.getKeys();
  17848. for (var index = 0; index < keys.length; index++) {
  17849. var animationKey = keys[index];
  17850. var key = {};
  17851. key.frame = animationKey.frame;
  17852. switch (dataType) {
  17853. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  17854. key.values = [animationKey.value];
  17855. break;
  17856. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  17857. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  17858. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  17859. key.values = animationKey.value.asArray();
  17860. break;
  17861. }
  17862. serializationObject.keys.push(key);
  17863. }
  17864. return serializationObject;
  17865. };
  17866. var serializeMultiMaterial = function (material) {
  17867. var serializationObject = {};
  17868. serializationObject.name = material.name;
  17869. serializationObject.id = material.id;
  17870. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17871. serializationObject.materials = [];
  17872. for (var matIndex = 0; matIndex < material.subMaterials.length; matIndex++) {
  17873. var subMat = material.subMaterials[matIndex];
  17874. if (subMat) {
  17875. serializationObject.materials.push(subMat.id);
  17876. }
  17877. else {
  17878. serializationObject.materials.push(null);
  17879. }
  17880. }
  17881. return serializationObject;
  17882. };
  17883. var serializeMaterial = function (material) {
  17884. var serializationObject = {};
  17885. serializationObject.name = material.name;
  17886. serializationObject.ambient = material.ambientColor.asArray();
  17887. serializationObject.diffuse = material.diffuseColor.asArray();
  17888. serializationObject.specular = material.specularColor.asArray();
  17889. serializationObject.specularPower = material.specularPower;
  17890. serializationObject.emissive = material.emissiveColor.asArray();
  17891. serializationObject.alpha = material.alpha;
  17892. serializationObject.id = material.id;
  17893. serializationObject.tags = BABYLON.Tags.GetTags(material);
  17894. serializationObject.backFaceCulling = material.backFaceCulling;
  17895. if (material.diffuseTexture) {
  17896. serializationObject.diffuseTexture = serializeTexture(material.diffuseTexture);
  17897. }
  17898. if (material.diffuseFresnelParameters) {
  17899. serializationObject.diffuseFresnelParameters = serializeFresnelParameter(material.diffuseFresnelParameters);
  17900. }
  17901. if (material.ambientTexture) {
  17902. serializationObject.ambientTexture = serializeTexture(material.ambientTexture);
  17903. }
  17904. if (material.opacityTexture) {
  17905. serializationObject.opacityTexture = serializeTexture(material.opacityTexture);
  17906. }
  17907. if (material.opacityFresnelParameters) {
  17908. serializationObject.opacityFresnelParameters = serializeFresnelParameter(material.opacityFresnelParameters);
  17909. }
  17910. if (material.reflectionTexture) {
  17911. serializationObject.reflectionTexture = serializeTexture(material.reflectionTexture);
  17912. }
  17913. if (material.reflectionFresnelParameters) {
  17914. serializationObject.reflectionFresnelParameters = serializeFresnelParameter(material.reflectionFresnelParameters);
  17915. }
  17916. if (material.emissiveTexture) {
  17917. serializationObject.emissiveTexture = serializeTexture(material.emissiveTexture);
  17918. }
  17919. if (material.emissiveFresnelParameters) {
  17920. serializationObject.emissiveFresnelParameters = serializeFresnelParameter(material.emissiveFresnelParameters);
  17921. }
  17922. if (material.specularTexture) {
  17923. serializationObject.specularTexture = serializeTexture(material.specularTexture);
  17924. }
  17925. if (material.bumpTexture) {
  17926. serializationObject.bumpTexture = serializeTexture(material.bumpTexture);
  17927. }
  17928. return serializationObject;
  17929. };
  17930. var serializeTexture = function (texture) {
  17931. var serializationObject = {};
  17932. if (!texture.name) {
  17933. return null;
  17934. }
  17935. if (texture instanceof BABYLON.CubeTexture) {
  17936. serializationObject.name = texture.name;
  17937. serializationObject.hasAlpha = texture.hasAlpha;
  17938. serializationObject.level = texture.level;
  17939. serializationObject.coordinatesMode = texture.coordinatesMode;
  17940. return serializationObject;
  17941. }
  17942. if (texture instanceof BABYLON.MirrorTexture) {
  17943. var mirrorTexture = texture;
  17944. serializationObject.renderTargetSize = mirrorTexture.getRenderSize();
  17945. serializationObject.renderList = [];
  17946. for (var index = 0; index < mirrorTexture.renderList.length; index++) {
  17947. serializationObject.renderList.push(mirrorTexture.renderList[index].id);
  17948. }
  17949. serializationObject.mirrorPlane = mirrorTexture.mirrorPlane.asArray();
  17950. }
  17951. else if (texture instanceof BABYLON.RenderTargetTexture) {
  17952. var renderTargetTexture = texture;
  17953. serializationObject.renderTargetSize = renderTargetTexture.getRenderSize();
  17954. serializationObject.renderList = [];
  17955. for (index = 0; index < renderTargetTexture.renderList.length; index++) {
  17956. serializationObject.renderList.push(renderTargetTexture.renderList[index].id);
  17957. }
  17958. }
  17959. var regularTexture = texture;
  17960. serializationObject.name = texture.name;
  17961. serializationObject.hasAlpha = texture.hasAlpha;
  17962. serializationObject.level = texture.level;
  17963. serializationObject.coordinatesIndex = texture.coordinatesIndex;
  17964. serializationObject.coordinatesMode = texture.coordinatesMode;
  17965. serializationObject.uOffset = regularTexture.uOffset;
  17966. serializationObject.vOffset = regularTexture.vOffset;
  17967. serializationObject.uScale = regularTexture.uScale;
  17968. serializationObject.vScale = regularTexture.vScale;
  17969. serializationObject.uAng = regularTexture.uAng;
  17970. serializationObject.vAng = regularTexture.vAng;
  17971. serializationObject.wAng = regularTexture.wAng;
  17972. serializationObject.wrapU = texture.wrapU;
  17973. serializationObject.wrapV = texture.wrapV;
  17974. // Animations
  17975. appendAnimations(texture, serializationObject);
  17976. return serializationObject;
  17977. };
  17978. var serializeSkeleton = function (skeleton) {
  17979. var serializationObject = {};
  17980. serializationObject.name = skeleton.name;
  17981. serializationObject.id = skeleton.id;
  17982. serializationObject.bones = [];
  17983. for (var index = 0; index < skeleton.bones.length; index++) {
  17984. var bone = skeleton.bones[index];
  17985. var serializedBone = {
  17986. parentBoneIndex: bone.getParent() ? skeleton.bones.indexOf(bone.getParent()) : -1,
  17987. name: bone.name,
  17988. matrix: bone.getLocalMatrix().toArray()
  17989. };
  17990. serializationObject.bones.push(serializedBone);
  17991. if (bone.animations && bone.animations.length > 0) {
  17992. serializedBone.animation = serializeAnimation(bone.animations[0]);
  17993. }
  17994. }
  17995. return serializationObject;
  17996. };
  17997. var serializeParticleSystem = function (particleSystem) {
  17998. var serializationObject = {};
  17999. serializationObject.emitterId = particleSystem.emitter.id;
  18000. serializationObject.capacity = particleSystem.getCapacity();
  18001. if (particleSystem.particleTexture) {
  18002. serializationObject.textureName = particleSystem.particleTexture.name;
  18003. }
  18004. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  18005. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  18006. serializationObject.minSize = particleSystem.minSize;
  18007. serializationObject.maxSize = particleSystem.maxSize;
  18008. serializationObject.minLifeTime = particleSystem.minLifeTime;
  18009. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  18010. serializationObject.emitRate = particleSystem.emitRate;
  18011. serializationObject.minEmitBox = particleSystem.minEmitBox.asArray();
  18012. serializationObject.maxEmitBox = particleSystem.maxEmitBox.asArray();
  18013. serializationObject.gravity = particleSystem.gravity.asArray();
  18014. serializationObject.direction1 = particleSystem.direction1.asArray();
  18015. serializationObject.direction2 = particleSystem.direction2.asArray();
  18016. serializationObject.color1 = particleSystem.color1.asArray();
  18017. serializationObject.color2 = particleSystem.color2.asArray();
  18018. serializationObject.colorDead = particleSystem.colorDead.asArray();
  18019. serializationObject.updateSpeed = particleSystem.updateSpeed;
  18020. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  18021. serializationObject.textureMask = particleSystem.textureMask.asArray();
  18022. serializationObject.blendMode = particleSystem.blendMode;
  18023. return serializationObject;
  18024. };
  18025. var serializeLensFlareSystem = function (lensFlareSystem) {
  18026. var serializationObject = {};
  18027. serializationObject.emitterId = lensFlareSystem.getEmitter().id;
  18028. serializationObject.borderLimit = lensFlareSystem.borderLimit;
  18029. serializationObject.flares = [];
  18030. for (var index = 0; index < lensFlareSystem.lensFlares.length; index++) {
  18031. var flare = lensFlareSystem.lensFlares[index];
  18032. serializationObject.flares.push({
  18033. size: flare.size,
  18034. position: flare.position,
  18035. color: flare.color.asArray(),
  18036. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  18037. });
  18038. }
  18039. return serializationObject;
  18040. };
  18041. var serializeShadowGenerator = function (light) {
  18042. var serializationObject = {};
  18043. var shadowGenerator = light.getShadowGenerator();
  18044. serializationObject.lightId = light.id;
  18045. serializationObject.mapSize = shadowGenerator.getShadowMap().getRenderSize();
  18046. serializationObject.useVarianceShadowMap = shadowGenerator.useVarianceShadowMap;
  18047. serializationObject.usePoissonSampling = shadowGenerator.usePoissonSampling;
  18048. serializationObject.renderList = [];
  18049. for (var meshIndex = 0; meshIndex < shadowGenerator.getShadowMap().renderList.length; meshIndex++) {
  18050. var mesh = shadowGenerator.getShadowMap().renderList[meshIndex];
  18051. serializationObject.renderList.push(mesh.id);
  18052. }
  18053. return serializationObject;
  18054. };
  18055. var serializedGeometries = [];
  18056. var serializeGeometry = function (geometry, serializationGeometries) {
  18057. if (serializedGeometries[geometry.id]) {
  18058. return;
  18059. }
  18060. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  18061. serializationGeometries.boxes.push(serializeBox(geometry));
  18062. }
  18063. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  18064. serializationGeometries.spheres.push(serializeSphere(geometry));
  18065. }
  18066. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  18067. serializationGeometries.cylinders.push(serializeCylinder(geometry));
  18068. }
  18069. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  18070. serializationGeometries.toruses.push(serializeTorus(geometry));
  18071. }
  18072. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  18073. serializationGeometries.grounds.push(serializeGround(geometry));
  18074. }
  18075. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  18076. serializationGeometries.planes.push(serializePlane(geometry));
  18077. }
  18078. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  18079. serializationGeometries.torusKnots.push(serializeTorusKnot(geometry));
  18080. }
  18081. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  18082. throw new Error("Unknow primitive type");
  18083. }
  18084. else {
  18085. serializationGeometries.vertexData.push(serializeVertexData(geometry));
  18086. }
  18087. serializedGeometries[geometry.id] = true;
  18088. };
  18089. var serializeGeometryBase = function (geometry) {
  18090. var serializationObject = {};
  18091. serializationObject.id = geometry.id;
  18092. if (BABYLON.Tags.HasTags(geometry)) {
  18093. serializationObject.tags = BABYLON.Tags.GetTags(geometry);
  18094. }
  18095. return serializationObject;
  18096. };
  18097. var serializeVertexData = function (vertexData) {
  18098. var serializationObject = serializeGeometryBase(vertexData);
  18099. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  18100. serializationObject.positions = vertexData.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18101. }
  18102. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  18103. serializationObject.normals = vertexData.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18104. }
  18105. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  18106. serializationObject.uvs = vertexData.getVerticesData(BABYLON.VertexBuffer.UVKind);
  18107. }
  18108. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  18109. serializationObject.uvs2 = vertexData.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  18110. }
  18111. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  18112. serializationObject.colors = vertexData.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  18113. }
  18114. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  18115. serializationObject.matricesIndices = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  18116. serializationObject.matricesIndices._isExpanded = true;
  18117. }
  18118. if (vertexData.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  18119. serializationObject.matricesWeights = vertexData.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  18120. }
  18121. serializationObject.indices = vertexData.getIndices();
  18122. return serializationObject;
  18123. };
  18124. var serializePrimitive = function (primitive) {
  18125. var serializationObject = serializeGeometryBase(primitive);
  18126. serializationObject.canBeRegenerated = primitive.canBeRegenerated();
  18127. return serializationObject;
  18128. };
  18129. var serializeBox = function (box) {
  18130. var serializationObject = serializePrimitive(box);
  18131. serializationObject.size = box.size;
  18132. return serializationObject;
  18133. };
  18134. var serializeSphere = function (sphere) {
  18135. var serializationObject = serializePrimitive(sphere);
  18136. serializationObject.segments = sphere.segments;
  18137. serializationObject.diameter = sphere.diameter;
  18138. return serializationObject;
  18139. };
  18140. var serializeCylinder = function (cylinder) {
  18141. var serializationObject = serializePrimitive(cylinder);
  18142. serializationObject.height = cylinder.height;
  18143. serializationObject.diameterTop = cylinder.diameterTop;
  18144. serializationObject.diameterBottom = cylinder.diameterBottom;
  18145. serializationObject.tessellation = cylinder.tessellation;
  18146. return serializationObject;
  18147. };
  18148. var serializeTorus = function (torus) {
  18149. var serializationObject = serializePrimitive(torus);
  18150. serializationObject.diameter = torus.diameter;
  18151. serializationObject.thickness = torus.thickness;
  18152. serializationObject.tessellation = torus.tessellation;
  18153. return serializationObject;
  18154. };
  18155. var serializeGround = function (ground) {
  18156. var serializationObject = serializePrimitive(ground);
  18157. serializationObject.width = ground.width;
  18158. serializationObject.height = ground.height;
  18159. serializationObject.subdivisions = ground.subdivisions;
  18160. return serializationObject;
  18161. };
  18162. var serializePlane = function (plane) {
  18163. var serializationObject = serializePrimitive(plane);
  18164. serializationObject.size = plane.size;
  18165. return serializationObject;
  18166. };
  18167. var serializeTorusKnot = function (torusKnot) {
  18168. var serializationObject = serializePrimitive(torusKnot);
  18169. serializationObject.radius = torusKnot.radius;
  18170. serializationObject.tube = torusKnot.tube;
  18171. serializationObject.radialSegments = torusKnot.radialSegments;
  18172. serializationObject.tubularSegments = torusKnot.tubularSegments;
  18173. serializationObject.p = torusKnot.p;
  18174. serializationObject.q = torusKnot.q;
  18175. return serializationObject;
  18176. };
  18177. var serializeMesh = function (mesh, serializationScene) {
  18178. var serializationObject = {};
  18179. serializationObject.name = mesh.name;
  18180. serializationObject.id = mesh.id;
  18181. if (BABYLON.Tags.HasTags(mesh)) {
  18182. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  18183. }
  18184. serializationObject.position = mesh.position.asArray();
  18185. if (mesh.rotationQuaternion) {
  18186. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  18187. }
  18188. else if (mesh.rotation) {
  18189. serializationObject.rotation = mesh.rotation.asArray();
  18190. }
  18191. serializationObject.scaling = mesh.scaling.asArray();
  18192. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  18193. serializationObject.isEnabled = mesh.isEnabled();
  18194. serializationObject.isVisible = mesh.isVisible;
  18195. serializationObject.infiniteDistance = mesh.infiniteDistance;
  18196. serializationObject.pickable = mesh.isPickable;
  18197. serializationObject.receiveShadows = mesh.receiveShadows;
  18198. serializationObject.billboardMode = mesh.billboardMode;
  18199. serializationObject.visibility = mesh.visibility;
  18200. serializationObject.checkCollisions = mesh.checkCollisions;
  18201. // Parent
  18202. if (mesh.parent) {
  18203. serializationObject.parentId = mesh.parent.id;
  18204. }
  18205. // Geometry
  18206. var geometry = mesh._geometry;
  18207. if (geometry) {
  18208. var geometryId = geometry.id;
  18209. serializationObject.geometryId = geometryId;
  18210. if (!mesh.getScene().getGeometryByID(geometryId)) {
  18211. // 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
  18212. serializeGeometry(geometry, serializationScene.geometries);
  18213. }
  18214. // SubMeshes
  18215. serializationObject.subMeshes = [];
  18216. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  18217. var subMesh = mesh.subMeshes[subIndex];
  18218. serializationObject.subMeshes.push({
  18219. materialIndex: subMesh.materialIndex,
  18220. verticesStart: subMesh.verticesStart,
  18221. verticesCount: subMesh.verticesCount,
  18222. indexStart: subMesh.indexStart,
  18223. indexCount: subMesh.indexCount
  18224. });
  18225. }
  18226. }
  18227. // Material
  18228. if (mesh.material) {
  18229. serializationObject.materialId = mesh.material.id;
  18230. }
  18231. else {
  18232. mesh.material = null;
  18233. }
  18234. // Skeleton
  18235. if (mesh.skeleton) {
  18236. serializationObject.skeletonId = mesh.skeleton.id;
  18237. }
  18238. // Physics
  18239. if (mesh.getPhysicsImpostor() !== BABYLON.PhysicsEngine.NoImpostor) {
  18240. serializationObject.physicsMass = mesh.getPhysicsMass();
  18241. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  18242. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  18243. switch (mesh.getPhysicsImpostor()) {
  18244. case BABYLON.PhysicsEngine.BoxImpostor:
  18245. serializationObject.physicsImpostor = 1;
  18246. break;
  18247. case BABYLON.PhysicsEngine.SphereImpostor:
  18248. serializationObject.physicsImpostor = 2;
  18249. break;
  18250. }
  18251. }
  18252. // Instances
  18253. serializationObject.instances = [];
  18254. for (var index = 0; index < mesh.instances.length; index++) {
  18255. var instance = mesh.instances[index];
  18256. var serializationInstance = {
  18257. name: instance.name,
  18258. position: instance.position,
  18259. rotation: instance.rotation,
  18260. rotationQuaternion: instance.rotationQuaternion,
  18261. scaling: instance.scaling
  18262. };
  18263. serializationObject.instances.push(serializationInstance);
  18264. // Animations
  18265. appendAnimations(instance, serializationInstance);
  18266. }
  18267. // Animations
  18268. appendAnimations(mesh, serializationObject);
  18269. // Layer mask
  18270. serializationObject.layerMask = mesh.layerMask;
  18271. return serializationObject;
  18272. };
  18273. var SceneSerializer = (function () {
  18274. function SceneSerializer() {
  18275. }
  18276. SceneSerializer.Serialize = function (scene) {
  18277. var serializationObject = {};
  18278. // Scene
  18279. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  18280. serializationObject.autoClear = scene.autoClear;
  18281. serializationObject.clearColor = scene.clearColor.asArray();
  18282. serializationObject.ambientColor = scene.ambientColor.asArray();
  18283. serializationObject.gravity = scene.gravity.asArray();
  18284. // Fog
  18285. if (scene.fogMode && scene.fogMode !== 0) {
  18286. serializationObject.fogMode = scene.fogMode;
  18287. serializationObject.fogColor = scene.fogColor.asArray();
  18288. serializationObject.fogStart = scene.fogStart;
  18289. serializationObject.fogEnd = scene.fogEnd;
  18290. serializationObject.fogDensity = scene.fogDensity;
  18291. }
  18292. // Lights
  18293. serializationObject.lights = [];
  18294. for (var index = 0; index < scene.lights.length; index++) {
  18295. var light = scene.lights[index];
  18296. serializationObject.lights.push(serializeLight(light));
  18297. }
  18298. // Cameras
  18299. serializationObject.cameras = [];
  18300. for (index = 0; index < scene.cameras.length; index++) {
  18301. var camera = scene.cameras[index];
  18302. if (camera instanceof BABYLON.FreeCamera) {
  18303. serializationObject.cameras.push(serializeCamera(camera));
  18304. }
  18305. }
  18306. if (scene.activeCamera) {
  18307. serializationObject.activeCameraID = scene.activeCamera.id;
  18308. }
  18309. // Materials
  18310. serializationObject.materials = [];
  18311. serializationObject.multiMaterials = [];
  18312. for (index = 0; index < scene.materials.length; index++) {
  18313. var material = scene.materials[index];
  18314. if (material instanceof BABYLON.StandardMaterial) {
  18315. serializationObject.materials.push(serializeMaterial(material));
  18316. }
  18317. else if (material instanceof BABYLON.MultiMaterial) {
  18318. serializationObject.multiMaterials.push(serializeMultiMaterial(material));
  18319. }
  18320. }
  18321. // Skeletons
  18322. serializationObject.skeletons = [];
  18323. for (index = 0; index < scene.skeletons.length; index++) {
  18324. serializationObject.skeletons.push(serializeSkeleton(scene.skeletons[index]));
  18325. }
  18326. // Geometries
  18327. serializationObject.geometries = {};
  18328. serializationObject.geometries.boxes = [];
  18329. serializationObject.geometries.spheres = [];
  18330. serializationObject.geometries.cylinders = [];
  18331. serializationObject.geometries.toruses = [];
  18332. serializationObject.geometries.grounds = [];
  18333. serializationObject.geometries.planes = [];
  18334. serializationObject.geometries.torusKnots = [];
  18335. serializationObject.geometries.vertexData = [];
  18336. serializedGeometries = [];
  18337. var geometries = scene.getGeometries();
  18338. for (var index = 0; index < geometries.length; index++) {
  18339. var geometry = geometries[index];
  18340. if (geometry.isReady()) {
  18341. serializeGeometry(geometry, serializationObject.geometries);
  18342. }
  18343. }
  18344. // Meshes
  18345. serializationObject.meshes = [];
  18346. for (index = 0; index < scene.meshes.length; index++) {
  18347. var abstractMesh = scene.meshes[index];
  18348. if (abstractMesh instanceof BABYLON.Mesh) {
  18349. var mesh = abstractMesh;
  18350. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  18351. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  18352. }
  18353. }
  18354. }
  18355. // Particles Systems
  18356. serializationObject.particleSystems = [];
  18357. for (index = 0; index < scene.particleSystems.length; index++) {
  18358. serializationObject.particleSystems.push(serializeParticleSystem(scene.particleSystems[index]));
  18359. }
  18360. // Lens flares
  18361. serializationObject.lensFlareSystems = [];
  18362. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  18363. serializationObject.lensFlareSystems.push(serializeLensFlareSystem(scene.lensFlareSystems[index]));
  18364. }
  18365. // Shadows
  18366. serializationObject.shadowGenerators = [];
  18367. for (index = 0; index < scene.lights.length; index++) {
  18368. light = scene.lights[index];
  18369. if (light.getShadowGenerator()) {
  18370. serializationObject.shadowGenerators.push(serializeShadowGenerator(light));
  18371. }
  18372. }
  18373. return serializationObject;
  18374. };
  18375. return SceneSerializer;
  18376. })();
  18377. BABYLON.SceneSerializer = SceneSerializer;
  18378. })(BABYLON || (BABYLON = {}));
  18379. //# sourceMappingURL=babylon.sceneSerializer.js.mapvar BABYLON;
  18380. (function (BABYLON) {
  18381. var SceneLoader = (function () {
  18382. function SceneLoader() {
  18383. }
  18384. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  18385. get: function () {
  18386. return SceneLoader._ForceFullSceneLoadingForIncremental;
  18387. },
  18388. set: function (value) {
  18389. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  18390. },
  18391. enumerable: true,
  18392. configurable: true
  18393. });
  18394. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  18395. get: function () {
  18396. return SceneLoader._ShowLoadingScreen;
  18397. },
  18398. set: function (value) {
  18399. SceneLoader._ShowLoadingScreen = value;
  18400. },
  18401. enumerable: true,
  18402. configurable: true
  18403. });
  18404. SceneLoader._getPluginForFilename = function (sceneFilename) {
  18405. var dotPosition = sceneFilename.lastIndexOf(".");
  18406. var queryStringPosition = sceneFilename.indexOf("?");
  18407. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  18408. for (var index = 0; index < this._registeredPlugins.length; index++) {
  18409. var plugin = this._registeredPlugins[index];
  18410. if (plugin.extensions.indexOf(extension) !== -1) {
  18411. return plugin;
  18412. }
  18413. }
  18414. return this._registeredPlugins[this._registeredPlugins.length - 1];
  18415. };
  18416. // Public functions
  18417. SceneLoader.RegisterPlugin = function (plugin) {
  18418. plugin.extensions = plugin.extensions.toLowerCase();
  18419. SceneLoader._registeredPlugins.push(plugin);
  18420. };
  18421. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18422. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18423. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18424. return;
  18425. }
  18426. var manifestChecked = function (success) {
  18427. scene.database = database;
  18428. var plugin = SceneLoader._getPluginForFilename(sceneFilename);
  18429. var importMeshFromData = function (data) {
  18430. var meshes = [];
  18431. var particleSystems = [];
  18432. var skeletons = [];
  18433. try {
  18434. if (!plugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  18435. if (onerror) {
  18436. onerror(scene, 'unable to load the scene');
  18437. }
  18438. return;
  18439. }
  18440. }
  18441. catch (e) {
  18442. if (onerror) {
  18443. onerror(scene, e);
  18444. }
  18445. return;
  18446. }
  18447. if (onsuccess) {
  18448. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  18449. onsuccess(meshes, particleSystems, skeletons);
  18450. }
  18451. };
  18452. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18453. // Direct load
  18454. importMeshFromData(sceneFilename.substr(5));
  18455. return;
  18456. }
  18457. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  18458. importMeshFromData(data);
  18459. }, progressCallBack, database);
  18460. };
  18461. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18462. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18463. };
  18464. /**
  18465. * Load a scene
  18466. * @param rootUrl a string that defines the root url for scene and resources
  18467. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18468. * @param engine is the instance of BABYLON.Engine to use to create the scene
  18469. */
  18470. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  18471. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  18472. };
  18473. /**
  18474. * Append a scene
  18475. * @param rootUrl a string that defines the root url for scene and resources
  18476. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  18477. * @param scene is the instance of BABYLON.Scene to append to
  18478. */
  18479. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  18480. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  18481. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  18482. return;
  18483. }
  18484. var plugin = this._getPluginForFilename(sceneFilename.name || sceneFilename);
  18485. var database;
  18486. if (SceneLoader.ShowLoadingScreen) {
  18487. scene.getEngine().displayLoadingUI();
  18488. }
  18489. var loadSceneFromData = function (data) {
  18490. scene.database = database;
  18491. if (!plugin.load(scene, data, rootUrl)) {
  18492. if (onerror) {
  18493. onerror(scene);
  18494. }
  18495. scene.getEngine().hideLoadingUI();
  18496. return;
  18497. }
  18498. if (onsuccess) {
  18499. onsuccess(scene);
  18500. }
  18501. if (SceneLoader.ShowLoadingScreen) {
  18502. scene.executeWhenReady(function () {
  18503. scene.getEngine().hideLoadingUI();
  18504. });
  18505. }
  18506. };
  18507. var manifestChecked = function (success) {
  18508. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database);
  18509. };
  18510. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  18511. // Direct load
  18512. loadSceneFromData(sceneFilename.substr(5));
  18513. return;
  18514. }
  18515. if (rootUrl.indexOf("file:") === -1) {
  18516. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  18517. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  18518. }
  18519. else {
  18520. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack);
  18521. }
  18522. };
  18523. // Flags
  18524. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  18525. SceneLoader._ShowLoadingScreen = true;
  18526. // Members
  18527. SceneLoader._registeredPlugins = new Array();
  18528. return SceneLoader;
  18529. })();
  18530. BABYLON.SceneLoader = SceneLoader;
  18531. ;
  18532. })(BABYLON || (BABYLON = {}));
  18533. //# sourceMappingURL=babylon.sceneLoader.js.mapvar BABYLON;
  18534. (function (BABYLON) {
  18535. var Internals;
  18536. (function (Internals) {
  18537. var checkColors4 = function (colors, count) {
  18538. // Check if color3 was used
  18539. if (colors.length === count * 3) {
  18540. var colors4 = [];
  18541. for (var index = 0; index < colors.length; index += 3) {
  18542. var newIndex = (index / 3) * 4;
  18543. colors4[newIndex] = colors[index];
  18544. colors4[newIndex + 1] = colors[index + 1];
  18545. colors4[newIndex + 2] = colors[index + 2];
  18546. colors4[newIndex + 3] = 1.0;
  18547. }
  18548. return colors4;
  18549. }
  18550. return colors;
  18551. };
  18552. var loadCubeTexture = function (rootUrl, parsedTexture, scene) {
  18553. var texture = new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene);
  18554. texture.name = parsedTexture.name;
  18555. texture.hasAlpha = parsedTexture.hasAlpha;
  18556. texture.level = parsedTexture.level;
  18557. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18558. return texture;
  18559. };
  18560. var loadTexture = function (rootUrl, parsedTexture, scene) {
  18561. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  18562. return null;
  18563. }
  18564. if (parsedTexture.isCube) {
  18565. return loadCubeTexture(rootUrl, parsedTexture, scene);
  18566. }
  18567. var texture;
  18568. if (parsedTexture.mirrorPlane) {
  18569. texture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18570. texture._waitingRenderList = parsedTexture.renderList;
  18571. texture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  18572. }
  18573. else if (parsedTexture.isRenderTarget) {
  18574. texture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  18575. texture._waitingRenderList = parsedTexture.renderList;
  18576. }
  18577. else {
  18578. texture = new BABYLON.Texture(rootUrl + parsedTexture.name, scene);
  18579. }
  18580. texture.name = parsedTexture.name;
  18581. texture.hasAlpha = parsedTexture.hasAlpha;
  18582. texture.getAlphaFromRGB = parsedTexture.getAlphaFromRGB;
  18583. texture.level = parsedTexture.level;
  18584. texture.coordinatesIndex = parsedTexture.coordinatesIndex;
  18585. texture.coordinatesMode = parsedTexture.coordinatesMode;
  18586. texture.uOffset = parsedTexture.uOffset;
  18587. texture.vOffset = parsedTexture.vOffset;
  18588. texture.uScale = parsedTexture.uScale;
  18589. texture.vScale = parsedTexture.vScale;
  18590. texture.uAng = parsedTexture.uAng;
  18591. texture.vAng = parsedTexture.vAng;
  18592. texture.wAng = parsedTexture.wAng;
  18593. texture.wrapU = parsedTexture.wrapU;
  18594. texture.wrapV = parsedTexture.wrapV;
  18595. // Animations
  18596. if (parsedTexture.animations) {
  18597. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  18598. var parsedAnimation = parsedTexture.animations[animationIndex];
  18599. texture.animations.push(parseAnimation(parsedAnimation));
  18600. }
  18601. }
  18602. return texture;
  18603. };
  18604. var parseSkeleton = function (parsedSkeleton, scene) {
  18605. var skeleton = new BABYLON.Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  18606. for (var index = 0; index < parsedSkeleton.bones.length; index++) {
  18607. var parsedBone = parsedSkeleton.bones[index];
  18608. var parentBone = null;
  18609. if (parsedBone.parentBoneIndex > -1) {
  18610. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  18611. }
  18612. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix));
  18613. if (parsedBone.animation) {
  18614. bone.animations.push(parseAnimation(parsedBone.animation));
  18615. }
  18616. }
  18617. return skeleton;
  18618. };
  18619. var parseFresnelParameters = function (parsedFresnelParameters) {
  18620. var fresnelParameters = new BABYLON.FresnelParameters();
  18621. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  18622. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  18623. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  18624. fresnelParameters.bias = parsedFresnelParameters.bias;
  18625. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  18626. return fresnelParameters;
  18627. };
  18628. var parseMaterial = function (parsedMaterial, scene, rootUrl) {
  18629. var material;
  18630. material = new BABYLON.StandardMaterial(parsedMaterial.name, scene);
  18631. material.ambientColor = BABYLON.Color3.FromArray(parsedMaterial.ambient);
  18632. material.diffuseColor = BABYLON.Color3.FromArray(parsedMaterial.diffuse);
  18633. material.specularColor = BABYLON.Color3.FromArray(parsedMaterial.specular);
  18634. material.specularPower = parsedMaterial.specularPower;
  18635. material.emissiveColor = BABYLON.Color3.FromArray(parsedMaterial.emissive);
  18636. material.alpha = parsedMaterial.alpha;
  18637. material.id = parsedMaterial.id;
  18638. BABYLON.Tags.AddTagsTo(material, parsedMaterial.tags);
  18639. material.backFaceCulling = parsedMaterial.backFaceCulling;
  18640. material.wireframe = parsedMaterial.wireframe;
  18641. if (parsedMaterial.diffuseTexture) {
  18642. material.diffuseTexture = loadTexture(rootUrl, parsedMaterial.diffuseTexture, scene);
  18643. }
  18644. if (parsedMaterial.diffuseFresnelParameters) {
  18645. material.diffuseFresnelParameters = parseFresnelParameters(parsedMaterial.diffuseFresnelParameters);
  18646. }
  18647. if (parsedMaterial.ambientTexture) {
  18648. material.ambientTexture = loadTexture(rootUrl, parsedMaterial.ambientTexture, scene);
  18649. }
  18650. if (parsedMaterial.opacityTexture) {
  18651. material.opacityTexture = loadTexture(rootUrl, parsedMaterial.opacityTexture, scene);
  18652. }
  18653. if (parsedMaterial.opacityFresnelParameters) {
  18654. material.opacityFresnelParameters = parseFresnelParameters(parsedMaterial.opacityFresnelParameters);
  18655. }
  18656. if (parsedMaterial.reflectionTexture) {
  18657. material.reflectionTexture = loadTexture(rootUrl, parsedMaterial.reflectionTexture, scene);
  18658. }
  18659. if (parsedMaterial.reflectionFresnelParameters) {
  18660. material.reflectionFresnelParameters = parseFresnelParameters(parsedMaterial.reflectionFresnelParameters);
  18661. }
  18662. if (parsedMaterial.emissiveTexture) {
  18663. material.emissiveTexture = loadTexture(rootUrl, parsedMaterial.emissiveTexture, scene);
  18664. }
  18665. if (parsedMaterial.emissiveFresnelParameters) {
  18666. material.emissiveFresnelParameters = parseFresnelParameters(parsedMaterial.emissiveFresnelParameters);
  18667. }
  18668. if (parsedMaterial.specularTexture) {
  18669. material.specularTexture = loadTexture(rootUrl, parsedMaterial.specularTexture, scene);
  18670. }
  18671. if (parsedMaterial.bumpTexture) {
  18672. material.bumpTexture = loadTexture(rootUrl, parsedMaterial.bumpTexture, scene);
  18673. }
  18674. return material;
  18675. };
  18676. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  18677. for (var index = 0; index < parsedData.materials.length; index++) {
  18678. var parsedMaterial = parsedData.materials[index];
  18679. if (parsedMaterial.id === id) {
  18680. return parseMaterial(parsedMaterial, scene, rootUrl);
  18681. }
  18682. }
  18683. return null;
  18684. };
  18685. var parseMultiMaterial = function (parsedMultiMaterial, scene) {
  18686. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  18687. multiMaterial.id = parsedMultiMaterial.id;
  18688. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  18689. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  18690. var subMatId = parsedMultiMaterial.materials[matIndex];
  18691. if (subMatId) {
  18692. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  18693. }
  18694. else {
  18695. multiMaterial.subMaterials.push(null);
  18696. }
  18697. }
  18698. return multiMaterial;
  18699. };
  18700. var parseLensFlareSystem = function (parsedLensFlareSystem, scene, rootUrl) {
  18701. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  18702. var lensFlareSystem = new BABYLON.LensFlareSystem("lensFlareSystem#" + parsedLensFlareSystem.emitterId, emitter, scene);
  18703. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  18704. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  18705. var parsedFlare = parsedLensFlareSystem.flares[index];
  18706. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  18707. }
  18708. return lensFlareSystem;
  18709. };
  18710. var parseParticleSystem = function (parsedParticleSystem, scene, rootUrl) {
  18711. var emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  18712. var particleSystem = new BABYLON.ParticleSystem("particles#" + emitter.name, parsedParticleSystem.capacity, scene);
  18713. if (parsedParticleSystem.textureName) {
  18714. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  18715. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  18716. }
  18717. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  18718. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  18719. particleSystem.minSize = parsedParticleSystem.minSize;
  18720. particleSystem.maxSize = parsedParticleSystem.maxSize;
  18721. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  18722. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  18723. particleSystem.emitter = emitter;
  18724. particleSystem.emitRate = parsedParticleSystem.emitRate;
  18725. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  18726. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  18727. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  18728. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  18729. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  18730. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  18731. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  18732. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  18733. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  18734. particleSystem.targetStopDuration = parsedParticleSystem.targetStopFrame;
  18735. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  18736. particleSystem.blendMode = parsedParticleSystem.blendMode;
  18737. particleSystem.start();
  18738. return particleSystem;
  18739. };
  18740. var parseShadowGenerator = function (parsedShadowGenerator, scene) {
  18741. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  18742. var shadowGenerator = new BABYLON.ShadowGenerator(parsedShadowGenerator.mapSize, light);
  18743. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  18744. var mesh = scene.getMeshByID(parsedShadowGenerator.renderList[meshIndex]);
  18745. shadowGenerator.getShadowMap().renderList.push(mesh);
  18746. }
  18747. if (parsedShadowGenerator.usePoissonSampling) {
  18748. shadowGenerator.usePoissonSampling = true;
  18749. }
  18750. else {
  18751. shadowGenerator.useVarianceShadowMap = parsedShadowGenerator.useVarianceShadowMap;
  18752. }
  18753. return shadowGenerator;
  18754. };
  18755. var parseAnimation = function (parsedAnimation) {
  18756. var animation = new BABYLON.Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  18757. var dataType = parsedAnimation.dataType;
  18758. var keys = [];
  18759. for (var index = 0; index < parsedAnimation.keys.length; index++) {
  18760. var key = parsedAnimation.keys[index];
  18761. var data;
  18762. switch (dataType) {
  18763. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  18764. data = key.values[0];
  18765. break;
  18766. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  18767. data = BABYLON.Quaternion.FromArray(key.values);
  18768. break;
  18769. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  18770. data = BABYLON.Matrix.FromArray(key.values);
  18771. break;
  18772. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  18773. default:
  18774. data = BABYLON.Vector3.FromArray(key.values);
  18775. break;
  18776. }
  18777. keys.push({
  18778. frame: key.frame,
  18779. value: data
  18780. });
  18781. }
  18782. animation.setKeys(keys);
  18783. return animation;
  18784. };
  18785. var parseLight = function (parsedLight, scene) {
  18786. var light;
  18787. switch (parsedLight.type) {
  18788. case 0:
  18789. light = new BABYLON.PointLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), scene);
  18790. break;
  18791. case 1:
  18792. light = new BABYLON.DirectionalLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18793. light.position = BABYLON.Vector3.FromArray(parsedLight.position);
  18794. break;
  18795. case 2:
  18796. light = new BABYLON.SpotLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.position), BABYLON.Vector3.FromArray(parsedLight.direction), parsedLight.angle, parsedLight.exponent, scene);
  18797. break;
  18798. case 3:
  18799. light = new BABYLON.HemisphericLight(parsedLight.name, BABYLON.Vector3.FromArray(parsedLight.direction), scene);
  18800. light.groundColor = BABYLON.Color3.FromArray(parsedLight.groundColor);
  18801. break;
  18802. }
  18803. light.id = parsedLight.id;
  18804. BABYLON.Tags.AddTagsTo(light, parsedLight.tags);
  18805. if (parsedLight.intensity !== undefined) {
  18806. light.intensity = parsedLight.intensity;
  18807. }
  18808. if (parsedLight.range) {
  18809. light.range = parsedLight.range;
  18810. }
  18811. light.diffuse = BABYLON.Color3.FromArray(parsedLight.diffuse);
  18812. light.specular = BABYLON.Color3.FromArray(parsedLight.specular);
  18813. if (parsedLight.excludedMeshesIds) {
  18814. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  18815. }
  18816. // Parent
  18817. if (parsedLight.parentId) {
  18818. light._waitingParentId = parsedLight.parentId;
  18819. }
  18820. if (parsedLight.includedOnlyMeshesIds) {
  18821. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  18822. }
  18823. // Animations
  18824. if (parsedLight.animations) {
  18825. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  18826. var parsedAnimation = parsedLight.animations[animationIndex];
  18827. light.animations.push(parseAnimation(parsedAnimation));
  18828. }
  18829. }
  18830. if (parsedLight.autoAnimate) {
  18831. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, 1.0);
  18832. }
  18833. };
  18834. var parseCamera = function (parsedCamera, scene) {
  18835. var camera;
  18836. var position = BABYLON.Vector3.FromArray(parsedCamera.position);
  18837. var lockedTargetMesh = (parsedCamera.lockedTargetId) ? scene.getLastMeshByID(parsedCamera.lockedTargetId) : null;
  18838. if (parsedCamera.type === "AnaglyphArcRotateCamera" || parsedCamera.type === "ArcRotateCamera") {
  18839. var alpha = parsedCamera.alpha;
  18840. var beta = parsedCamera.beta;
  18841. var radius = parsedCamera.radius;
  18842. if (parsedCamera.type === "AnaglyphArcRotateCamera") {
  18843. var eye_space = parsedCamera.eye_space;
  18844. camera = new BABYLON.AnaglyphArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, eye_space, scene);
  18845. }
  18846. else {
  18847. camera = new BABYLON.ArcRotateCamera(parsedCamera.name, alpha, beta, radius, lockedTargetMesh, scene);
  18848. }
  18849. }
  18850. else if (parsedCamera.type === "AnaglyphFreeCamera") {
  18851. eye_space = parsedCamera.eye_space;
  18852. camera = new BABYLON.AnaglyphFreeCamera(parsedCamera.name, position, eye_space, scene);
  18853. }
  18854. else if (parsedCamera.type === "DeviceOrientationCamera") {
  18855. camera = new BABYLON.DeviceOrientationCamera(parsedCamera.name, position, scene);
  18856. }
  18857. else if (parsedCamera.type === "FollowCamera") {
  18858. camera = new BABYLON.FollowCamera(parsedCamera.name, position, scene);
  18859. camera.heightOffset = parsedCamera.heightOffset;
  18860. camera.radius = parsedCamera.radius;
  18861. camera.rotationOffset = parsedCamera.rotationOffset;
  18862. if (lockedTargetMesh)
  18863. camera.target = lockedTargetMesh;
  18864. }
  18865. else if (parsedCamera.type === "GamepadCamera") {
  18866. camera = new BABYLON.GamepadCamera(parsedCamera.name, position, scene);
  18867. }
  18868. else if (parsedCamera.type === "OculusCamera") {
  18869. camera = new BABYLON.OculusCamera(parsedCamera.name, position, scene);
  18870. }
  18871. else if (parsedCamera.type === "OculusGamepadCamera") {
  18872. camera = new BABYLON.OculusGamepadCamera(parsedCamera.name, position, scene);
  18873. }
  18874. else if (parsedCamera.type === "TouchCamera") {
  18875. camera = new BABYLON.TouchCamera(parsedCamera.name, position, scene);
  18876. }
  18877. else if (parsedCamera.type === "VirtualJoysticksCamera") {
  18878. camera = new BABYLON.VirtualJoysticksCamera(parsedCamera.name, position, scene);
  18879. }
  18880. else if (parsedCamera.type === "WebVRCamera") {
  18881. camera = new BABYLON.WebVRCamera(parsedCamera.name, position, scene);
  18882. }
  18883. else if (parsedCamera.type === "VRDeviceOrientationCamera") {
  18884. camera = new BABYLON.VRDeviceOrientationCamera(parsedCamera.name, position, scene);
  18885. }
  18886. else {
  18887. // Free Camera is the default value
  18888. camera = new BABYLON.FreeCamera(parsedCamera.name, position, scene);
  18889. }
  18890. // Test for lockedTargetMesh & FreeCamera outside of if-else-if nest, since things like GamepadCamera extend FreeCamera
  18891. if (lockedTargetMesh && camera instanceof BABYLON.FreeCamera) {
  18892. camera.lockedTarget = lockedTargetMesh;
  18893. }
  18894. camera.id = parsedCamera.id;
  18895. BABYLON.Tags.AddTagsTo(camera, parsedCamera.tags);
  18896. // Parent
  18897. if (parsedCamera.parentId) {
  18898. camera._waitingParentId = parsedCamera.parentId;
  18899. }
  18900. // Target
  18901. if (parsedCamera.target) {
  18902. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  18903. }
  18904. else {
  18905. camera.rotation = BABYLON.Vector3.FromArray(parsedCamera.rotation);
  18906. }
  18907. camera.fov = parsedCamera.fov;
  18908. camera.minZ = parsedCamera.minZ;
  18909. camera.maxZ = parsedCamera.maxZ;
  18910. camera.speed = parsedCamera.speed;
  18911. camera.inertia = parsedCamera.inertia;
  18912. camera.checkCollisions = parsedCamera.checkCollisions;
  18913. camera.applyGravity = parsedCamera.applyGravity;
  18914. if (parsedCamera.ellipsoid) {
  18915. camera.ellipsoid = BABYLON.Vector3.FromArray(parsedCamera.ellipsoid);
  18916. }
  18917. // Animations
  18918. if (parsedCamera.animations) {
  18919. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  18920. var parsedAnimation = parsedCamera.animations[animationIndex];
  18921. camera.animations.push(parseAnimation(parsedAnimation));
  18922. }
  18923. }
  18924. if (parsedCamera.autoAnimate) {
  18925. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, 1.0);
  18926. }
  18927. // Layer Mask
  18928. if (parsedCamera.layerMask && (!isNaN(parsedCamera.layerMask))) {
  18929. camera.layerMask = Math.abs(parseInt(parsedCamera.layerMask));
  18930. }
  18931. else {
  18932. camera.layerMask = 0xFFFFFFFF;
  18933. }
  18934. return camera;
  18935. };
  18936. var parseGeometry = function (parsedGeometry, scene) {
  18937. var id = parsedGeometry.id;
  18938. return scene.getGeometryByID(id);
  18939. };
  18940. var parseBox = function (parsedBox, scene) {
  18941. if (parseGeometry(parsedBox, scene)) {
  18942. return null; // null since geometry could be something else than a box...
  18943. }
  18944. var box = new BABYLON.Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  18945. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  18946. scene.pushGeometry(box, true);
  18947. return box;
  18948. };
  18949. var parseSphere = function (parsedSphere, scene) {
  18950. if (parseGeometry(parsedSphere, scene)) {
  18951. return null; // null since geometry could be something else than a sphere...
  18952. }
  18953. var sphere = new BABYLON.Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  18954. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  18955. scene.pushGeometry(sphere, true);
  18956. return sphere;
  18957. };
  18958. var parseCylinder = function (parsedCylinder, scene) {
  18959. if (parseGeometry(parsedCylinder, scene)) {
  18960. return null; // null since geometry could be something else than a cylinder...
  18961. }
  18962. var cylinder = new BABYLON.Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  18963. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  18964. scene.pushGeometry(cylinder, true);
  18965. return cylinder;
  18966. };
  18967. var parseTorus = function (parsedTorus, scene) {
  18968. if (parseGeometry(parsedTorus, scene)) {
  18969. return null; // null since geometry could be something else than a torus...
  18970. }
  18971. var torus = new BABYLON.Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  18972. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  18973. scene.pushGeometry(torus, true);
  18974. return torus;
  18975. };
  18976. var parseGround = function (parsedGround, scene) {
  18977. if (parseGeometry(parsedGround, scene)) {
  18978. return null; // null since geometry could be something else than a ground...
  18979. }
  18980. var ground = new BABYLON.Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  18981. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  18982. scene.pushGeometry(ground, true);
  18983. return ground;
  18984. };
  18985. var parsePlane = function (parsedPlane, scene) {
  18986. if (parseGeometry(parsedPlane, scene)) {
  18987. return null; // null since geometry could be something else than a plane...
  18988. }
  18989. var plane = new BABYLON.Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  18990. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  18991. scene.pushGeometry(plane, true);
  18992. return plane;
  18993. };
  18994. var parseTorusKnot = function (parsedTorusKnot, scene) {
  18995. if (parseGeometry(parsedTorusKnot, scene)) {
  18996. return null; // null since geometry could be something else than a torusKnot...
  18997. }
  18998. 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);
  18999. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  19000. scene.pushGeometry(torusKnot, true);
  19001. return torusKnot;
  19002. };
  19003. var parseVertexData = function (parsedVertexData, scene, rootUrl) {
  19004. if (parseGeometry(parsedVertexData, scene)) {
  19005. return null; // null since geometry could be a primitive
  19006. }
  19007. var geometry = new BABYLON.Geometry(parsedVertexData.id, scene);
  19008. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  19009. if (parsedVertexData.delayLoadingFile) {
  19010. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19011. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  19012. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  19013. geometry._delayInfo = [];
  19014. if (parsedVertexData.hasUVs) {
  19015. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19016. }
  19017. if (parsedVertexData.hasUVs2) {
  19018. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19019. }
  19020. if (parsedVertexData.hasColors) {
  19021. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19022. }
  19023. if (parsedVertexData.hasMatricesIndices) {
  19024. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19025. }
  19026. if (parsedVertexData.hasMatricesWeights) {
  19027. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19028. }
  19029. geometry._delayLoadingFunction = importVertexData;
  19030. }
  19031. else {
  19032. importVertexData(parsedVertexData, geometry);
  19033. }
  19034. scene.pushGeometry(geometry, true);
  19035. return geometry;
  19036. };
  19037. var parseMesh = function (parsedMesh, scene, rootUrl) {
  19038. var mesh = new BABYLON.Mesh(parsedMesh.name, scene);
  19039. mesh.id = parsedMesh.id;
  19040. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  19041. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  19042. if (parsedMesh.rotationQuaternion) {
  19043. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  19044. }
  19045. else if (parsedMesh.rotation) {
  19046. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  19047. }
  19048. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  19049. if (parsedMesh.localMatrix) {
  19050. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  19051. }
  19052. else if (parsedMesh.pivotMatrix) {
  19053. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  19054. }
  19055. mesh.setEnabled(parsedMesh.isEnabled);
  19056. mesh.isVisible = parsedMesh.isVisible;
  19057. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  19058. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  19059. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  19060. if (parsedMesh.applyFog !== undefined) {
  19061. mesh.applyFog = parsedMesh.applyFog;
  19062. }
  19063. if (parsedMesh.pickable !== undefined) {
  19064. mesh.isPickable = parsedMesh.pickable;
  19065. }
  19066. if (parsedMesh.alphaIndex !== undefined) {
  19067. mesh.alphaIndex = parsedMesh.alphaIndex;
  19068. }
  19069. mesh.receiveShadows = parsedMesh.receiveShadows;
  19070. mesh.billboardMode = parsedMesh.billboardMode;
  19071. if (parsedMesh.visibility !== undefined) {
  19072. mesh.visibility = parsedMesh.visibility;
  19073. }
  19074. mesh.checkCollisions = parsedMesh.checkCollisions;
  19075. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  19076. // Parent
  19077. if (parsedMesh.parentId) {
  19078. mesh._waitingParentId = parsedMesh.parentId;
  19079. }
  19080. // Actions
  19081. if (parsedMesh.actions !== undefined) {
  19082. mesh._waitingActions = parsedMesh.actions;
  19083. }
  19084. // Geometry
  19085. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  19086. if (parsedMesh.delayLoadingFile) {
  19087. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  19088. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  19089. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  19090. if (parsedMesh._binaryInfo) {
  19091. mesh._binaryInfo = parsedMesh._binaryInfo;
  19092. }
  19093. mesh._delayInfo = [];
  19094. if (parsedMesh.hasUVs) {
  19095. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  19096. }
  19097. if (parsedMesh.hasUVs2) {
  19098. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  19099. }
  19100. if (parsedMesh.hasColors) {
  19101. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  19102. }
  19103. if (parsedMesh.hasMatricesIndices) {
  19104. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  19105. }
  19106. if (parsedMesh.hasMatricesWeights) {
  19107. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  19108. }
  19109. mesh._delayLoadingFunction = importGeometry;
  19110. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  19111. mesh._checkDelayState();
  19112. }
  19113. }
  19114. else {
  19115. importGeometry(parsedMesh, mesh);
  19116. }
  19117. // Material
  19118. if (parsedMesh.materialId) {
  19119. mesh.setMaterialByID(parsedMesh.materialId);
  19120. }
  19121. else {
  19122. mesh.material = null;
  19123. }
  19124. // Skeleton
  19125. if (parsedMesh.skeletonId > -1) {
  19126. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  19127. }
  19128. // Physics
  19129. if (parsedMesh.physicsImpostor) {
  19130. if (!scene.isPhysicsEnabled()) {
  19131. scene.enablePhysics();
  19132. }
  19133. mesh.setPhysicsState({ impostor: parsedMesh.physicsImpostor, mass: parsedMesh.physicsMass, friction: parsedMesh.physicsFriction, restitution: parsedMesh.physicsRestitution });
  19134. }
  19135. // Animations
  19136. if (parsedMesh.animations) {
  19137. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19138. var parsedAnimation = parsedMesh.animations[animationIndex];
  19139. mesh.animations.push(parseAnimation(parsedAnimation));
  19140. }
  19141. }
  19142. if (parsedMesh.autoAnimate) {
  19143. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, 1.0);
  19144. }
  19145. // Layer Mask
  19146. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  19147. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  19148. }
  19149. else {
  19150. mesh.layerMask = 0xFFFFFFFF;
  19151. }
  19152. // Instances
  19153. if (parsedMesh.instances) {
  19154. for (var index = 0; index < parsedMesh.instances.length; index++) {
  19155. var parsedInstance = parsedMesh.instances[index];
  19156. var instance = mesh.createInstance(parsedInstance.name);
  19157. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  19158. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  19159. if (parsedInstance.rotationQuaternion) {
  19160. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  19161. }
  19162. else if (parsedInstance.rotation) {
  19163. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  19164. }
  19165. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  19166. instance.checkCollisions = mesh.checkCollisions;
  19167. if (parsedMesh.animations) {
  19168. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  19169. parsedAnimation = parsedMesh.animations[animationIndex];
  19170. instance.animations.push(parseAnimation(parsedAnimation));
  19171. }
  19172. }
  19173. }
  19174. }
  19175. return mesh;
  19176. };
  19177. var parseActions = function (parsedActions, object, scene) {
  19178. var actionManager = new BABYLON.ActionManager(scene);
  19179. if (object === null)
  19180. scene.actionManager = actionManager;
  19181. else
  19182. object.actionManager = actionManager;
  19183. // instanciate a new object
  19184. var instanciate = function (name, params) {
  19185. var newInstance = Object.create(BABYLON[name].prototype);
  19186. newInstance.constructor.apply(newInstance, params);
  19187. return newInstance;
  19188. };
  19189. var parseParameter = function (name, value, target, propertyPath) {
  19190. if (propertyPath === null) {
  19191. // String, boolean or float
  19192. var floatValue = parseFloat(value);
  19193. if (value === "true" || value === "false")
  19194. return value === "true";
  19195. else
  19196. return isNaN(floatValue) ? value : floatValue;
  19197. }
  19198. var effectiveTarget = propertyPath.split(".");
  19199. var values = value.split(",");
  19200. for (var i = 0; i < effectiveTarget.length; i++) {
  19201. target = target[effectiveTarget[i]];
  19202. }
  19203. // Return appropriate value with its type
  19204. if (target instanceof Boolean)
  19205. return values[0] === "true";
  19206. if (target instanceof String)
  19207. return values[0];
  19208. // Parameters with multiple values such as Vector3 etc.
  19209. var split = new Array();
  19210. for (var i = 0; i < values.length; i++)
  19211. split.push(parseFloat(values[i]));
  19212. if (target instanceof BABYLON.Vector3)
  19213. return BABYLON.Vector3.FromArray(split);
  19214. if (target instanceof BABYLON.Vector4)
  19215. return BABYLON.Vector4.FromArray(split);
  19216. if (target instanceof BABYLON.Color3)
  19217. return BABYLON.Color3.FromArray(split);
  19218. if (target instanceof BABYLON.Color4)
  19219. return BABYLON.Color4.FromArray(split);
  19220. return parseFloat(values[0]);
  19221. };
  19222. // traverse graph per trigger
  19223. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  19224. if (combineArray === void 0) { combineArray = null; }
  19225. if (parsedAction.detached)
  19226. return;
  19227. var parameters = new Array();
  19228. var target = null;
  19229. var propertyPath = null;
  19230. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  19231. // Parameters
  19232. if (parsedAction.type === 2)
  19233. parameters.push(actionManager);
  19234. else
  19235. parameters.push(trigger);
  19236. if (combine) {
  19237. var actions = new Array();
  19238. for (var j = 0; j < parsedAction.combine.length; j++) {
  19239. traverse(parsedAction.combine[j], BABYLON.ActionManager.NothingTrigger, condition, action, actions);
  19240. }
  19241. parameters.push(actions);
  19242. }
  19243. else {
  19244. for (var i = 0; i < parsedAction.properties.length; i++) {
  19245. var value = parsedAction.properties[i].value;
  19246. var name = parsedAction.properties[i].name;
  19247. if (name === "target")
  19248. value = target = scene.getNodeByName(value);
  19249. else if (name === "parent")
  19250. value = scene.getNodeByName(value);
  19251. else if (name === "sound")
  19252. value = scene.getSoundByName(value);
  19253. else if (name !== "propertyPath") {
  19254. if (parsedAction.type === 2 && name === "operator")
  19255. value = BABYLON.ValueCondition[value];
  19256. else
  19257. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  19258. }
  19259. else {
  19260. propertyPath = value;
  19261. }
  19262. parameters.push(value);
  19263. }
  19264. }
  19265. parameters.push(condition);
  19266. // If interpolate value action
  19267. if (parsedAction.name === "InterpolateValueAction") {
  19268. var param = parameters[parameters.length - 2];
  19269. parameters[parameters.length - 1] = param;
  19270. parameters[parameters.length - 2] = condition;
  19271. }
  19272. // Action or condition(s) and not CombineAction
  19273. var newAction = instanciate(parsedAction.name, parameters);
  19274. if (combineArray === null) {
  19275. if (newAction instanceof BABYLON.Condition) {
  19276. condition = newAction;
  19277. newAction = action;
  19278. }
  19279. else {
  19280. condition = null;
  19281. if (action)
  19282. action.then(newAction);
  19283. else
  19284. actionManager.registerAction(newAction);
  19285. }
  19286. }
  19287. else {
  19288. if (combineArray !== null)
  19289. combineArray.push(newAction);
  19290. }
  19291. for (var i = 0; i < parsedAction.children.length; i++)
  19292. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  19293. };
  19294. for (var i = 0; i < parsedActions.children.length; i++) {
  19295. var triggerParams;
  19296. var trigger = parsedActions.children[i];
  19297. if (trigger.properties.length > 0) {
  19298. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: scene.getMeshByName(trigger.properties[0].value) };
  19299. }
  19300. else
  19301. triggerParams = BABYLON.ActionManager[trigger.name];
  19302. for (var j = 0; j < trigger.children.length; j++)
  19303. traverse(trigger.children[j], triggerParams, null, null);
  19304. }
  19305. };
  19306. var parseSound = function (parsedSound, scene, rootUrl) {
  19307. var soundName = parsedSound.name;
  19308. var soundUrl = rootUrl + soundName;
  19309. var options = {
  19310. autoplay: parsedSound.autoplay,
  19311. loop: parsedSound.loop,
  19312. volume: parsedSound.volume,
  19313. spatialSound: parsedSound.spatialSound,
  19314. maxDistance: parsedSound.maxDistance,
  19315. rolloffFactor: parsedSound.rolloffFactor,
  19316. refDistance: parsedSound.refDistance,
  19317. distanceModel: parsedSound.distanceModel,
  19318. panningModel: parsedSound.panningModel,
  19319. playbackRate: parsedSound.playbackRate
  19320. };
  19321. var newSound = new BABYLON.Sound(soundName, soundUrl, scene, function () {
  19322. scene._removePendingData(newSound);
  19323. }, options);
  19324. scene._addPendingData(newSound);
  19325. if (parsedSound.position) {
  19326. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  19327. newSound.setPosition(soundPosition);
  19328. }
  19329. if (parsedSound.isDirectional) {
  19330. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  19331. if (parsedSound.localDirectionToMesh) {
  19332. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  19333. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  19334. }
  19335. }
  19336. if (parsedSound.connectedMeshId) {
  19337. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  19338. if (connectedMesh) {
  19339. newSound.attachToMesh(connectedMesh);
  19340. }
  19341. }
  19342. };
  19343. var isDescendantOf = function (mesh, names, hierarchyIds) {
  19344. names = (names instanceof Array) ? names : [names];
  19345. for (var i in names) {
  19346. if (mesh.name === names[i]) {
  19347. hierarchyIds.push(mesh.id);
  19348. return true;
  19349. }
  19350. }
  19351. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  19352. hierarchyIds.push(mesh.id);
  19353. return true;
  19354. }
  19355. return false;
  19356. };
  19357. var importVertexData = function (parsedVertexData, geometry) {
  19358. var vertexData = new BABYLON.VertexData();
  19359. // positions
  19360. var positions = parsedVertexData.positions;
  19361. if (positions) {
  19362. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  19363. }
  19364. // normals
  19365. var normals = parsedVertexData.normals;
  19366. if (normals) {
  19367. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  19368. }
  19369. // uvs
  19370. var uvs = parsedVertexData.uvs;
  19371. if (uvs) {
  19372. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  19373. }
  19374. // uv2s
  19375. var uv2s = parsedVertexData.uv2s;
  19376. if (uv2s) {
  19377. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  19378. }
  19379. // colors
  19380. var colors = parsedVertexData.colors;
  19381. if (colors) {
  19382. vertexData.set(checkColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  19383. }
  19384. // matricesIndices
  19385. var matricesIndices = parsedVertexData.matricesIndices;
  19386. if (matricesIndices) {
  19387. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  19388. }
  19389. // matricesWeights
  19390. var matricesWeights = parsedVertexData.matricesWeights;
  19391. if (matricesWeights) {
  19392. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  19393. }
  19394. // indices
  19395. var indices = parsedVertexData.indices;
  19396. if (indices) {
  19397. vertexData.indices = indices;
  19398. }
  19399. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  19400. };
  19401. var importGeometry = function (parsedGeometry, mesh) {
  19402. var scene = mesh.getScene();
  19403. // Geometry
  19404. var geometryId = parsedGeometry.geometryId;
  19405. if (geometryId) {
  19406. var geometry = scene.getGeometryByID(geometryId);
  19407. if (geometry) {
  19408. geometry.applyToMesh(mesh);
  19409. }
  19410. }
  19411. else if (parsedGeometry instanceof ArrayBuffer) {
  19412. var binaryInfo = mesh._binaryInfo;
  19413. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  19414. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  19415. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  19416. }
  19417. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  19418. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  19419. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  19420. }
  19421. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  19422. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  19423. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  19424. }
  19425. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  19426. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  19427. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  19428. }
  19429. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  19430. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  19431. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false);
  19432. }
  19433. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  19434. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  19435. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  19436. }
  19437. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  19438. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  19439. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  19440. }
  19441. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  19442. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  19443. mesh.setIndices(indicesData);
  19444. }
  19445. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  19446. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  19447. mesh.subMeshes = [];
  19448. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  19449. var materialIndex = subMeshesData[(i * 5) + 0];
  19450. var verticesStart = subMeshesData[(i * 5) + 1];
  19451. var verticesCount = subMeshesData[(i * 5) + 2];
  19452. var indexStart = subMeshesData[(i * 5) + 3];
  19453. var indexCount = subMeshesData[(i * 5) + 4];
  19454. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  19455. }
  19456. }
  19457. }
  19458. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  19459. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  19460. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  19461. if (parsedGeometry.uvs) {
  19462. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  19463. }
  19464. if (parsedGeometry.uvs2) {
  19465. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  19466. }
  19467. if (parsedGeometry.colors) {
  19468. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, checkColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  19469. }
  19470. if (parsedGeometry.matricesIndices) {
  19471. if (!parsedGeometry.matricesIndices._isExpanded) {
  19472. var floatIndices = [];
  19473. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  19474. var matricesIndex = parsedGeometry.matricesIndices[i];
  19475. floatIndices.push(matricesIndex & 0x000000FF);
  19476. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  19477. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  19478. floatIndices.push(matricesIndex >> 24);
  19479. }
  19480. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  19481. }
  19482. else {
  19483. delete parsedGeometry.matricesIndices._isExpanded;
  19484. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  19485. }
  19486. }
  19487. if (parsedGeometry.matricesWeights) {
  19488. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  19489. }
  19490. mesh.setIndices(parsedGeometry.indices);
  19491. // SubMeshes
  19492. if (parsedGeometry.subMeshes) {
  19493. mesh.subMeshes = [];
  19494. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  19495. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  19496. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  19497. }
  19498. }
  19499. }
  19500. // Flat shading
  19501. if (mesh._shouldGenerateFlatShading) {
  19502. mesh.convertToFlatShadedMesh();
  19503. delete mesh._shouldGenerateFlatShading;
  19504. }
  19505. // Update
  19506. mesh.computeWorldMatrix(true);
  19507. // Octree
  19508. if (scene._selectionOctree) {
  19509. scene._selectionOctree.addMesh(mesh);
  19510. }
  19511. };
  19512. BABYLON.SceneLoader.RegisterPlugin({
  19513. extensions: ".babylon",
  19514. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  19515. var parsedData = JSON.parse(data);
  19516. var loadedSkeletonsIds = [];
  19517. var loadedMaterialsIds = [];
  19518. var hierarchyIds = [];
  19519. for (var index = 0; index < parsedData.meshes.length; index++) {
  19520. var parsedMesh = parsedData.meshes[index];
  19521. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  19522. if (meshesNames instanceof Array) {
  19523. // Remove found mesh name from list.
  19524. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  19525. }
  19526. // Material ?
  19527. if (parsedMesh.materialId) {
  19528. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  19529. if (!materialFound) {
  19530. for (var multimatIndex = 0; multimatIndex < parsedData.multiMaterials.length; multimatIndex++) {
  19531. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  19532. if (parsedMultiMaterial.id == parsedMesh.materialId) {
  19533. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  19534. var subMatId = parsedMultiMaterial.materials[matIndex];
  19535. loadedMaterialsIds.push(subMatId);
  19536. parseMaterialById(subMatId, parsedData, scene, rootUrl);
  19537. }
  19538. loadedMaterialsIds.push(parsedMultiMaterial.id);
  19539. parseMultiMaterial(parsedMultiMaterial, scene);
  19540. materialFound = true;
  19541. break;
  19542. }
  19543. }
  19544. }
  19545. if (!materialFound) {
  19546. loadedMaterialsIds.push(parsedMesh.materialId);
  19547. parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  19548. }
  19549. }
  19550. // Skeleton ?
  19551. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  19552. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  19553. if (!skeletonAlreadyLoaded) {
  19554. for (var skeletonIndex = 0; skeletonIndex < parsedData.skeletons.length; skeletonIndex++) {
  19555. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  19556. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  19557. skeletons.push(parseSkeleton(parsedSkeleton, scene));
  19558. loadedSkeletonsIds.push(parsedSkeleton.id);
  19559. }
  19560. }
  19561. }
  19562. }
  19563. var mesh = parseMesh(parsedMesh, scene, rootUrl);
  19564. meshes.push(mesh);
  19565. }
  19566. }
  19567. for (index = 0; index < scene.meshes.length; index++) {
  19568. var currentMesh = scene.meshes[index];
  19569. if (currentMesh._waitingParentId) {
  19570. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  19571. currentMesh._waitingParentId = undefined;
  19572. }
  19573. }
  19574. // Particles
  19575. if (parsedData.particleSystems) {
  19576. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19577. var parsedParticleSystem = parsedData.particleSystems[index];
  19578. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  19579. particleSystems.push(parseParticleSystem(parsedParticleSystem, scene, rootUrl));
  19580. }
  19581. }
  19582. }
  19583. return true;
  19584. },
  19585. load: function (scene, data, rootUrl) {
  19586. var parsedData = JSON.parse(data);
  19587. // Scene
  19588. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  19589. scene.autoClear = parsedData.autoClear;
  19590. scene.clearColor = BABYLON.Color3.FromArray(parsedData.clearColor);
  19591. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  19592. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  19593. // Fog
  19594. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  19595. scene.fogMode = parsedData.fogMode;
  19596. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  19597. scene.fogStart = parsedData.fogStart;
  19598. scene.fogEnd = parsedData.fogEnd;
  19599. scene.fogDensity = parsedData.fogDensity;
  19600. }
  19601. for (var index = 0; index < parsedData.lights.length; index++) {
  19602. var parsedLight = parsedData.lights[index];
  19603. parseLight(parsedLight, scene);
  19604. }
  19605. // Materials
  19606. if (parsedData.materials) {
  19607. for (index = 0; index < parsedData.materials.length; index++) {
  19608. var parsedMaterial = parsedData.materials[index];
  19609. parseMaterial(parsedMaterial, scene, rootUrl);
  19610. }
  19611. }
  19612. if (parsedData.multiMaterials) {
  19613. for (index = 0; index < parsedData.multiMaterials.length; index++) {
  19614. var parsedMultiMaterial = parsedData.multiMaterials[index];
  19615. parseMultiMaterial(parsedMultiMaterial, scene);
  19616. }
  19617. }
  19618. // Skeletons
  19619. if (parsedData.skeletons) {
  19620. for (index = 0; index < parsedData.skeletons.length; index++) {
  19621. var parsedSkeleton = parsedData.skeletons[index];
  19622. parseSkeleton(parsedSkeleton, scene);
  19623. }
  19624. }
  19625. // Geometries
  19626. var geometries = parsedData.geometries;
  19627. if (geometries) {
  19628. // Boxes
  19629. var boxes = geometries.boxes;
  19630. if (boxes) {
  19631. for (index = 0; index < boxes.length; index++) {
  19632. var parsedBox = boxes[index];
  19633. parseBox(parsedBox, scene);
  19634. }
  19635. }
  19636. // Spheres
  19637. var spheres = geometries.spheres;
  19638. if (spheres) {
  19639. for (index = 0; index < spheres.length; index++) {
  19640. var parsedSphere = spheres[index];
  19641. parseSphere(parsedSphere, scene);
  19642. }
  19643. }
  19644. // Cylinders
  19645. var cylinders = geometries.cylinders;
  19646. if (cylinders) {
  19647. for (index = 0; index < cylinders.length; index++) {
  19648. var parsedCylinder = cylinders[index];
  19649. parseCylinder(parsedCylinder, scene);
  19650. }
  19651. }
  19652. // Toruses
  19653. var toruses = geometries.toruses;
  19654. if (toruses) {
  19655. for (index = 0; index < toruses.length; index++) {
  19656. var parsedTorus = toruses[index];
  19657. parseTorus(parsedTorus, scene);
  19658. }
  19659. }
  19660. // Grounds
  19661. var grounds = geometries.grounds;
  19662. if (grounds) {
  19663. for (index = 0; index < grounds.length; index++) {
  19664. var parsedGround = grounds[index];
  19665. parseGround(parsedGround, scene);
  19666. }
  19667. }
  19668. // Planes
  19669. var planes = geometries.planes;
  19670. if (planes) {
  19671. for (index = 0; index < planes.length; index++) {
  19672. var parsedPlane = planes[index];
  19673. parsePlane(parsedPlane, scene);
  19674. }
  19675. }
  19676. // TorusKnots
  19677. var torusKnots = geometries.torusKnots;
  19678. if (torusKnots) {
  19679. for (index = 0; index < torusKnots.length; index++) {
  19680. var parsedTorusKnot = torusKnots[index];
  19681. parseTorusKnot(parsedTorusKnot, scene);
  19682. }
  19683. }
  19684. // VertexData
  19685. var vertexData = geometries.vertexData;
  19686. if (vertexData) {
  19687. for (index = 0; index < vertexData.length; index++) {
  19688. var parsedVertexData = vertexData[index];
  19689. parseVertexData(parsedVertexData, scene, rootUrl);
  19690. }
  19691. }
  19692. }
  19693. for (index = 0; index < parsedData.meshes.length; index++) {
  19694. var parsedMesh = parsedData.meshes[index];
  19695. parseMesh(parsedMesh, scene, rootUrl);
  19696. }
  19697. for (index = 0; index < parsedData.cameras.length; index++) {
  19698. var parsedCamera = parsedData.cameras[index];
  19699. parseCamera(parsedCamera, scene);
  19700. }
  19701. if (parsedData.activeCameraID) {
  19702. scene.setActiveCameraByID(parsedData.activeCameraID);
  19703. }
  19704. for (index = 0; index < scene.cameras.length; index++) {
  19705. var camera = scene.cameras[index];
  19706. if (camera._waitingParentId) {
  19707. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  19708. camera._waitingParentId = undefined;
  19709. }
  19710. }
  19711. for (index = 0; index < scene.lights.length; index++) {
  19712. var light = scene.lights[index];
  19713. if (light._waitingParentId) {
  19714. light.parent = scene.getLastEntryByID(light._waitingParentId);
  19715. light._waitingParentId = undefined;
  19716. }
  19717. }
  19718. // Sounds
  19719. if (parsedData.sounds) {
  19720. for (index = 0; index < parsedData.sounds.length; index++) {
  19721. var parsedSound = parsedData.sounds[index];
  19722. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  19723. parseSound(parsedSound, scene, rootUrl);
  19724. }
  19725. else {
  19726. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  19727. }
  19728. }
  19729. }
  19730. for (index = 0; index < scene.meshes.length; index++) {
  19731. var mesh = scene.meshes[index];
  19732. if (mesh._waitingParentId) {
  19733. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  19734. mesh._waitingParentId = undefined;
  19735. }
  19736. if (mesh._waitingActions) {
  19737. parseActions(mesh._waitingActions, mesh, scene);
  19738. mesh._waitingActions = undefined;
  19739. }
  19740. }
  19741. // Particles Systems
  19742. if (parsedData.particleSystems) {
  19743. for (index = 0; index < parsedData.particleSystems.length; index++) {
  19744. var parsedParticleSystem = parsedData.particleSystems[index];
  19745. parseParticleSystem(parsedParticleSystem, scene, rootUrl);
  19746. }
  19747. }
  19748. // Lens flares
  19749. if (parsedData.lensFlareSystems) {
  19750. for (index = 0; index < parsedData.lensFlareSystems.length; index++) {
  19751. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  19752. parseLensFlareSystem(parsedLensFlareSystem, scene, rootUrl);
  19753. }
  19754. }
  19755. // Shadows
  19756. if (parsedData.shadowGenerators) {
  19757. for (index = 0; index < parsedData.shadowGenerators.length; index++) {
  19758. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  19759. parseShadowGenerator(parsedShadowGenerator, scene);
  19760. }
  19761. }
  19762. // Actions (scene)
  19763. if (parsedData.actions) {
  19764. parseActions(parsedData.actions, null, scene);
  19765. }
  19766. // Finish
  19767. return true;
  19768. }
  19769. });
  19770. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  19771. })(BABYLON || (BABYLON = {}));
  19772. //# sourceMappingURL=babylon.babylonFileLoader.js.mapvar BABYLON;
  19773. (function (BABYLON) {
  19774. // Unique ID when we import meshes from Babylon to CSG
  19775. var currentCSGMeshId = 0;
  19776. // # class Vertex
  19777. // Represents a vertex of a polygon. Use your own vertex class instead of this
  19778. // one to provide additional features like texture coordinates and vertex
  19779. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  19780. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  19781. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  19782. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  19783. // is not used anywhere else.
  19784. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  19785. var Vertex = (function () {
  19786. function Vertex(pos, normal, uv) {
  19787. this.pos = pos;
  19788. this.normal = normal;
  19789. this.uv = uv;
  19790. }
  19791. Vertex.prototype.clone = function () {
  19792. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  19793. };
  19794. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  19795. // orientation of a polygon is flipped.
  19796. Vertex.prototype.flip = function () {
  19797. this.normal = this.normal.scale(-1);
  19798. };
  19799. // Create a new vertex between this vertex and `other` by linearly
  19800. // interpolating all properties using a parameter of `t`. Subclasses should
  19801. // override this to interpolate additional properties.
  19802. Vertex.prototype.interpolate = function (other, t) {
  19803. 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));
  19804. };
  19805. return Vertex;
  19806. })();
  19807. // # class Plane
  19808. // Represents a plane in 3D space.
  19809. var Plane = (function () {
  19810. function Plane(normal, w) {
  19811. this.normal = normal;
  19812. this.w = w;
  19813. }
  19814. Plane.FromPoints = function (a, b, c) {
  19815. var v0 = c.subtract(a);
  19816. var v1 = b.subtract(a);
  19817. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  19818. return null;
  19819. }
  19820. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  19821. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  19822. };
  19823. Plane.prototype.clone = function () {
  19824. return new Plane(this.normal.clone(), this.w);
  19825. };
  19826. Plane.prototype.flip = function () {
  19827. this.normal.scaleInPlace(-1);
  19828. this.w = -this.w;
  19829. };
  19830. // Split `polygon` by this plane if needed, then put the polygon or polygon
  19831. // fragments in the appropriate lists. Coplanar polygons go into either
  19832. // `coplanarFront` or `coplanarBack` depending on their orientation with
  19833. // respect to this plane. Polygons in front or in back of this plane go into
  19834. // either `front` or `back`.
  19835. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  19836. var COPLANAR = 0;
  19837. var FRONT = 1;
  19838. var BACK = 2;
  19839. var SPANNING = 3;
  19840. // Classify each point as well as the entire polygon into one of the above
  19841. // four classes.
  19842. var polygonType = 0;
  19843. var types = [];
  19844. for (var i = 0; i < polygon.vertices.length; i++) {
  19845. var t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  19846. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  19847. polygonType |= type;
  19848. types.push(type);
  19849. }
  19850. switch (polygonType) {
  19851. case COPLANAR:
  19852. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  19853. break;
  19854. case FRONT:
  19855. front.push(polygon);
  19856. break;
  19857. case BACK:
  19858. back.push(polygon);
  19859. break;
  19860. case SPANNING:
  19861. var f = [], b = [];
  19862. for (i = 0; i < polygon.vertices.length; i++) {
  19863. var j = (i + 1) % polygon.vertices.length;
  19864. var ti = types[i], tj = types[j];
  19865. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  19866. if (ti != BACK)
  19867. f.push(vi);
  19868. if (ti != FRONT)
  19869. b.push(ti != BACK ? vi.clone() : vi);
  19870. if ((ti | tj) == SPANNING) {
  19871. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  19872. var v = vi.interpolate(vj, t);
  19873. f.push(v);
  19874. b.push(v.clone());
  19875. }
  19876. }
  19877. if (f.length >= 3) {
  19878. var poly = new Polygon(f, polygon.shared);
  19879. if (poly.plane)
  19880. front.push(poly);
  19881. }
  19882. if (b.length >= 3) {
  19883. poly = new Polygon(b, polygon.shared);
  19884. if (poly.plane)
  19885. back.push(poly);
  19886. }
  19887. break;
  19888. }
  19889. };
  19890. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  19891. // point is on the plane.
  19892. Plane.EPSILON = 1e-5;
  19893. return Plane;
  19894. })();
  19895. // # class Polygon
  19896. // Represents a convex polygon. The vertices used to initialize a polygon must
  19897. // be coplanar and form a convex loop.
  19898. //
  19899. // Each convex polygon has a `shared` property, which is shared between all
  19900. // polygons that are clones of each other or were split from the same polygon.
  19901. // This can be used to define per-polygon properties (such as surface color).
  19902. var Polygon = (function () {
  19903. function Polygon(vertices, shared) {
  19904. this.vertices = vertices;
  19905. this.shared = shared;
  19906. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  19907. }
  19908. Polygon.prototype.clone = function () {
  19909. var vertices = this.vertices.map(function (v) { return v.clone(); });
  19910. return new Polygon(vertices, this.shared);
  19911. };
  19912. Polygon.prototype.flip = function () {
  19913. this.vertices.reverse().map(function (v) {
  19914. v.flip();
  19915. });
  19916. this.plane.flip();
  19917. };
  19918. return Polygon;
  19919. })();
  19920. // # class Node
  19921. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  19922. // by picking a polygon to split along. That polygon (and all other coplanar
  19923. // polygons) are added directly to that node and the other polygons are added to
  19924. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  19925. // no distinction between internal and leaf nodes.
  19926. var Node = (function () {
  19927. function Node(polygons) {
  19928. this.plane = null;
  19929. this.front = null;
  19930. this.back = null;
  19931. this.polygons = [];
  19932. if (polygons) {
  19933. this.build(polygons);
  19934. }
  19935. }
  19936. Node.prototype.clone = function () {
  19937. var node = new Node();
  19938. node.plane = this.plane && this.plane.clone();
  19939. node.front = this.front && this.front.clone();
  19940. node.back = this.back && this.back.clone();
  19941. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  19942. return node;
  19943. };
  19944. // Convert solid space to empty space and empty space to solid space.
  19945. Node.prototype.invert = function () {
  19946. for (var i = 0; i < this.polygons.length; i++) {
  19947. this.polygons[i].flip();
  19948. }
  19949. if (this.plane) {
  19950. this.plane.flip();
  19951. }
  19952. if (this.front) {
  19953. this.front.invert();
  19954. }
  19955. if (this.back) {
  19956. this.back.invert();
  19957. }
  19958. var temp = this.front;
  19959. this.front = this.back;
  19960. this.back = temp;
  19961. };
  19962. // Recursively remove all polygons in `polygons` that are inside this BSP
  19963. // tree.
  19964. Node.prototype.clipPolygons = function (polygons) {
  19965. if (!this.plane)
  19966. return polygons.slice();
  19967. var front = [], back = [];
  19968. for (var i = 0; i < polygons.length; i++) {
  19969. this.plane.splitPolygon(polygons[i], front, back, front, back);
  19970. }
  19971. if (this.front) {
  19972. front = this.front.clipPolygons(front);
  19973. }
  19974. if (this.back) {
  19975. back = this.back.clipPolygons(back);
  19976. }
  19977. else {
  19978. back = [];
  19979. }
  19980. return front.concat(back);
  19981. };
  19982. // Remove all polygons in this BSP tree that are inside the other BSP tree
  19983. // `bsp`.
  19984. Node.prototype.clipTo = function (bsp) {
  19985. this.polygons = bsp.clipPolygons(this.polygons);
  19986. if (this.front)
  19987. this.front.clipTo(bsp);
  19988. if (this.back)
  19989. this.back.clipTo(bsp);
  19990. };
  19991. // Return a list of all polygons in this BSP tree.
  19992. Node.prototype.allPolygons = function () {
  19993. var polygons = this.polygons.slice();
  19994. if (this.front)
  19995. polygons = polygons.concat(this.front.allPolygons());
  19996. if (this.back)
  19997. polygons = polygons.concat(this.back.allPolygons());
  19998. return polygons;
  19999. };
  20000. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  20001. // new polygons are filtered down to the bottom of the tree and become new
  20002. // nodes there. Each set of polygons is partitioned using the first polygon
  20003. // (no heuristic is used to pick a good split).
  20004. Node.prototype.build = function (polygons) {
  20005. if (!polygons.length)
  20006. return;
  20007. if (!this.plane)
  20008. this.plane = polygons[0].plane.clone();
  20009. var front = [], back = [];
  20010. for (var i = 0; i < polygons.length; i++) {
  20011. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  20012. }
  20013. if (front.length) {
  20014. if (!this.front)
  20015. this.front = new Node();
  20016. this.front.build(front);
  20017. }
  20018. if (back.length) {
  20019. if (!this.back)
  20020. this.back = new Node();
  20021. this.back.build(back);
  20022. }
  20023. };
  20024. return Node;
  20025. })();
  20026. var CSG = (function () {
  20027. function CSG() {
  20028. this.polygons = new Array();
  20029. }
  20030. // Convert BABYLON.Mesh to BABYLON.CSG
  20031. CSG.FromMesh = function (mesh) {
  20032. var vertex, normal, uv, position, polygon, polygons = [], vertices;
  20033. if (mesh instanceof BABYLON.Mesh) {
  20034. mesh.computeWorldMatrix(true);
  20035. var matrix = mesh.getWorldMatrix();
  20036. var meshPosition = mesh.position.clone();
  20037. var meshRotation = mesh.rotation.clone();
  20038. var meshScaling = mesh.scaling.clone();
  20039. }
  20040. else {
  20041. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  20042. }
  20043. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20044. var subMeshes = mesh.subMeshes;
  20045. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  20046. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  20047. vertices = [];
  20048. for (var j = 0; j < 3; j++) {
  20049. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  20050. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  20051. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  20052. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  20053. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  20054. vertex = new Vertex(position, normal, uv);
  20055. vertices.push(vertex);
  20056. }
  20057. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  20058. // To handle the case of degenerated triangle
  20059. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  20060. if (polygon.plane)
  20061. polygons.push(polygon);
  20062. }
  20063. }
  20064. var csg = CSG.FromPolygons(polygons);
  20065. csg.matrix = matrix;
  20066. csg.position = meshPosition;
  20067. csg.rotation = meshRotation;
  20068. csg.scaling = meshScaling;
  20069. currentCSGMeshId++;
  20070. return csg;
  20071. };
  20072. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  20073. CSG.FromPolygons = function (polygons) {
  20074. var csg = new BABYLON.CSG();
  20075. csg.polygons = polygons;
  20076. return csg;
  20077. };
  20078. CSG.prototype.clone = function () {
  20079. var csg = new BABYLON.CSG();
  20080. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  20081. csg.copyTransformAttributes(this);
  20082. return csg;
  20083. };
  20084. CSG.prototype.toPolygons = function () {
  20085. return this.polygons;
  20086. };
  20087. CSG.prototype.union = function (csg) {
  20088. var a = new Node(this.clone().polygons);
  20089. var b = new Node(csg.clone().polygons);
  20090. a.clipTo(b);
  20091. b.clipTo(a);
  20092. b.invert();
  20093. b.clipTo(a);
  20094. b.invert();
  20095. a.build(b.allPolygons());
  20096. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20097. };
  20098. CSG.prototype.unionInPlace = function (csg) {
  20099. var a = new Node(this.polygons);
  20100. var b = new Node(csg.polygons);
  20101. a.clipTo(b);
  20102. b.clipTo(a);
  20103. b.invert();
  20104. b.clipTo(a);
  20105. b.invert();
  20106. a.build(b.allPolygons());
  20107. this.polygons = a.allPolygons();
  20108. };
  20109. CSG.prototype.subtract = function (csg) {
  20110. var a = new Node(this.clone().polygons);
  20111. var b = new Node(csg.clone().polygons);
  20112. a.invert();
  20113. a.clipTo(b);
  20114. b.clipTo(a);
  20115. b.invert();
  20116. b.clipTo(a);
  20117. b.invert();
  20118. a.build(b.allPolygons());
  20119. a.invert();
  20120. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20121. };
  20122. CSG.prototype.subtractInPlace = function (csg) {
  20123. var a = new Node(this.polygons);
  20124. var b = new Node(csg.polygons);
  20125. a.invert();
  20126. a.clipTo(b);
  20127. b.clipTo(a);
  20128. b.invert();
  20129. b.clipTo(a);
  20130. b.invert();
  20131. a.build(b.allPolygons());
  20132. a.invert();
  20133. this.polygons = a.allPolygons();
  20134. };
  20135. CSG.prototype.intersect = function (csg) {
  20136. var a = new Node(this.clone().polygons);
  20137. var b = new Node(csg.clone().polygons);
  20138. a.invert();
  20139. b.clipTo(a);
  20140. b.invert();
  20141. a.clipTo(b);
  20142. b.clipTo(a);
  20143. a.build(b.allPolygons());
  20144. a.invert();
  20145. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  20146. };
  20147. CSG.prototype.intersectInPlace = function (csg) {
  20148. var a = new Node(this.polygons);
  20149. var b = new Node(csg.polygons);
  20150. a.invert();
  20151. b.clipTo(a);
  20152. b.invert();
  20153. a.clipTo(b);
  20154. b.clipTo(a);
  20155. a.build(b.allPolygons());
  20156. a.invert();
  20157. this.polygons = a.allPolygons();
  20158. };
  20159. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  20160. // not modified.
  20161. CSG.prototype.inverse = function () {
  20162. var csg = this.clone();
  20163. csg.inverseInPlace();
  20164. return csg;
  20165. };
  20166. CSG.prototype.inverseInPlace = function () {
  20167. this.polygons.map(function (p) {
  20168. p.flip();
  20169. });
  20170. };
  20171. // This is used to keep meshes transformations so they can be restored
  20172. // when we build back a Babylon Mesh
  20173. // NB : All CSG operations are performed in world coordinates
  20174. CSG.prototype.copyTransformAttributes = function (csg) {
  20175. this.matrix = csg.matrix;
  20176. this.position = csg.position;
  20177. this.rotation = csg.rotation;
  20178. this.scaling = csg.scaling;
  20179. return this;
  20180. };
  20181. // Build Raw mesh from CSG
  20182. // Coordinates here are in world space
  20183. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  20184. var matrix = this.matrix.clone();
  20185. matrix.invert();
  20186. 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;
  20187. if (keepSubMeshes) {
  20188. // Sort Polygons, since subMeshes are indices range
  20189. polygons.sort(function (a, b) {
  20190. if (a.shared.meshId === b.shared.meshId) {
  20191. return a.shared.subMeshId - b.shared.subMeshId;
  20192. }
  20193. else {
  20194. return a.shared.meshId - b.shared.meshId;
  20195. }
  20196. });
  20197. }
  20198. for (var i = 0, il = polygons.length; i < il; i++) {
  20199. polygon = polygons[i];
  20200. // Building SubMeshes
  20201. if (!subMesh_dict[polygon.shared.meshId]) {
  20202. subMesh_dict[polygon.shared.meshId] = {};
  20203. }
  20204. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  20205. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  20206. indexStart: +Infinity,
  20207. indexEnd: -Infinity,
  20208. materialIndex: polygon.shared.materialIndex
  20209. };
  20210. }
  20211. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  20212. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  20213. polygonIndices[0] = 0;
  20214. polygonIndices[1] = j - 1;
  20215. polygonIndices[2] = j;
  20216. for (var k = 0; k < 3; k++) {
  20217. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  20218. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  20219. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  20220. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  20221. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  20222. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  20223. // Check if 2 points can be merged
  20224. 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)) {
  20225. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  20226. uvs.push(uv.x, uv.y);
  20227. normals.push(normal.x, normal.y, normal.z);
  20228. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  20229. }
  20230. indices.push(vertex_idx);
  20231. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  20232. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  20233. currentIndex++;
  20234. }
  20235. }
  20236. }
  20237. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  20238. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20239. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  20240. mesh.setIndices(indices);
  20241. if (keepSubMeshes) {
  20242. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  20243. var materialIndexOffset = 0, materialMaxIndex;
  20244. mesh.subMeshes.length = 0;
  20245. for (var m in subMesh_dict) {
  20246. materialMaxIndex = -1;
  20247. for (var sm in subMesh_dict[m]) {
  20248. subMesh_obj = subMesh_dict[m][sm];
  20249. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  20250. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  20251. }
  20252. materialIndexOffset += ++materialMaxIndex;
  20253. }
  20254. }
  20255. return mesh;
  20256. };
  20257. // Build Mesh from CSG taking material and transforms into account
  20258. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  20259. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  20260. mesh.material = material;
  20261. mesh.position.copyFrom(this.position);
  20262. mesh.rotation.copyFrom(this.rotation);
  20263. mesh.scaling.copyFrom(this.scaling);
  20264. mesh.computeWorldMatrix(true);
  20265. return mesh;
  20266. };
  20267. return CSG;
  20268. })();
  20269. BABYLON.CSG = CSG;
  20270. })(BABYLON || (BABYLON = {}));
  20271. //# sourceMappingURL=babylon.csg.js.map
  20272. var BABYLON;
  20273. (function (BABYLON) {
  20274. var OculusDistortionCorrectionPostProcess = (function (_super) {
  20275. __extends(OculusDistortionCorrectionPostProcess, _super);
  20276. //ANY
  20277. function OculusDistortionCorrectionPostProcess(name, camera, isRightEye, cameraSettings) {
  20278. var _this = this;
  20279. _super.call(this, name, "oculusDistortionCorrection", [
  20280. 'LensCenter',
  20281. 'Scale',
  20282. 'ScaleIn',
  20283. 'HmdWarpParam'
  20284. ], null, cameraSettings.PostProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  20285. this._isRightEye = isRightEye;
  20286. this._distortionFactors = cameraSettings.DistortionK;
  20287. this._postProcessScaleFactor = cameraSettings.PostProcessScaleFactor;
  20288. this._lensCenterOffset = cameraSettings.LensCenterOffset;
  20289. this.onSizeChanged = function () {
  20290. _this.aspectRatio = _this.width * .5 / _this.height;
  20291. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  20292. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  20293. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  20294. };
  20295. this.onApply = function (effect) {
  20296. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  20297. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  20298. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  20299. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  20300. };
  20301. }
  20302. return OculusDistortionCorrectionPostProcess;
  20303. })(BABYLON.PostProcess);
  20304. BABYLON.OculusDistortionCorrectionPostProcess = OculusDistortionCorrectionPostProcess;
  20305. })(BABYLON || (BABYLON = {}));
  20306. //# sourceMappingURL=babylon.oculusDistortionCorrectionPostProcess.js.map// Mainly based on these 2 articles :
  20307. // 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
  20308. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  20309. var BABYLON;
  20310. (function (BABYLON) {
  20311. (function (JoystickAxis) {
  20312. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  20313. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  20314. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  20315. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  20316. var JoystickAxis = BABYLON.JoystickAxis;
  20317. var VirtualJoystick = (function () {
  20318. function VirtualJoystick(leftJoystick) {
  20319. var _this = this;
  20320. if (leftJoystick) {
  20321. this._leftJoystick = true;
  20322. }
  20323. else {
  20324. this._leftJoystick = false;
  20325. }
  20326. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  20327. VirtualJoystick._globalJoystickIndex++;
  20328. // By default left & right arrow keys are moving the X
  20329. // and up & down keys are moving the Y
  20330. this._axisTargetedByLeftAndRight = 0 /* X */;
  20331. this._axisTargetedByUpAndDown = 1 /* Y */;
  20332. this.reverseLeftRight = false;
  20333. this.reverseUpDown = false;
  20334. // collections of pointers
  20335. this._touches = new BABYLON.VirtualJoystick.Collection();
  20336. this.deltaPosition = BABYLON.Vector3.Zero();
  20337. this._joystickSensibility = 25;
  20338. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20339. this._rotationSpeed = 25;
  20340. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  20341. this._rotateOnAxisRelativeToMesh = false;
  20342. // injecting a canvas element on top of the canvas 3D game
  20343. if (!VirtualJoystick.vjCanvas) {
  20344. window.addEventListener("resize", function () {
  20345. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20346. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20347. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  20348. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  20349. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  20350. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  20351. }, false);
  20352. VirtualJoystick.vjCanvas = document.createElement("canvas");
  20353. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  20354. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  20355. VirtualJoystick.vjCanvas.width = window.innerWidth;
  20356. VirtualJoystick.vjCanvas.height = window.innerHeight;
  20357. VirtualJoystick.vjCanvas.style.width = "100%";
  20358. VirtualJoystick.vjCanvas.style.height = "100%";
  20359. VirtualJoystick.vjCanvas.style.position = "absolute";
  20360. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  20361. VirtualJoystick.vjCanvas.style.top = "0px";
  20362. VirtualJoystick.vjCanvas.style.left = "0px";
  20363. VirtualJoystick.vjCanvas.style.zIndex = "5";
  20364. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  20365. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  20366. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  20367. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20368. document.body.appendChild(VirtualJoystick.vjCanvas);
  20369. }
  20370. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  20371. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  20372. this.pressed = false;
  20373. // default joystick color
  20374. this._joystickColor = "cyan";
  20375. this._joystickPointerID = -1;
  20376. // current joystick position
  20377. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  20378. // origin joystick position
  20379. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  20380. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  20381. VirtualJoystick.vjCanvas.addEventListener('pointerdown', function (evt) {
  20382. _this._onPointerDown(evt);
  20383. }, false);
  20384. VirtualJoystick.vjCanvas.addEventListener('pointermove', function (evt) {
  20385. _this._onPointerMove(evt);
  20386. }, false);
  20387. VirtualJoystick.vjCanvas.addEventListener('pointerup', function (evt) {
  20388. _this._onPointerUp(evt);
  20389. }, false);
  20390. VirtualJoystick.vjCanvas.addEventListener('pointerout', function (evt) {
  20391. _this._onPointerUp(evt);
  20392. }, false);
  20393. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  20394. evt.preventDefault(); // Disables system menu
  20395. }, false);
  20396. requestAnimationFrame(function () {
  20397. _this._drawVirtualJoystick();
  20398. });
  20399. }
  20400. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  20401. this._joystickSensibility = newJoystickSensibility;
  20402. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  20403. };
  20404. VirtualJoystick.prototype._onPointerDown = function (e) {
  20405. var positionOnScreenCondition;
  20406. e.preventDefault();
  20407. if (this._leftJoystick === true) {
  20408. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  20409. }
  20410. else {
  20411. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  20412. }
  20413. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  20414. // First contact will be dedicated to the virtual joystick
  20415. this._joystickPointerID = e.pointerId;
  20416. this._joystickPointerStartPos.x = e.clientX;
  20417. this._joystickPointerStartPos.y = e.clientY;
  20418. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  20419. this._deltaJoystickVector.x = 0;
  20420. this._deltaJoystickVector.y = 0;
  20421. this.pressed = true;
  20422. this._touches.add(e.pointerId.toString(), e);
  20423. }
  20424. else {
  20425. // You can only trigger the action buttons with a joystick declared
  20426. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  20427. this._action();
  20428. this._touches.add(e.pointerId.toString(), e);
  20429. }
  20430. }
  20431. };
  20432. VirtualJoystick.prototype._onPointerMove = function (e) {
  20433. // If the current pointer is the one associated to the joystick (first touch contact)
  20434. if (this._joystickPointerID == e.pointerId) {
  20435. this._joystickPointerPos.x = e.clientX;
  20436. this._joystickPointerPos.y = e.clientY;
  20437. this._deltaJoystickVector = this._joystickPointerPos.clone();
  20438. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  20439. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  20440. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  20441. switch (this._axisTargetedByLeftAndRight) {
  20442. case 0 /* X */:
  20443. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  20444. break;
  20445. case 1 /* Y */:
  20446. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  20447. break;
  20448. case 2 /* Z */:
  20449. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  20450. break;
  20451. }
  20452. var directionUpDown = this.reverseUpDown ? 1 : -1;
  20453. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  20454. switch (this._axisTargetedByUpAndDown) {
  20455. case 0 /* X */:
  20456. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  20457. break;
  20458. case 1 /* Y */:
  20459. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  20460. break;
  20461. case 2 /* Z */:
  20462. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  20463. break;
  20464. }
  20465. }
  20466. else {
  20467. if (this._touches.item(e.pointerId.toString())) {
  20468. this._touches.item(e.pointerId.toString()).x = e.clientX;
  20469. this._touches.item(e.pointerId.toString()).y = e.clientY;
  20470. }
  20471. }
  20472. };
  20473. VirtualJoystick.prototype._onPointerUp = function (e) {
  20474. this._clearCanvas();
  20475. if (this._joystickPointerID == e.pointerId) {
  20476. this._joystickPointerID = -1;
  20477. this.pressed = false;
  20478. }
  20479. this._deltaJoystickVector.x = 0;
  20480. this._deltaJoystickVector.y = 0;
  20481. this._touches.remove(e.pointerId.toString());
  20482. };
  20483. /**
  20484. * Change the color of the virtual joystick
  20485. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  20486. */
  20487. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  20488. this._joystickColor = newColor;
  20489. };
  20490. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  20491. this._action = action;
  20492. };
  20493. // Define which axis you'd like to control for left & right
  20494. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  20495. switch (axis) {
  20496. case 0 /* X */:
  20497. case 1 /* Y */:
  20498. case 2 /* Z */:
  20499. this._axisTargetedByLeftAndRight = axis;
  20500. break;
  20501. default:
  20502. this._axisTargetedByLeftAndRight = 0 /* X */;
  20503. break;
  20504. }
  20505. };
  20506. // Define which axis you'd like to control for up & down
  20507. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  20508. switch (axis) {
  20509. case 0 /* X */:
  20510. case 1 /* Y */:
  20511. case 2 /* Z */:
  20512. this._axisTargetedByUpAndDown = axis;
  20513. break;
  20514. default:
  20515. this._axisTargetedByUpAndDown = 1 /* Y */;
  20516. break;
  20517. }
  20518. };
  20519. VirtualJoystick.prototype._clearCanvas = function () {
  20520. if (this._leftJoystick) {
  20521. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  20522. }
  20523. else {
  20524. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  20525. }
  20526. };
  20527. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  20528. var _this = this;
  20529. if (this.pressed) {
  20530. this._clearCanvas();
  20531. this._touches.forEach(function (touch) {
  20532. if (touch.pointerId === _this._joystickPointerID) {
  20533. VirtualJoystick.vjCanvasContext.beginPath();
  20534. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20535. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20536. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  20537. VirtualJoystick.vjCanvasContext.stroke();
  20538. VirtualJoystick.vjCanvasContext.beginPath();
  20539. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20540. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  20541. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  20542. VirtualJoystick.vjCanvasContext.stroke();
  20543. VirtualJoystick.vjCanvasContext.beginPath();
  20544. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  20545. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  20546. VirtualJoystick.vjCanvasContext.stroke();
  20547. }
  20548. else {
  20549. VirtualJoystick.vjCanvasContext.beginPath();
  20550. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  20551. VirtualJoystick.vjCanvasContext.beginPath();
  20552. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  20553. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  20554. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  20555. VirtualJoystick.vjCanvasContext.stroke();
  20556. }
  20557. ;
  20558. });
  20559. }
  20560. requestAnimationFrame(function () {
  20561. _this._drawVirtualJoystick();
  20562. });
  20563. };
  20564. VirtualJoystick.prototype.releaseCanvas = function () {
  20565. if (VirtualJoystick.vjCanvas) {
  20566. document.body.removeChild(VirtualJoystick.vjCanvas);
  20567. VirtualJoystick.vjCanvas = null;
  20568. }
  20569. };
  20570. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  20571. VirtualJoystick._globalJoystickIndex = 0;
  20572. return VirtualJoystick;
  20573. })();
  20574. BABYLON.VirtualJoystick = VirtualJoystick;
  20575. })(BABYLON || (BABYLON = {}));
  20576. var BABYLON;
  20577. (function (BABYLON) {
  20578. var VirtualJoystick;
  20579. (function (VirtualJoystick) {
  20580. var Collection = (function () {
  20581. function Collection() {
  20582. this._count = 0;
  20583. this._collection = new Array();
  20584. }
  20585. Collection.prototype.Count = function () {
  20586. return this._count;
  20587. };
  20588. Collection.prototype.add = function (key, item) {
  20589. if (this._collection[key] != undefined) {
  20590. return undefined;
  20591. }
  20592. this._collection[key] = item;
  20593. return ++this._count;
  20594. };
  20595. Collection.prototype.remove = function (key) {
  20596. if (this._collection[key] == undefined) {
  20597. return undefined;
  20598. }
  20599. delete this._collection[key];
  20600. return --this._count;
  20601. };
  20602. Collection.prototype.item = function (key) {
  20603. return this._collection[key];
  20604. };
  20605. Collection.prototype.forEach = function (block) {
  20606. var key;
  20607. for (key in this._collection) {
  20608. if (this._collection.hasOwnProperty(key)) {
  20609. block(this._collection[key]);
  20610. }
  20611. }
  20612. };
  20613. return Collection;
  20614. })();
  20615. VirtualJoystick.Collection = Collection;
  20616. })(VirtualJoystick = BABYLON.VirtualJoystick || (BABYLON.VirtualJoystick = {}));
  20617. })(BABYLON || (BABYLON = {}));
  20618. //# sourceMappingURL=babylon.virtualJoystick.js.map
  20619. var BABYLON;
  20620. (function (BABYLON) {
  20621. var OculusRiftDevKit2013_Metric = {
  20622. HResolution: 1280,
  20623. VResolution: 800,
  20624. HScreenSize: 0.149759993,
  20625. VScreenSize: 0.0935999975,
  20626. VScreenCenter: 0.0467999987,
  20627. EyeToScreenDistance: 0.0410000011,
  20628. LensSeparationDistance: 0.0635000020,
  20629. InterpupillaryDistance: 0.0640000030,
  20630. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20631. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20632. PostProcessScaleFactor: 1.714605507808412,
  20633. LensCenterOffset: 0.151976421
  20634. };
  20635. var _OculusInnerCamera = (function (_super) {
  20636. __extends(_OculusInnerCamera, _super);
  20637. function _OculusInnerCamera(name, position, scene, isLeftEye) {
  20638. _super.call(this, name, position, scene);
  20639. this._workMatrix = new BABYLON.Matrix();
  20640. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20641. // Constants
  20642. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20643. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20644. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20645. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20646. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20647. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20648. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20649. // Postprocess
  20650. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20651. }
  20652. _OculusInnerCamera.prototype.getProjectionMatrix = function () {
  20653. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20654. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20655. return this._projectionMatrix;
  20656. };
  20657. _OculusInnerCamera.prototype._getViewMatrix = function () {
  20658. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20659. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20660. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20661. // Computing target and final matrix
  20662. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20663. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20664. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20665. return this._viewMatrix;
  20666. };
  20667. return _OculusInnerCamera;
  20668. })(BABYLON.FreeCamera);
  20669. var OculusCamera = (function (_super) {
  20670. __extends(OculusCamera, _super);
  20671. function OculusCamera(name, position, scene) {
  20672. _super.call(this, name, position, scene);
  20673. this._leftCamera = new _OculusInnerCamera(name + "_left", position.clone(), scene, true);
  20674. this._rightCamera = new _OculusInnerCamera(name + "_right", position.clone(), scene, false);
  20675. this.subCameras.push(this._leftCamera);
  20676. this.subCameras.push(this._rightCamera);
  20677. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20678. }
  20679. OculusCamera.prototype._update = function () {
  20680. this._leftCamera.position.copyFrom(this.position);
  20681. this._rightCamera.position.copyFrom(this.position);
  20682. this._updateCamera(this._leftCamera);
  20683. this._updateCamera(this._rightCamera);
  20684. _super.prototype._update.call(this);
  20685. };
  20686. OculusCamera.prototype._updateCamera = function (camera) {
  20687. camera.minZ = this.minZ;
  20688. camera.maxZ = this.maxZ;
  20689. camera.rotation.x = this.rotation.x;
  20690. camera.rotation.y = this.rotation.y;
  20691. camera.rotation.z = this.rotation.z;
  20692. };
  20693. // Oculus events
  20694. OculusCamera.prototype._onOrientationEvent = function (evt) {
  20695. var yaw = evt.alpha / 180 * Math.PI;
  20696. var pitch = evt.beta / 180 * Math.PI;
  20697. var roll = evt.gamma / 180 * Math.PI;
  20698. if (!this._offsetOrientation) {
  20699. this._offsetOrientation = {
  20700. yaw: yaw,
  20701. pitch: pitch,
  20702. roll: roll
  20703. };
  20704. return;
  20705. }
  20706. else {
  20707. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20708. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20709. this.rotation.z += this._offsetOrientation.roll - roll;
  20710. this._offsetOrientation.yaw = yaw;
  20711. this._offsetOrientation.pitch = pitch;
  20712. this._offsetOrientation.roll = roll;
  20713. }
  20714. };
  20715. OculusCamera.prototype.attachControl = function (element, noPreventDefault) {
  20716. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20717. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20718. };
  20719. OculusCamera.prototype.detachControl = function (element) {
  20720. _super.prototype.detachControl.call(this, element);
  20721. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20722. };
  20723. return OculusCamera;
  20724. })(BABYLON.FreeCamera);
  20725. BABYLON.OculusCamera = OculusCamera;
  20726. })(BABYLON || (BABYLON = {}));
  20727. //# sourceMappingURL=babylon.oculusCamera.js.map
  20728. var BABYLON;
  20729. (function (BABYLON) {
  20730. var OculusRiftDevKit2013_Metric = {
  20731. HResolution: 1280,
  20732. VResolution: 800,
  20733. HScreenSize: 0.149759993,
  20734. VScreenSize: 0.0935999975,
  20735. VScreenCenter: 0.0467999987,
  20736. EyeToScreenDistance: 0.0410000011,
  20737. LensSeparationDistance: 0.0635000020,
  20738. InterpupillaryDistance: 0.0640000030,
  20739. DistortionK: [1.0, 0.219999999, 0.239999995, 0.0],
  20740. ChromaAbCorrection: [0.995999992, -0.00400000019, 1.01400006, 0.0],
  20741. PostProcessScaleFactor: 1.714605507808412,
  20742. LensCenterOffset: 0.151976421
  20743. };
  20744. var _OculusInnerGamepadCamera = (function (_super) {
  20745. __extends(_OculusInnerGamepadCamera, _super);
  20746. function _OculusInnerGamepadCamera(name, position, scene, isLeftEye) {
  20747. _super.call(this, name, position, scene);
  20748. this._workMatrix = new BABYLON.Matrix();
  20749. this._actualUp = new BABYLON.Vector3(0, 0, 0);
  20750. // Constants
  20751. this._aspectRatioAspectRatio = OculusRiftDevKit2013_Metric.HResolution / (2 * OculusRiftDevKit2013_Metric.VResolution);
  20752. this._aspectRatioFov = (2 * Math.atan((OculusRiftDevKit2013_Metric.PostProcessScaleFactor * OculusRiftDevKit2013_Metric.VScreenSize) / (2 * OculusRiftDevKit2013_Metric.EyeToScreenDistance)));
  20753. var hMeters = (OculusRiftDevKit2013_Metric.HScreenSize / 4) - (OculusRiftDevKit2013_Metric.LensSeparationDistance / 2);
  20754. var h = (4 * hMeters) / OculusRiftDevKit2013_Metric.HScreenSize;
  20755. this._hMatrix = BABYLON.Matrix.Translation(isLeftEye ? h : -h, 0, 0);
  20756. this.viewport = new BABYLON.Viewport(isLeftEye ? 0 : 0.5, 0, 0.5, 1.0);
  20757. this._preViewMatrix = BABYLON.Matrix.Translation(isLeftEye ? .5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance : -.5 * OculusRiftDevKit2013_Metric.InterpupillaryDistance, 0, 0);
  20758. // Postprocess
  20759. var postProcess = new BABYLON.OculusDistortionCorrectionPostProcess("Oculus Distortion", this, !isLeftEye, OculusRiftDevKit2013_Metric);
  20760. }
  20761. _OculusInnerGamepadCamera.prototype.getProjectionMatrix = function () {
  20762. BABYLON.Matrix.PerspectiveFovLHToRef(this._aspectRatioFov, this._aspectRatioAspectRatio, this.minZ, this.maxZ, this._workMatrix);
  20763. this._workMatrix.multiplyToRef(this._hMatrix, this._projectionMatrix);
  20764. return this._projectionMatrix;
  20765. };
  20766. _OculusInnerGamepadCamera.prototype._getViewMatrix = function () {
  20767. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  20768. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  20769. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._actualUp);
  20770. // Computing target and final matrix
  20771. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  20772. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._actualUp, this._workMatrix);
  20773. this._workMatrix.multiplyToRef(this._preViewMatrix, this._viewMatrix);
  20774. return this._viewMatrix;
  20775. };
  20776. return _OculusInnerGamepadCamera;
  20777. })(BABYLON.FreeCamera);
  20778. var OculusGamepadCamera = (function (_super) {
  20779. __extends(OculusGamepadCamera, _super);
  20780. function OculusGamepadCamera(name, position, scene) {
  20781. var _this = this;
  20782. _super.call(this, name, position, scene);
  20783. this.angularSensibility = 200;
  20784. this.moveSensibility = 75;
  20785. this._leftCamera = new _OculusInnerGamepadCamera(name + "_left", position.clone(), scene, true);
  20786. this._rightCamera = new _OculusInnerGamepadCamera(name + "_right", position.clone(), scene, false);
  20787. this.subCameras.push(this._leftCamera);
  20788. this.subCameras.push(this._rightCamera);
  20789. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  20790. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  20791. _this._onNewGameConnected(gamepad);
  20792. });
  20793. }
  20794. OculusGamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  20795. // Only the first gamepad can control the camera
  20796. if (gamepad.index === 0) {
  20797. this._gamepad = gamepad;
  20798. }
  20799. };
  20800. OculusGamepadCamera.prototype._update = function () {
  20801. this._leftCamera.position.copyFrom(this.position);
  20802. this._rightCamera.position.copyFrom(this.position);
  20803. this._updateCamera(this._leftCamera);
  20804. this._updateCamera(this._rightCamera);
  20805. _super.prototype._update.call(this);
  20806. };
  20807. OculusGamepadCamera.prototype._checkInputs = function () {
  20808. if (!this._gamepad) {
  20809. return;
  20810. }
  20811. var LSValues = this._gamepad.leftStick;
  20812. var normalizedLX = LSValues.x / this.moveSensibility;
  20813. var normalizedLY = LSValues.y / this.moveSensibility;
  20814. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  20815. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  20816. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20817. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x, 0, -LSValues.y), cameraTransform);
  20818. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20819. };
  20820. OculusGamepadCamera.prototype._updateCamera = function (camera) {
  20821. camera.minZ = this.minZ;
  20822. camera.maxZ = this.maxZ;
  20823. camera.rotation.x = this.rotation.x;
  20824. camera.rotation.y = this.rotation.y;
  20825. camera.rotation.z = this.rotation.z;
  20826. };
  20827. // Oculus events
  20828. OculusGamepadCamera.prototype._onOrientationEvent = function (evt) {
  20829. var yaw = evt.alpha / 180 * Math.PI;
  20830. var pitch = evt.beta / 180 * Math.PI;
  20831. var roll = evt.gamma / 180 * Math.PI;
  20832. if (!this._offsetOrientation) {
  20833. this._offsetOrientation = {
  20834. yaw: yaw,
  20835. pitch: pitch,
  20836. roll: roll
  20837. };
  20838. return;
  20839. }
  20840. else {
  20841. this.rotation.y += yaw - this._offsetOrientation.yaw;
  20842. this.rotation.x += pitch - this._offsetOrientation.pitch;
  20843. this.rotation.z += this._offsetOrientation.roll - roll;
  20844. this._offsetOrientation.yaw = yaw;
  20845. this._offsetOrientation.pitch = pitch;
  20846. this._offsetOrientation.roll = roll;
  20847. }
  20848. };
  20849. OculusGamepadCamera.prototype.attachControl = function (element, noPreventDefault) {
  20850. _super.prototype.attachControl.call(this, element, noPreventDefault);
  20851. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  20852. };
  20853. OculusGamepadCamera.prototype.detachControl = function (element) {
  20854. _super.prototype.detachControl.call(this, element);
  20855. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  20856. };
  20857. OculusGamepadCamera.prototype.dispose = function () {
  20858. this._gamepads.dispose();
  20859. _super.prototype.dispose.call(this);
  20860. };
  20861. return OculusGamepadCamera;
  20862. })(BABYLON.FreeCamera);
  20863. BABYLON.OculusGamepadCamera = OculusGamepadCamera;
  20864. })(BABYLON || (BABYLON = {}));
  20865. //# sourceMappingURL=babylon.oculusGamepadCamera.js.map
  20866. var BABYLON;
  20867. (function (BABYLON) {
  20868. // We're mainly based on the logic defined into the FreeCamera code
  20869. var VirtualJoysticksCamera = (function (_super) {
  20870. __extends(VirtualJoysticksCamera, _super);
  20871. function VirtualJoysticksCamera(name, position, scene) {
  20872. _super.call(this, name, position, scene);
  20873. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  20874. this._leftjoystick.setAxisForUpDown(2 /* Z */);
  20875. this._leftjoystick.setAxisForLeftRight(0 /* X */);
  20876. this._leftjoystick.setJoystickSensibility(0.15);
  20877. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  20878. this._rightjoystick.setAxisForUpDown(0 /* X */);
  20879. this._rightjoystick.setAxisForLeftRight(1 /* Y */);
  20880. this._rightjoystick.reverseUpDown = true;
  20881. this._rightjoystick.setJoystickSensibility(0.05);
  20882. this._rightjoystick.setJoystickColor("yellow");
  20883. }
  20884. VirtualJoysticksCamera.prototype._checkInputs = function () {
  20885. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  20886. var deltaTransform = BABYLON.Vector3.TransformCoordinates(this._leftjoystick.deltaPosition, cameraTransform);
  20887. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  20888. this.cameraRotation = this.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  20889. if (!this._leftjoystick.pressed) {
  20890. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  20891. }
  20892. if (!this._rightjoystick.pressed) {
  20893. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  20894. }
  20895. };
  20896. VirtualJoysticksCamera.prototype.dispose = function () {
  20897. this._leftjoystick.releaseCanvas();
  20898. _super.prototype.dispose.call(this);
  20899. };
  20900. return VirtualJoysticksCamera;
  20901. })(BABYLON.FreeCamera);
  20902. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  20903. })(BABYLON || (BABYLON = {}));
  20904. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  20905. var BABYLON;
  20906. (function (BABYLON) {
  20907. var ShaderMaterial = (function (_super) {
  20908. __extends(ShaderMaterial, _super);
  20909. function ShaderMaterial(name, scene, shaderPath, options) {
  20910. _super.call(this, name, scene);
  20911. this._textures = new Array();
  20912. this._floats = new Array();
  20913. this._floatsArrays = {};
  20914. this._colors3 = new Array();
  20915. this._colors4 = new Array();
  20916. this._vectors2 = new Array();
  20917. this._vectors3 = new Array();
  20918. this._matrices = new Array();
  20919. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  20920. this._shaderPath = shaderPath;
  20921. options.needAlphaBlending = options.needAlphaBlending || false;
  20922. options.needAlphaTesting = options.needAlphaTesting || false;
  20923. options.attributes = options.attributes || ["position", "normal", "uv"];
  20924. options.uniforms = options.uniforms || ["worldViewProjection"];
  20925. options.samplers = options.samplers || [];
  20926. this._options = options;
  20927. }
  20928. ShaderMaterial.prototype.needAlphaBlending = function () {
  20929. return this._options.needAlphaBlending;
  20930. };
  20931. ShaderMaterial.prototype.needAlphaTesting = function () {
  20932. return this._options.needAlphaTesting;
  20933. };
  20934. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  20935. if (this._options.uniforms.indexOf(uniformName) === -1) {
  20936. this._options.uniforms.push(uniformName);
  20937. }
  20938. };
  20939. ShaderMaterial.prototype.setTexture = function (name, texture) {
  20940. if (this._options.samplers.indexOf(name) === -1) {
  20941. this._options.samplers.push(name);
  20942. }
  20943. this._textures[name] = texture;
  20944. return this;
  20945. };
  20946. ShaderMaterial.prototype.setFloat = function (name, value) {
  20947. this._checkUniform(name);
  20948. this._floats[name] = value;
  20949. return this;
  20950. };
  20951. ShaderMaterial.prototype.setFloats = function (name, value) {
  20952. this._checkUniform(name);
  20953. this._floatsArrays[name] = value;
  20954. return this;
  20955. };
  20956. ShaderMaterial.prototype.setColor3 = function (name, value) {
  20957. this._checkUniform(name);
  20958. this._colors3[name] = value;
  20959. return this;
  20960. };
  20961. ShaderMaterial.prototype.setColor4 = function (name, value) {
  20962. this._checkUniform(name);
  20963. this._colors4[name] = value;
  20964. return this;
  20965. };
  20966. ShaderMaterial.prototype.setVector2 = function (name, value) {
  20967. this._checkUniform(name);
  20968. this._vectors2[name] = value;
  20969. return this;
  20970. };
  20971. ShaderMaterial.prototype.setVector3 = function (name, value) {
  20972. this._checkUniform(name);
  20973. this._vectors3[name] = value;
  20974. return this;
  20975. };
  20976. ShaderMaterial.prototype.setMatrix = function (name, value) {
  20977. this._checkUniform(name);
  20978. this._matrices[name] = value;
  20979. return this;
  20980. };
  20981. ShaderMaterial.prototype.isReady = function () {
  20982. var scene = this.getScene();
  20983. var engine = scene.getEngine();
  20984. if (!this.checkReadyOnEveryCall) {
  20985. if (this._renderId === scene.getRenderId()) {
  20986. return true;
  20987. }
  20988. }
  20989. var previousEffect = this._effect;
  20990. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, "", null, this.onCompiled, this.onError);
  20991. if (!this._effect.isReady()) {
  20992. return false;
  20993. }
  20994. if (previousEffect !== this._effect) {
  20995. scene.resetCachedMaterial();
  20996. }
  20997. this._renderId = scene.getRenderId();
  20998. return true;
  20999. };
  21000. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  21001. var scene = this.getScene();
  21002. if (this._options.uniforms.indexOf("world") !== -1) {
  21003. this._effect.setMatrix("world", world);
  21004. }
  21005. if (this._options.uniforms.indexOf("worldView") !== -1) {
  21006. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  21007. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  21008. }
  21009. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  21010. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  21011. }
  21012. };
  21013. ShaderMaterial.prototype.bind = function (world) {
  21014. // Std values
  21015. this.bindOnlyWorldMatrix(world);
  21016. if (this.getScene().getCachedMaterial() !== this) {
  21017. if (this._options.uniforms.indexOf("view") !== -1) {
  21018. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  21019. }
  21020. if (this._options.uniforms.indexOf("projection") !== -1) {
  21021. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  21022. }
  21023. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  21024. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  21025. }
  21026. for (var name in this._textures) {
  21027. this._effect.setTexture(name, this._textures[name]);
  21028. }
  21029. for (name in this._floats) {
  21030. this._effect.setFloat(name, this._floats[name]);
  21031. }
  21032. for (name in this._floatsArrays) {
  21033. this._effect.setArray(name, this._floatsArrays[name]);
  21034. }
  21035. for (name in this._colors3) {
  21036. this._effect.setColor3(name, this._colors3[name]);
  21037. }
  21038. for (name in this._colors4) {
  21039. var color = this._colors4[name];
  21040. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  21041. }
  21042. for (name in this._vectors2) {
  21043. this._effect.setVector2(name, this._vectors2[name]);
  21044. }
  21045. for (name in this._vectors3) {
  21046. this._effect.setVector3(name, this._vectors3[name]);
  21047. }
  21048. for (name in this._matrices) {
  21049. this._effect.setMatrix(name, this._matrices[name]);
  21050. }
  21051. }
  21052. _super.prototype.bind.call(this, world, null);
  21053. };
  21054. ShaderMaterial.prototype.dispose = function (forceDisposeEffect) {
  21055. for (var name in this._textures) {
  21056. this._textures[name].dispose();
  21057. }
  21058. this._textures = [];
  21059. _super.prototype.dispose.call(this, forceDisposeEffect);
  21060. };
  21061. return ShaderMaterial;
  21062. })(BABYLON.Material);
  21063. BABYLON.ShaderMaterial = ShaderMaterial;
  21064. })(BABYLON || (BABYLON = {}));
  21065. //# sourceMappingURL=babylon.shaderMaterial.js.mapvar BABYLON;
  21066. (function (BABYLON) {
  21067. var VertexData = (function () {
  21068. function VertexData() {
  21069. }
  21070. VertexData.prototype.set = function (data, kind) {
  21071. switch (kind) {
  21072. case BABYLON.VertexBuffer.PositionKind:
  21073. this.positions = data;
  21074. break;
  21075. case BABYLON.VertexBuffer.NormalKind:
  21076. this.normals = data;
  21077. break;
  21078. case BABYLON.VertexBuffer.UVKind:
  21079. this.uvs = data;
  21080. break;
  21081. case BABYLON.VertexBuffer.UV2Kind:
  21082. this.uv2s = data;
  21083. break;
  21084. case BABYLON.VertexBuffer.ColorKind:
  21085. this.colors = data;
  21086. break;
  21087. case BABYLON.VertexBuffer.MatricesIndicesKind:
  21088. this.matricesIndices = data;
  21089. break;
  21090. case BABYLON.VertexBuffer.MatricesWeightsKind:
  21091. this.matricesWeights = data;
  21092. break;
  21093. }
  21094. };
  21095. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  21096. this._applyTo(mesh, updatable);
  21097. };
  21098. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  21099. this._applyTo(geometry, updatable);
  21100. };
  21101. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  21102. this._update(mesh);
  21103. };
  21104. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  21105. this._update(geometry);
  21106. };
  21107. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  21108. if (this.positions) {
  21109. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  21110. }
  21111. if (this.normals) {
  21112. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  21113. }
  21114. if (this.uvs) {
  21115. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  21116. }
  21117. if (this.uv2s) {
  21118. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updatable);
  21119. }
  21120. if (this.colors) {
  21121. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  21122. }
  21123. if (this.matricesIndices) {
  21124. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  21125. }
  21126. if (this.matricesWeights) {
  21127. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  21128. }
  21129. if (this.indices) {
  21130. meshOrGeometry.setIndices(this.indices);
  21131. }
  21132. };
  21133. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  21134. if (this.positions) {
  21135. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  21136. }
  21137. if (this.normals) {
  21138. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  21139. }
  21140. if (this.uvs) {
  21141. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  21142. }
  21143. if (this.uv2s) {
  21144. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uv2s, updateExtends, makeItUnique);
  21145. }
  21146. if (this.colors) {
  21147. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  21148. }
  21149. if (this.matricesIndices) {
  21150. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  21151. }
  21152. if (this.matricesWeights) {
  21153. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  21154. }
  21155. if (this.indices) {
  21156. meshOrGeometry.setIndices(this.indices);
  21157. }
  21158. };
  21159. VertexData.prototype.transform = function (matrix) {
  21160. var transformed = BABYLON.Vector3.Zero();
  21161. if (this.positions) {
  21162. var position = BABYLON.Vector3.Zero();
  21163. for (var index = 0; index < this.positions.length; index += 3) {
  21164. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  21165. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  21166. this.positions[index] = transformed.x;
  21167. this.positions[index + 1] = transformed.y;
  21168. this.positions[index + 2] = transformed.z;
  21169. }
  21170. }
  21171. if (this.normals) {
  21172. var normal = BABYLON.Vector3.Zero();
  21173. for (index = 0; index < this.normals.length; index += 3) {
  21174. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  21175. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  21176. this.normals[index] = transformed.x;
  21177. this.normals[index + 1] = transformed.y;
  21178. this.normals[index + 2] = transformed.z;
  21179. }
  21180. }
  21181. };
  21182. VertexData.prototype.merge = function (other) {
  21183. if (other.indices) {
  21184. if (!this.indices) {
  21185. this.indices = [];
  21186. }
  21187. var offset = this.positions ? this.positions.length / 3 : 0;
  21188. for (var index = 0; index < other.indices.length; index++) {
  21189. this.indices.push(other.indices[index] + offset);
  21190. }
  21191. }
  21192. if (other.positions) {
  21193. if (!this.positions) {
  21194. this.positions = [];
  21195. }
  21196. for (index = 0; index < other.positions.length; index++) {
  21197. this.positions.push(other.positions[index]);
  21198. }
  21199. }
  21200. if (other.normals) {
  21201. if (!this.normals) {
  21202. this.normals = [];
  21203. }
  21204. for (index = 0; index < other.normals.length; index++) {
  21205. this.normals.push(other.normals[index]);
  21206. }
  21207. }
  21208. if (other.uvs) {
  21209. if (!this.uvs) {
  21210. this.uvs = [];
  21211. }
  21212. for (index = 0; index < other.uvs.length; index++) {
  21213. this.uvs.push(other.uvs[index]);
  21214. }
  21215. }
  21216. if (other.uv2s) {
  21217. if (!this.uv2s) {
  21218. this.uv2s = [];
  21219. }
  21220. for (index = 0; index < other.uv2s.length; index++) {
  21221. this.uv2s.push(other.uv2s[index]);
  21222. }
  21223. }
  21224. if (other.matricesIndices) {
  21225. if (!this.matricesIndices) {
  21226. this.matricesIndices = [];
  21227. }
  21228. for (index = 0; index < other.matricesIndices.length; index++) {
  21229. this.matricesIndices.push(other.matricesIndices[index]);
  21230. }
  21231. }
  21232. if (other.matricesWeights) {
  21233. if (!this.matricesWeights) {
  21234. this.matricesWeights = [];
  21235. }
  21236. for (index = 0; index < other.matricesWeights.length; index++) {
  21237. this.matricesWeights.push(other.matricesWeights[index]);
  21238. }
  21239. }
  21240. if (other.colors) {
  21241. if (!this.colors) {
  21242. this.colors = [];
  21243. }
  21244. for (index = 0; index < other.colors.length; index++) {
  21245. this.colors.push(other.colors[index]);
  21246. }
  21247. }
  21248. };
  21249. // Statics
  21250. VertexData.ExtractFromMesh = function (mesh) {
  21251. return VertexData._ExtractFrom(mesh);
  21252. };
  21253. VertexData.ExtractFromGeometry = function (geometry) {
  21254. return VertexData._ExtractFrom(geometry);
  21255. };
  21256. VertexData._ExtractFrom = function (meshOrGeometry) {
  21257. var result = new VertexData();
  21258. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21259. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21260. }
  21261. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21262. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21263. }
  21264. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21265. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21266. }
  21267. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  21268. result.uv2s = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  21269. }
  21270. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  21271. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  21272. }
  21273. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21274. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21275. }
  21276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21277. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21278. }
  21279. result.indices = meshOrGeometry.getIndices();
  21280. return result;
  21281. };
  21282. VertexData.CreateRibbon = function (pathArray, closeArray, closePath, offset, sideOrientation) {
  21283. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21284. closeArray = closeArray || false;
  21285. closePath = closePath || false;
  21286. var defaultOffset = Math.floor(pathArray[0].length / 2);
  21287. offset = offset || defaultOffset;
  21288. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  21289. var positions = [];
  21290. var indices = [];
  21291. var normals = [];
  21292. var uvs = [];
  21293. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  21294. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  21295. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  21296. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  21297. var minlg; // minimal length among all paths from pathArray
  21298. var lg = []; // array of path lengths : nb of vertex per path
  21299. var idx = []; // array of path indexes : index of each path (first vertex) in positions array
  21300. var p; // path iterator
  21301. var i; // point iterator
  21302. var j; // point iterator
  21303. // if single path in pathArray
  21304. if (pathArray.length < 2) {
  21305. var ar1 = [];
  21306. var ar2 = [];
  21307. for (i = 0; i < pathArray[0].length - offset; i++) {
  21308. ar1.push(pathArray[0][i]);
  21309. ar2.push(pathArray[0][i + offset]);
  21310. }
  21311. pathArray = [ar1, ar2];
  21312. }
  21313. // positions and horizontal distances (u)
  21314. var idc = 0;
  21315. minlg = pathArray[0].length;
  21316. for (p = 0; p < pathArray.length; p++) {
  21317. uTotalDistance[p] = 0;
  21318. us[p] = [0];
  21319. var path = pathArray[p];
  21320. var l = path.length;
  21321. minlg = (minlg < l) ? minlg : l;
  21322. lg[p] = l;
  21323. idx[p] = idc;
  21324. j = 0;
  21325. while (j < l) {
  21326. positions.push(path[j].x, path[j].y, path[j].z);
  21327. if (j > 0) {
  21328. var vectlg = path[j].subtract(path[j - 1]).length();
  21329. var dist = vectlg + uTotalDistance[p];
  21330. us[p].push(dist);
  21331. uTotalDistance[p] = dist;
  21332. }
  21333. j++;
  21334. }
  21335. if (closePath) {
  21336. vectlg = path[0].subtract(path[j - 1]).length();
  21337. dist = vectlg + uTotalDistance[p];
  21338. uTotalDistance[p] = dist;
  21339. }
  21340. idc += l;
  21341. }
  21342. for (i = 0; i < minlg; i++) {
  21343. vTotalDistance[i] = 0;
  21344. vs[i] = [0];
  21345. var path1;
  21346. var path2;
  21347. for (p = 0; p < pathArray.length - 1; p++) {
  21348. path1 = pathArray[p];
  21349. path2 = pathArray[p + 1];
  21350. vectlg = path2[i].subtract(path1[i]).length();
  21351. dist = vectlg + vTotalDistance[i];
  21352. vs[i].push(dist);
  21353. vTotalDistance[i] = dist;
  21354. }
  21355. if (closeArray) {
  21356. path1 = pathArray[p];
  21357. path2 = pathArray[0];
  21358. vectlg = path2[i].subtract(path1[i]).length();
  21359. dist = vectlg + vTotalDistance[i];
  21360. vTotalDistance[i] = dist;
  21361. }
  21362. }
  21363. // uvs
  21364. var u;
  21365. var v;
  21366. for (p = 0; p < pathArray.length; p++) {
  21367. for (i = 0; i < minlg; i++) {
  21368. u = us[p][i] / uTotalDistance[p];
  21369. v = vs[i][p] / vTotalDistance[i];
  21370. uvs.push(u, v);
  21371. }
  21372. }
  21373. // indices
  21374. p = 0; // path index
  21375. var pi = 0; // positions array index
  21376. var l1 = lg[p] - 1; // path1 length
  21377. var l2 = lg[p + 1] - 1; // path2 length
  21378. var min = (l1 < l2) ? l1 : l2; // current path stop index
  21379. var shft = idx[1] - idx[0]; // shift
  21380. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate
  21381. var t1; // two consecutive triangles, so 4 points : point1
  21382. var t2; // point2
  21383. var t3; // point3
  21384. var t4; // point4
  21385. while (pi <= min && p < path1nb) {
  21386. // 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
  21387. t1 = pi;
  21388. t2 = pi + shft;
  21389. t3 = pi + 1;
  21390. t4 = pi + shft + 1;
  21391. indices.push(pi, pi + shft, pi + 1);
  21392. indices.push(pi + shft + 1, pi + 1, pi + shft);
  21393. pi += 1;
  21394. if (pi === min) {
  21395. if (closePath) {
  21396. indices.push(pi, pi + shft, idx[p]);
  21397. indices.push(idx[p] + shft, idx[p], pi + shft);
  21398. t3 = idx[p];
  21399. t4 = idx[p] + shft;
  21400. }
  21401. p++;
  21402. if (p === lg.length - 1) {
  21403. shft = idx[0] - idx[p];
  21404. l1 = lg[p] - 1;
  21405. l2 = lg[0] - 1;
  21406. }
  21407. else {
  21408. shft = idx[p + 1] - idx[p];
  21409. l1 = lg[p] - 1;
  21410. l2 = lg[p + 1] - 1;
  21411. }
  21412. pi = idx[p];
  21413. min = (l1 < l2) ? l1 + pi : l2 + pi;
  21414. }
  21415. }
  21416. // normals
  21417. VertexData.ComputeNormals(positions, indices, normals);
  21418. // sides
  21419. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21420. // Result
  21421. var vertexData = new VertexData();
  21422. vertexData.indices = indices;
  21423. vertexData.positions = positions;
  21424. vertexData.normals = normals;
  21425. vertexData.uvs = uvs;
  21426. return vertexData;
  21427. };
  21428. VertexData.CreateBox = function (size, sideOrientation) {
  21429. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21430. var normalsSource = [
  21431. new BABYLON.Vector3(0, 0, 1),
  21432. new BABYLON.Vector3(0, 0, -1),
  21433. new BABYLON.Vector3(1, 0, 0),
  21434. new BABYLON.Vector3(-1, 0, 0),
  21435. new BABYLON.Vector3(0, 1, 0),
  21436. new BABYLON.Vector3(0, -1, 0)
  21437. ];
  21438. var indices = [];
  21439. var positions = [];
  21440. var normals = [];
  21441. var uvs = [];
  21442. size = size || 1;
  21443. for (var index = 0; index < normalsSource.length; index++) {
  21444. var normal = normalsSource[index];
  21445. // Get two vectors perpendicular to the face normal and to each other.
  21446. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  21447. var side2 = BABYLON.Vector3.Cross(normal, side1);
  21448. // Six indices (two triangles) per face.
  21449. var verticesLength = positions.length / 3;
  21450. indices.push(verticesLength);
  21451. indices.push(verticesLength + 1);
  21452. indices.push(verticesLength + 2);
  21453. indices.push(verticesLength);
  21454. indices.push(verticesLength + 2);
  21455. indices.push(verticesLength + 3);
  21456. // Four vertices per face.
  21457. var vertex = normal.subtract(side1).subtract(side2).scale(size / 2);
  21458. positions.push(vertex.x, vertex.y, vertex.z);
  21459. normals.push(normal.x, normal.y, normal.z);
  21460. uvs.push(1.0, 1.0);
  21461. vertex = normal.subtract(side1).add(side2).scale(size / 2);
  21462. positions.push(vertex.x, vertex.y, vertex.z);
  21463. normals.push(normal.x, normal.y, normal.z);
  21464. uvs.push(0.0, 1.0);
  21465. vertex = normal.add(side1).add(side2).scale(size / 2);
  21466. positions.push(vertex.x, vertex.y, vertex.z);
  21467. normals.push(normal.x, normal.y, normal.z);
  21468. uvs.push(0.0, 0.0);
  21469. vertex = normal.add(side1).subtract(side2).scale(size / 2);
  21470. positions.push(vertex.x, vertex.y, vertex.z);
  21471. normals.push(normal.x, normal.y, normal.z);
  21472. uvs.push(1.0, 0.0);
  21473. }
  21474. // sides
  21475. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21476. // Result
  21477. var vertexData = new VertexData();
  21478. vertexData.indices = indices;
  21479. vertexData.positions = positions;
  21480. vertexData.normals = normals;
  21481. vertexData.uvs = uvs;
  21482. return vertexData;
  21483. };
  21484. VertexData.CreateSphere = function (segments, diameter, sideOrientation) {
  21485. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21486. segments = segments || 32;
  21487. diameter = diameter || 1;
  21488. var radius = diameter / 2;
  21489. var totalZRotationSteps = 2 + segments;
  21490. var totalYRotationSteps = 2 * totalZRotationSteps;
  21491. var indices = [];
  21492. var positions = [];
  21493. var normals = [];
  21494. var uvs = [];
  21495. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  21496. var normalizedZ = zRotationStep / totalZRotationSteps;
  21497. var angleZ = (normalizedZ * Math.PI);
  21498. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  21499. var normalizedY = yRotationStep / totalYRotationSteps;
  21500. var angleY = normalizedY * Math.PI * 2;
  21501. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  21502. var rotationY = BABYLON.Matrix.RotationY(angleY);
  21503. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  21504. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  21505. var vertex = complete.scale(radius);
  21506. var normal = BABYLON.Vector3.Normalize(vertex);
  21507. positions.push(vertex.x, vertex.y, vertex.z);
  21508. normals.push(normal.x, normal.y, normal.z);
  21509. uvs.push(normalizedZ, normalizedY);
  21510. }
  21511. if (zRotationStep > 0) {
  21512. var verticesCount = positions.length / 3;
  21513. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  21514. indices.push((firstIndex));
  21515. indices.push((firstIndex + 1));
  21516. indices.push(firstIndex + totalYRotationSteps + 1);
  21517. indices.push((firstIndex + totalYRotationSteps + 1));
  21518. indices.push((firstIndex + 1));
  21519. indices.push((firstIndex + totalYRotationSteps + 2));
  21520. }
  21521. }
  21522. }
  21523. // Sides
  21524. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21525. // Result
  21526. var vertexData = new VertexData();
  21527. vertexData.indices = indices;
  21528. vertexData.positions = positions;
  21529. vertexData.normals = normals;
  21530. vertexData.uvs = uvs;
  21531. return vertexData;
  21532. };
  21533. VertexData.CreateCylinder = function (height, diameterTop, diameterBottom, tessellation, subdivisions, sideOrientation) {
  21534. if (subdivisions === void 0) { subdivisions = 1; }
  21535. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21536. var radiusTop = diameterTop / 2;
  21537. var radiusBottom = diameterBottom / 2;
  21538. var indices = [];
  21539. var positions = [];
  21540. var normals = [];
  21541. var uvs = [];
  21542. height = height || 1;
  21543. diameterTop = diameterTop || 0.5;
  21544. diameterBottom = diameterBottom || 1;
  21545. tessellation = tessellation || 16;
  21546. subdivisions = subdivisions || 1;
  21547. subdivisions = (subdivisions < 1) ? 1 : subdivisions;
  21548. var getCircleVector = function (i) {
  21549. var angle = (i * 2.0 * Math.PI / tessellation);
  21550. var dx = Math.cos(angle);
  21551. var dz = Math.sin(angle);
  21552. return new BABYLON.Vector3(dx, 0, dz);
  21553. };
  21554. var createCylinderCap = function (isTop) {
  21555. var radius = isTop ? radiusTop : radiusBottom;
  21556. if (radius === 0) {
  21557. return;
  21558. }
  21559. var vbase = positions.length / 3;
  21560. var offset = new BABYLON.Vector3(0, height / 2, 0);
  21561. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  21562. if (!isTop) {
  21563. offset.scaleInPlace(-1);
  21564. textureScale.x = -textureScale.x;
  21565. }
  21566. for (var i = 0; i < tessellation; i++) {
  21567. var circleVector = getCircleVector(i);
  21568. var position = circleVector.scale(radius).add(offset);
  21569. var textureCoordinate = new BABYLON.Vector2(circleVector.x * textureScale.x + 0.5, circleVector.z * textureScale.y + 0.5);
  21570. positions.push(position.x, position.y, position.z);
  21571. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21572. }
  21573. for (i = 0; i < tessellation - 2; i++) {
  21574. if (!isTop) {
  21575. indices.push(vbase);
  21576. indices.push(vbase + (i + 2) % tessellation);
  21577. indices.push(vbase + (i + 1) % tessellation);
  21578. }
  21579. else {
  21580. indices.push(vbase);
  21581. indices.push(vbase + (i + 1) % tessellation);
  21582. indices.push(vbase + (i + 2) % tessellation);
  21583. }
  21584. }
  21585. };
  21586. var base = new BABYLON.Vector3(0, -1, 0).scale(height / 2);
  21587. var offset = new BABYLON.Vector3(0, 1, 0).scale(height / subdivisions);
  21588. var stride = tessellation + 1;
  21589. for (var i = 0; i <= tessellation; i++) {
  21590. var circleVector = getCircleVector(i);
  21591. var textureCoordinate = new BABYLON.Vector2(i / tessellation, 0);
  21592. var position, radius = radiusBottom;
  21593. for (var s = 0; s <= subdivisions; s++) {
  21594. // Update variables
  21595. position = circleVector.scale(radius);
  21596. position.addInPlace(base.add(offset.scale(s)));
  21597. textureCoordinate.y += 1 / subdivisions;
  21598. radius += (radiusTop - radiusBottom) / subdivisions;
  21599. // Push in arrays
  21600. positions.push(position.x, position.y, position.z);
  21601. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21602. }
  21603. }
  21604. subdivisions += 1;
  21605. for (s = 0; s < subdivisions - 1; s++) {
  21606. for (i = 0; i <= tessellation; i++) {
  21607. indices.push(i * subdivisions + s);
  21608. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21609. indices.push(i * subdivisions + (s + 1));
  21610. indices.push(i * subdivisions + (s + 1));
  21611. indices.push((i * subdivisions + (s + subdivisions)) % (stride * subdivisions));
  21612. indices.push((i * subdivisions + (s + subdivisions + 1)) % (stride * subdivisions));
  21613. }
  21614. }
  21615. // Create flat triangle fan caps to seal the top and bottom.
  21616. createCylinderCap(true);
  21617. createCylinderCap(false);
  21618. // Normals
  21619. VertexData.ComputeNormals(positions, indices, normals);
  21620. // Sides
  21621. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21622. // Result
  21623. var vertexData = new VertexData();
  21624. vertexData.indices = indices;
  21625. vertexData.positions = positions;
  21626. vertexData.normals = normals;
  21627. vertexData.uvs = uvs;
  21628. return vertexData;
  21629. };
  21630. VertexData.CreateTorus = function (diameter, thickness, tessellation, sideOrientation) {
  21631. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21632. var indices = [];
  21633. var positions = [];
  21634. var normals = [];
  21635. var uvs = [];
  21636. diameter = diameter || 1;
  21637. thickness = thickness || 0.5;
  21638. tessellation = tessellation || 16;
  21639. var stride = tessellation + 1;
  21640. for (var i = 0; i <= tessellation; i++) {
  21641. var u = i / tessellation;
  21642. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  21643. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  21644. for (var j = 0; j <= tessellation; j++) {
  21645. var v = 1 - j / tessellation;
  21646. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  21647. var dx = Math.cos(innerAngle);
  21648. var dy = Math.sin(innerAngle);
  21649. // Create a vertex.
  21650. var normal = new BABYLON.Vector3(dx, dy, 0);
  21651. var position = normal.scale(thickness / 2);
  21652. var textureCoordinate = new BABYLON.Vector2(u, v);
  21653. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  21654. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  21655. positions.push(position.x, position.y, position.z);
  21656. normals.push(normal.x, normal.y, normal.z);
  21657. uvs.push(textureCoordinate.x, textureCoordinate.y);
  21658. // And create indices for two triangles.
  21659. var nextI = (i + 1) % stride;
  21660. var nextJ = (j + 1) % stride;
  21661. indices.push(i * stride + j);
  21662. indices.push(i * stride + nextJ);
  21663. indices.push(nextI * stride + j);
  21664. indices.push(i * stride + nextJ);
  21665. indices.push(nextI * stride + nextJ);
  21666. indices.push(nextI * stride + j);
  21667. }
  21668. }
  21669. // Sides
  21670. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21671. // Result
  21672. var vertexData = new VertexData();
  21673. vertexData.indices = indices;
  21674. vertexData.positions = positions;
  21675. vertexData.normals = normals;
  21676. vertexData.uvs = uvs;
  21677. return vertexData;
  21678. };
  21679. VertexData.CreateLines = function (points) {
  21680. var indices = [];
  21681. var positions = [];
  21682. for (var index = 0; index < points.length; index++) {
  21683. positions.push(points[index].x, points[index].y, points[index].z);
  21684. if (index > 0) {
  21685. indices.push(index - 1);
  21686. indices.push(index);
  21687. }
  21688. }
  21689. // Result
  21690. var vertexData = new VertexData();
  21691. vertexData.indices = indices;
  21692. vertexData.positions = positions;
  21693. return vertexData;
  21694. };
  21695. VertexData.CreateGround = function (width, height, subdivisions) {
  21696. var indices = [];
  21697. var positions = [];
  21698. var normals = [];
  21699. var uvs = [];
  21700. var row, col;
  21701. width = width || 1;
  21702. height = height || 1;
  21703. subdivisions = subdivisions || 1;
  21704. for (row = 0; row <= subdivisions; row++) {
  21705. for (col = 0; col <= subdivisions; col++) {
  21706. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21707. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21708. positions.push(position.x, position.y, position.z);
  21709. normals.push(normal.x, normal.y, normal.z);
  21710. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21711. }
  21712. }
  21713. for (row = 0; row < subdivisions; row++) {
  21714. for (col = 0; col < subdivisions; col++) {
  21715. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21716. indices.push(col + 1 + row * (subdivisions + 1));
  21717. indices.push(col + row * (subdivisions + 1));
  21718. indices.push(col + (row + 1) * (subdivisions + 1));
  21719. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21720. indices.push(col + row * (subdivisions + 1));
  21721. }
  21722. }
  21723. // Result
  21724. var vertexData = new VertexData();
  21725. vertexData.indices = indices;
  21726. vertexData.positions = positions;
  21727. vertexData.normals = normals;
  21728. vertexData.uvs = uvs;
  21729. return vertexData;
  21730. };
  21731. VertexData.CreateTiledGround = function (xmin, zmin, xmax, zmax, subdivisions, precision) {
  21732. if (subdivisions === void 0) { subdivisions = { w: 1, h: 1 }; }
  21733. if (precision === void 0) { precision = { w: 1, h: 1 }; }
  21734. var indices = [];
  21735. var positions = [];
  21736. var normals = [];
  21737. var uvs = [];
  21738. var row, col, tileRow, tileCol;
  21739. subdivisions.h = (subdivisions.w < 1) ? 1 : subdivisions.h;
  21740. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  21741. precision.w = (precision.w < 1) ? 1 : precision.w;
  21742. precision.h = (precision.h < 1) ? 1 : precision.h;
  21743. var tileSize = {
  21744. 'w': (xmax - xmin) / subdivisions.w,
  21745. 'h': (zmax - zmin) / subdivisions.h
  21746. };
  21747. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  21748. // Indices
  21749. var base = positions.length / 3;
  21750. var rowLength = precision.w + 1;
  21751. for (row = 0; row < precision.h; row++) {
  21752. for (col = 0; col < precision.w; col++) {
  21753. var square = [
  21754. base + col + row * rowLength,
  21755. base + (col + 1) + row * rowLength,
  21756. base + (col + 1) + (row + 1) * rowLength,
  21757. base + col + (row + 1) * rowLength
  21758. ];
  21759. indices.push(square[1]);
  21760. indices.push(square[2]);
  21761. indices.push(square[3]);
  21762. indices.push(square[0]);
  21763. indices.push(square[1]);
  21764. indices.push(square[3]);
  21765. }
  21766. }
  21767. // Position, normals and uvs
  21768. var position = BABYLON.Vector3.Zero();
  21769. var normal = new BABYLON.Vector3(0, 1.0, 0);
  21770. for (row = 0; row <= precision.h; row++) {
  21771. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  21772. for (col = 0; col <= precision.w; col++) {
  21773. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  21774. position.y = 0;
  21775. positions.push(position.x, position.y, position.z);
  21776. normals.push(normal.x, normal.y, normal.z);
  21777. uvs.push(col / precision.w, row / precision.h);
  21778. }
  21779. }
  21780. }
  21781. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  21782. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  21783. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  21784. }
  21785. }
  21786. // Result
  21787. var vertexData = new VertexData();
  21788. vertexData.indices = indices;
  21789. vertexData.positions = positions;
  21790. vertexData.normals = normals;
  21791. vertexData.uvs = uvs;
  21792. return vertexData;
  21793. };
  21794. VertexData.CreateGroundFromHeightMap = function (width, height, subdivisions, minHeight, maxHeight, buffer, bufferWidth, bufferHeight) {
  21795. var indices = [];
  21796. var positions = [];
  21797. var normals = [];
  21798. var uvs = [];
  21799. var row, col;
  21800. for (row = 0; row <= subdivisions; row++) {
  21801. for (col = 0; col <= subdivisions; col++) {
  21802. var position = new BABYLON.Vector3((col * width) / subdivisions - (width / 2.0), 0, ((subdivisions - row) * height) / subdivisions - (height / 2.0));
  21803. // Compute height
  21804. var heightMapX = (((position.x + width / 2) / width) * (bufferWidth - 1)) | 0;
  21805. var heightMapY = ((1.0 - (position.z + height / 2) / height) * (bufferHeight - 1)) | 0;
  21806. var pos = (heightMapX + heightMapY * bufferWidth) * 4;
  21807. var r = buffer[pos] / 255.0;
  21808. var g = buffer[pos + 1] / 255.0;
  21809. var b = buffer[pos + 2] / 255.0;
  21810. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21811. position.y = minHeight + (maxHeight - minHeight) * gradient;
  21812. // Add vertex
  21813. positions.push(position.x, position.y, position.z);
  21814. normals.push(0, 0, 0);
  21815. uvs.push(col / subdivisions, 1.0 - row / subdivisions);
  21816. }
  21817. }
  21818. for (row = 0; row < subdivisions; row++) {
  21819. for (col = 0; col < subdivisions; col++) {
  21820. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21821. indices.push(col + 1 + row * (subdivisions + 1));
  21822. indices.push(col + row * (subdivisions + 1));
  21823. indices.push(col + (row + 1) * (subdivisions + 1));
  21824. indices.push(col + 1 + (row + 1) * (subdivisions + 1));
  21825. indices.push(col + row * (subdivisions + 1));
  21826. }
  21827. }
  21828. // Normals
  21829. VertexData.ComputeNormals(positions, indices, normals);
  21830. // Result
  21831. var vertexData = new VertexData();
  21832. vertexData.indices = indices;
  21833. vertexData.positions = positions;
  21834. vertexData.normals = normals;
  21835. vertexData.uvs = uvs;
  21836. return vertexData;
  21837. };
  21838. VertexData.CreatePlane = function (size, sideOrientation) {
  21839. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21840. var indices = [];
  21841. var positions = [];
  21842. var normals = [];
  21843. var uvs = [];
  21844. size = size || 1;
  21845. // Vertices
  21846. var halfSize = size / 2.0;
  21847. positions.push(-halfSize, -halfSize, 0);
  21848. normals.push(0, 0, -1.0);
  21849. uvs.push(0.0, 0.0);
  21850. positions.push(halfSize, -halfSize, 0);
  21851. normals.push(0, 0, -1.0);
  21852. uvs.push(1.0, 0.0);
  21853. positions.push(halfSize, halfSize, 0);
  21854. normals.push(0, 0, -1.0);
  21855. uvs.push(1.0, 1.0);
  21856. positions.push(-halfSize, halfSize, 0);
  21857. normals.push(0, 0, -1.0);
  21858. uvs.push(0.0, 1.0);
  21859. // Indices
  21860. indices.push(0);
  21861. indices.push(1);
  21862. indices.push(2);
  21863. indices.push(0);
  21864. indices.push(2);
  21865. indices.push(3);
  21866. // Sides
  21867. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  21868. // Result
  21869. var vertexData = new VertexData();
  21870. vertexData.indices = indices;
  21871. vertexData.positions = positions;
  21872. vertexData.normals = normals;
  21873. vertexData.uvs = uvs;
  21874. return vertexData;
  21875. };
  21876. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  21877. VertexData.CreateTorusKnot = function (radius, tube, radialSegments, tubularSegments, p, q, sideOrientation) {
  21878. if (sideOrientation === void 0) { sideOrientation = BABYLON.Mesh.DEFAULTSIDE; }
  21879. var indices = [];
  21880. var positions = [];
  21881. var normals = [];
  21882. var uvs = [];
  21883. radius = radius || 2;
  21884. tube = tube || 0.5;
  21885. radialSegments = radialSegments || 32;
  21886. tubularSegments = tubularSegments || 32;
  21887. p = p || 2;
  21888. q = q || 3;
  21889. // Helper
  21890. var getPos = function (angle) {
  21891. var cu = Math.cos(angle);
  21892. var su = Math.sin(angle);
  21893. var quOverP = q / p * angle;
  21894. var cs = Math.cos(quOverP);
  21895. var tx = radius * (2 + cs) * 0.5 * cu;
  21896. var ty = radius * (2 + cs) * su * 0.5;
  21897. var tz = radius * Math.sin(quOverP) * 0.5;
  21898. return new BABYLON.Vector3(tx, ty, tz);
  21899. };
  21900. for (var i = 0; i <= radialSegments; i++) {
  21901. var modI = i % radialSegments;
  21902. var u = modI / radialSegments * 2 * p * Math.PI;
  21903. var p1 = getPos(u);
  21904. var p2 = getPos(u + 0.01);
  21905. var tang = p2.subtract(p1);
  21906. var n = p2.add(p1);
  21907. var bitan = BABYLON.Vector3.Cross(tang, n);
  21908. n = BABYLON.Vector3.Cross(bitan, tang);
  21909. bitan.normalize();
  21910. n.normalize();
  21911. for (var j = 0; j < tubularSegments; j++) {
  21912. var modJ = j % tubularSegments;
  21913. var v = modJ / tubularSegments * 2 * Math.PI;
  21914. var cx = -tube * Math.cos(v);
  21915. var cy = tube * Math.sin(v);
  21916. positions.push(p1.x + cx * n.x + cy * bitan.x);
  21917. positions.push(p1.y + cx * n.y + cy * bitan.y);
  21918. positions.push(p1.z + cx * n.z + cy * bitan.z);
  21919. uvs.push(i / radialSegments);
  21920. uvs.push(j / tubularSegments);
  21921. }
  21922. }
  21923. for (i = 0; i < radialSegments; i++) {
  21924. for (j = 0; j < tubularSegments; j++) {
  21925. var jNext = (j + 1) % tubularSegments;
  21926. var a = i * tubularSegments + j;
  21927. var b = (i + 1) * tubularSegments + j;
  21928. var c = (i + 1) * tubularSegments + jNext;
  21929. var d = i * tubularSegments + jNext;
  21930. indices.push(d);
  21931. indices.push(b);
  21932. indices.push(a);
  21933. indices.push(d);
  21934. indices.push(c);
  21935. indices.push(b);
  21936. }
  21937. }
  21938. // Normals
  21939. VertexData.ComputeNormals(positions, indices, normals);
  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. // Tools
  21951. VertexData.ComputeNormals = function (positions, indices, normals) {
  21952. var positionVectors = [];
  21953. var facesOfVertices = [];
  21954. var index;
  21955. for (index = 0; index < positions.length; index += 3) {
  21956. var vector3 = new BABYLON.Vector3(positions[index], positions[index + 1], positions[index + 2]);
  21957. positionVectors.push(vector3);
  21958. facesOfVertices.push([]);
  21959. }
  21960. // Compute normals
  21961. var facesNormals = [];
  21962. for (index = 0; index < indices.length / 3; index++) {
  21963. var i1 = indices[index * 3];
  21964. var i2 = indices[index * 3 + 1];
  21965. var i3 = indices[index * 3 + 2];
  21966. var p1 = positionVectors[i1];
  21967. var p2 = positionVectors[i2];
  21968. var p3 = positionVectors[i3];
  21969. var p1p2 = p1.subtract(p2);
  21970. var p3p2 = p3.subtract(p2);
  21971. facesNormals[index] = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21972. facesOfVertices[i1].push(index);
  21973. facesOfVertices[i2].push(index);
  21974. facesOfVertices[i3].push(index);
  21975. }
  21976. for (index = 0; index < positionVectors.length; index++) {
  21977. var faces = facesOfVertices[index];
  21978. var normal = BABYLON.Vector3.Zero();
  21979. for (var faceIndex = 0; faceIndex < faces.length; faceIndex++) {
  21980. normal.addInPlace(facesNormals[faces[faceIndex]]);
  21981. }
  21982. normal = BABYLON.Vector3.Normalize(normal.scale(1.0 / faces.length));
  21983. normals[index * 3] = normal.x;
  21984. normals[index * 3 + 1] = normal.y;
  21985. normals[index * 3 + 2] = normal.z;
  21986. }
  21987. };
  21988. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  21989. var li = indices.length;
  21990. var ln = normals.length;
  21991. var i;
  21992. var n;
  21993. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  21994. switch (sideOrientation) {
  21995. case BABYLON.Mesh.FRONTSIDE:
  21996. break;
  21997. case BABYLON.Mesh.BACKSIDE:
  21998. var tmp;
  21999. for (i = 0; i < li; i += 3) {
  22000. tmp = indices[i];
  22001. indices[i] = indices[i + 2];
  22002. indices[i + 2] = tmp;
  22003. }
  22004. for (n = 0; n < ln; n++) {
  22005. normals[n] = -normals[n];
  22006. }
  22007. break;
  22008. case BABYLON.Mesh.DOUBLESIDE:
  22009. // positions
  22010. var lp = positions.length;
  22011. var l = lp / 3;
  22012. for (var p = 0; p < lp; p++) {
  22013. positions[lp + p] = positions[p];
  22014. }
  22015. for (i = 0; i < li; i += 3) {
  22016. indices[i + li] = indices[i + 2] + l;
  22017. indices[i + 1 + li] = indices[i + 1] + l;
  22018. indices[i + 2 + li] = indices[i] + l;
  22019. }
  22020. for (n = 0; n < ln; n++) {
  22021. normals[ln + n] = -normals[n];
  22022. }
  22023. // uvs
  22024. var lu = uvs.length;
  22025. for (var u = 0; u < lu; u++) {
  22026. uvs[u + lu] = uvs[u];
  22027. }
  22028. break;
  22029. }
  22030. };
  22031. return VertexData;
  22032. })();
  22033. BABYLON.VertexData = VertexData;
  22034. })(BABYLON || (BABYLON = {}));
  22035. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  22036. var BABYLON;
  22037. (function (BABYLON) {
  22038. var buildCamera = function (that, name) {
  22039. that._leftCamera.isIntermediate = true;
  22040. that.subCameras.push(that._leftCamera);
  22041. that.subCameras.push(that._rightCamera);
  22042. that._leftTexture = new BABYLON.PassPostProcess(name + "_leftTexture", 1.0, that._leftCamera);
  22043. that._anaglyphPostProcess = new BABYLON.AnaglyphPostProcess(name + "_anaglyph", 1.0, that._rightCamera);
  22044. that._anaglyphPostProcess.onApply = function (effect) {
  22045. effect.setTextureFromPostProcess("leftSampler", that._leftTexture);
  22046. };
  22047. that._update();
  22048. };
  22049. var AnaglyphArcRotateCamera = (function (_super) {
  22050. __extends(AnaglyphArcRotateCamera, _super);
  22051. // ANY
  22052. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, eyeSpace, scene) {
  22053. _super.call(this, name, alpha, beta, radius, target, scene);
  22054. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22055. this._leftCamera = new BABYLON.ArcRotateCamera(name + "_left", alpha - this._eyeSpace, beta, radius, target, scene);
  22056. this._rightCamera = new BABYLON.ArcRotateCamera(name + "_right", alpha + this._eyeSpace, beta, radius, target, scene);
  22057. buildCamera(this, name);
  22058. }
  22059. AnaglyphArcRotateCamera.prototype._update = function () {
  22060. this._updateCamera(this._leftCamera);
  22061. this._updateCamera(this._rightCamera);
  22062. this._leftCamera.alpha = this.alpha - this._eyeSpace;
  22063. this._rightCamera.alpha = this.alpha + this._eyeSpace;
  22064. _super.prototype._update.call(this);
  22065. };
  22066. AnaglyphArcRotateCamera.prototype._updateCamera = function (camera) {
  22067. camera.beta = this.beta;
  22068. camera.radius = this.radius;
  22069. camera.minZ = this.minZ;
  22070. camera.maxZ = this.maxZ;
  22071. camera.fov = this.fov;
  22072. camera.target = this.target;
  22073. };
  22074. return AnaglyphArcRotateCamera;
  22075. })(BABYLON.ArcRotateCamera);
  22076. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  22077. var AnaglyphFreeCamera = (function (_super) {
  22078. __extends(AnaglyphFreeCamera, _super);
  22079. function AnaglyphFreeCamera(name, position, eyeSpace, scene) {
  22080. _super.call(this, name, position, scene);
  22081. this._eyeSpace = BABYLON.Tools.ToRadians(eyeSpace);
  22082. this._transformMatrix = new BABYLON.Matrix();
  22083. this._leftCamera = new BABYLON.FreeCamera(name + "_left", position.clone(), scene);
  22084. this._rightCamera = new BABYLON.FreeCamera(name + "_right", position.clone(), scene);
  22085. buildCamera(this, name);
  22086. }
  22087. AnaglyphFreeCamera.prototype._getSubCameraPosition = function (eyeSpace, result) {
  22088. var target = this.getTarget();
  22089. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(eyeSpace), this._transformMatrix);
  22090. this._transformMatrix = this._transformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  22091. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._transformMatrix, result);
  22092. };
  22093. AnaglyphFreeCamera.prototype._update = function () {
  22094. this._getSubCameraPosition(-this._eyeSpace, this._leftCamera.position);
  22095. this._getSubCameraPosition(this._eyeSpace, this._rightCamera.position);
  22096. this._updateCamera(this._leftCamera);
  22097. this._updateCamera(this._rightCamera);
  22098. _super.prototype._update.call(this);
  22099. };
  22100. AnaglyphFreeCamera.prototype._updateCamera = function (camera) {
  22101. camera.minZ = this.minZ;
  22102. camera.maxZ = this.maxZ;
  22103. camera.fov = this.fov;
  22104. camera.viewport = this.viewport;
  22105. camera.setTarget(this.getTarget());
  22106. };
  22107. return AnaglyphFreeCamera;
  22108. })(BABYLON.FreeCamera);
  22109. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  22110. })(BABYLON || (BABYLON = {}));
  22111. //# sourceMappingURL=babylon.anaglyphCamera.js.map
  22112. var BABYLON;
  22113. (function (BABYLON) {
  22114. var AnaglyphPostProcess = (function (_super) {
  22115. __extends(AnaglyphPostProcess, _super);
  22116. function AnaglyphPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22117. _super.call(this, name, "anaglyph", null, ["leftSampler"], ratio, camera, samplingMode, engine, reusable);
  22118. }
  22119. return AnaglyphPostProcess;
  22120. })(BABYLON.PostProcess);
  22121. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  22122. })(BABYLON || (BABYLON = {}));
  22123. //# sourceMappingURL=babylon.anaglyphPostProcess.js.mapvar BABYLON;
  22124. (function (BABYLON) {
  22125. var Tags = (function () {
  22126. function Tags() {
  22127. }
  22128. Tags.EnableFor = function (obj) {
  22129. obj._tags = obj._tags || {};
  22130. obj.hasTags = function () {
  22131. return Tags.HasTags(obj);
  22132. };
  22133. obj.addTags = function (tagsString) {
  22134. return Tags.AddTagsTo(obj, tagsString);
  22135. };
  22136. obj.removeTags = function (tagsString) {
  22137. return Tags.RemoveTagsFrom(obj, tagsString);
  22138. };
  22139. obj.matchesTagsQuery = function (tagsQuery) {
  22140. return Tags.MatchesQuery(obj, tagsQuery);
  22141. };
  22142. };
  22143. Tags.DisableFor = function (obj) {
  22144. delete obj._tags;
  22145. delete obj.hasTags;
  22146. delete obj.addTags;
  22147. delete obj.removeTags;
  22148. delete obj.matchesTagsQuery;
  22149. };
  22150. Tags.HasTags = function (obj) {
  22151. if (!obj._tags) {
  22152. return false;
  22153. }
  22154. return !BABYLON.Tools.IsEmpty(obj._tags);
  22155. };
  22156. Tags.GetTags = function (obj) {
  22157. if (!obj._tags) {
  22158. return null;
  22159. }
  22160. return obj._tags;
  22161. };
  22162. // the tags 'true' and 'false' are reserved and cannot be used as tags
  22163. // a tag cannot start with '||', '&&', and '!'
  22164. // it cannot contain whitespaces
  22165. Tags.AddTagsTo = function (obj, tagsString) {
  22166. if (!tagsString) {
  22167. return;
  22168. }
  22169. var tags = tagsString.split(" ");
  22170. for (var t in tags) {
  22171. Tags._AddTagTo(obj, tags[t]);
  22172. }
  22173. };
  22174. Tags._AddTagTo = function (obj, tag) {
  22175. tag = tag.trim();
  22176. if (tag === "" || tag === "true" || tag === "false") {
  22177. return;
  22178. }
  22179. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  22180. return;
  22181. }
  22182. Tags.EnableFor(obj);
  22183. obj._tags[tag] = true;
  22184. };
  22185. Tags.RemoveTagsFrom = function (obj, tagsString) {
  22186. if (!Tags.HasTags(obj)) {
  22187. return;
  22188. }
  22189. var tags = tagsString.split(" ");
  22190. for (var t in tags) {
  22191. Tags._RemoveTagFrom(obj, tags[t]);
  22192. }
  22193. };
  22194. Tags._RemoveTagFrom = function (obj, tag) {
  22195. delete obj._tags[tag];
  22196. };
  22197. Tags.MatchesQuery = function (obj, tagsQuery) {
  22198. if (tagsQuery === undefined) {
  22199. return true;
  22200. }
  22201. if (tagsQuery === "") {
  22202. return Tags.HasTags(obj);
  22203. }
  22204. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  22205. };
  22206. return Tags;
  22207. })();
  22208. BABYLON.Tags = Tags;
  22209. })(BABYLON || (BABYLON = {}));
  22210. //# sourceMappingURL=babylon.tags.js.mapvar BABYLON;
  22211. (function (BABYLON) {
  22212. var Internals;
  22213. (function (Internals) {
  22214. var AndOrNotEvaluator = (function () {
  22215. function AndOrNotEvaluator() {
  22216. }
  22217. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  22218. if (!query.match(/\([^\(\)]*\)/g)) {
  22219. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  22220. }
  22221. else {
  22222. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  22223. // remove parenthesis
  22224. r = r.slice(1, r.length - 1);
  22225. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  22226. });
  22227. }
  22228. if (query === "true") {
  22229. return true;
  22230. }
  22231. if (query === "false") {
  22232. return false;
  22233. }
  22234. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  22235. };
  22236. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  22237. evaluateCallback = evaluateCallback || (function (r) {
  22238. return r === "true" ? true : false;
  22239. });
  22240. var result;
  22241. var or = parenthesisContent.split("||");
  22242. for (var i in or) {
  22243. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  22244. var and = ori.split("&&");
  22245. if (and.length > 1) {
  22246. for (var j = 0; j < and.length; ++j) {
  22247. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  22248. if (andj !== "true" && andj !== "false") {
  22249. if (andj[0] === "!") {
  22250. result = !evaluateCallback(andj.substring(1));
  22251. }
  22252. else {
  22253. result = evaluateCallback(andj);
  22254. }
  22255. }
  22256. else {
  22257. result = andj === "true" ? true : false;
  22258. }
  22259. if (!result) {
  22260. ori = "false";
  22261. break;
  22262. }
  22263. }
  22264. }
  22265. if (result || ori === "true") {
  22266. result = true;
  22267. break;
  22268. }
  22269. // result equals false (or undefined)
  22270. if (ori !== "true" && ori !== "false") {
  22271. if (ori[0] === "!") {
  22272. result = !evaluateCallback(ori.substring(1));
  22273. }
  22274. else {
  22275. result = evaluateCallback(ori);
  22276. }
  22277. }
  22278. else {
  22279. result = ori === "true" ? true : false;
  22280. }
  22281. }
  22282. // the whole parenthesis scope is replaced by 'true' or 'false'
  22283. return result ? "true" : "false";
  22284. };
  22285. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  22286. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  22287. // remove whitespaces
  22288. r = r.replace(/[\s]/g, function () { return ""; });
  22289. return r.length % 2 ? "!" : "";
  22290. });
  22291. booleanString = booleanString.trim();
  22292. if (booleanString === "!true") {
  22293. booleanString = "false";
  22294. }
  22295. else if (booleanString === "!false") {
  22296. booleanString = "true";
  22297. }
  22298. return booleanString;
  22299. };
  22300. return AndOrNotEvaluator;
  22301. })();
  22302. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  22303. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  22304. })(BABYLON || (BABYLON = {}));
  22305. //# sourceMappingURL=babylon.andOrNotEvaluator.js.mapvar BABYLON;
  22306. (function (BABYLON) {
  22307. var PostProcessRenderPass = (function () {
  22308. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  22309. this._enabled = true;
  22310. this._refCount = 0;
  22311. this._name = name;
  22312. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  22313. this.setRenderList(renderList);
  22314. this._renderTexture.onBeforeRender = beforeRender;
  22315. this._renderTexture.onAfterRender = afterRender;
  22316. this._scene = scene;
  22317. this._renderList = renderList;
  22318. }
  22319. // private
  22320. PostProcessRenderPass.prototype._incRefCount = function () {
  22321. if (this._refCount === 0) {
  22322. this._scene.customRenderTargets.push(this._renderTexture);
  22323. }
  22324. return ++this._refCount;
  22325. };
  22326. PostProcessRenderPass.prototype._decRefCount = function () {
  22327. this._refCount--;
  22328. if (this._refCount <= 0) {
  22329. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  22330. }
  22331. return this._refCount;
  22332. };
  22333. PostProcessRenderPass.prototype._update = function () {
  22334. this.setRenderList(this._renderList);
  22335. };
  22336. // public
  22337. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  22338. this._renderTexture.renderList = renderList;
  22339. };
  22340. PostProcessRenderPass.prototype.getRenderTexture = function () {
  22341. return this._renderTexture;
  22342. };
  22343. return PostProcessRenderPass;
  22344. })();
  22345. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  22346. })(BABYLON || (BABYLON = {}));
  22347. //# sourceMappingURL=babylon.postProcessRenderPass.js.mapvar BABYLON;
  22348. (function (BABYLON) {
  22349. var PostProcessRenderEffect = (function () {
  22350. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  22351. this._engine = engine;
  22352. this._name = name;
  22353. this._singleInstance = singleInstance || true;
  22354. this._getPostProcess = getPostProcess;
  22355. this._cameras = [];
  22356. this._indicesForCamera = [];
  22357. this._postProcesses = {};
  22358. this._renderPasses = {};
  22359. this._renderEffectAsPasses = {};
  22360. }
  22361. PostProcessRenderEffect.prototype._update = function () {
  22362. for (var renderPassName in this._renderPasses) {
  22363. this._renderPasses[renderPassName]._update();
  22364. }
  22365. };
  22366. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  22367. this._renderPasses[renderPass._name] = renderPass;
  22368. this._linkParameters();
  22369. };
  22370. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  22371. delete this._renderPasses[renderPass._name];
  22372. this._linkParameters();
  22373. };
  22374. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  22375. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  22376. this._linkParameters();
  22377. };
  22378. PostProcessRenderEffect.prototype.getPass = function (passName) {
  22379. for (var renderPassName in this._renderPasses) {
  22380. if (renderPassName === passName) {
  22381. return this._renderPasses[passName];
  22382. }
  22383. }
  22384. };
  22385. PostProcessRenderEffect.prototype.emptyPasses = function () {
  22386. this._renderPasses = {};
  22387. this._linkParameters();
  22388. };
  22389. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  22390. var cameraKey;
  22391. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22392. for (var i = 0; i < _cam.length; i++) {
  22393. var camera = _cam[i];
  22394. var cameraName = camera.name;
  22395. if (this._singleInstance) {
  22396. cameraKey = 0;
  22397. }
  22398. else {
  22399. cameraKey = cameraName;
  22400. }
  22401. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  22402. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  22403. if (!this._indicesForCamera[cameraName]) {
  22404. this._indicesForCamera[cameraName] = [];
  22405. }
  22406. this._indicesForCamera[cameraName].push(index);
  22407. if (this._cameras.indexOf(camera) === -1) {
  22408. this._cameras[cameraName] = camera;
  22409. }
  22410. for (var passName in this._renderPasses) {
  22411. this._renderPasses[passName]._incRefCount();
  22412. }
  22413. }
  22414. this._linkParameters();
  22415. };
  22416. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  22417. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22418. for (var i = 0; i < _cam.length; i++) {
  22419. var camera = _cam[i];
  22420. var cameraName = camera.name;
  22421. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22422. var index = this._cameras.indexOf(cameraName);
  22423. this._indicesForCamera.splice(index, 1);
  22424. this._cameras.splice(index, 1);
  22425. for (var passName in this._renderPasses) {
  22426. this._renderPasses[passName]._decRefCount();
  22427. }
  22428. }
  22429. };
  22430. PostProcessRenderEffect.prototype._enable = function (cameras) {
  22431. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22432. for (var i = 0; i < _cam.length; i++) {
  22433. var camera = _cam[i];
  22434. var cameraName = camera.name;
  22435. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  22436. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  22437. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  22438. }
  22439. }
  22440. for (var passName in this._renderPasses) {
  22441. this._renderPasses[passName]._incRefCount();
  22442. }
  22443. }
  22444. };
  22445. PostProcessRenderEffect.prototype._disable = function (cameras) {
  22446. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22447. for (var i = 0; i < _cam.length; i++) {
  22448. var camera = _cam[i];
  22449. var cameraName = camera.Name;
  22450. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  22451. for (var passName in this._renderPasses) {
  22452. this._renderPasses[passName]._decRefCount();
  22453. }
  22454. }
  22455. };
  22456. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  22457. if (this._singleInstance) {
  22458. return this._postProcesses[0];
  22459. }
  22460. else {
  22461. return this._postProcesses[camera.name];
  22462. }
  22463. };
  22464. PostProcessRenderEffect.prototype._linkParameters = function () {
  22465. var _this = this;
  22466. for (var index in this._postProcesses) {
  22467. if (this.applyParameters) {
  22468. this.applyParameters(this._postProcesses[index]);
  22469. }
  22470. this._postProcesses[index].onBeforeRender = function (effect) {
  22471. _this._linkTextures(effect);
  22472. };
  22473. }
  22474. };
  22475. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  22476. for (var renderPassName in this._renderPasses) {
  22477. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  22478. }
  22479. for (var renderEffectName in this._renderEffectAsPasses) {
  22480. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  22481. }
  22482. };
  22483. return PostProcessRenderEffect;
  22484. })();
  22485. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  22486. })(BABYLON || (BABYLON = {}));
  22487. //# sourceMappingURL=babylon.postProcessRenderEffect.js.mapvar BABYLON;
  22488. (function (BABYLON) {
  22489. var PostProcessRenderPipeline = (function () {
  22490. function PostProcessRenderPipeline(engine, name) {
  22491. this._engine = engine;
  22492. this._name = name;
  22493. this._renderEffects = {};
  22494. this._renderEffectsForIsolatedPass = {};
  22495. this._cameras = [];
  22496. }
  22497. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  22498. this._renderEffects[renderEffect._name] = renderEffect;
  22499. };
  22500. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  22501. var renderEffects = this._renderEffects[renderEffectName];
  22502. if (!renderEffects) {
  22503. return;
  22504. }
  22505. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22506. };
  22507. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  22508. var renderEffects = this._renderEffects[renderEffectName];
  22509. if (!renderEffects) {
  22510. return;
  22511. }
  22512. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  22513. };
  22514. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  22515. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22516. var indicesToDelete = [];
  22517. for (var i = 0; i < _cam.length; i++) {
  22518. var camera = _cam[i];
  22519. var cameraName = camera.name;
  22520. if (this._cameras.indexOf(camera) === -1) {
  22521. this._cameras[cameraName] = camera;
  22522. }
  22523. else if (unique) {
  22524. indicesToDelete.push(i);
  22525. }
  22526. }
  22527. for (var i = 0; i < indicesToDelete.length; i++) {
  22528. cameras.splice(indicesToDelete[i], 1);
  22529. }
  22530. for (var renderEffectName in this._renderEffects) {
  22531. this._renderEffects[renderEffectName]._attachCameras(_cam);
  22532. }
  22533. };
  22534. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  22535. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22536. for (var renderEffectName in this._renderEffects) {
  22537. this._renderEffects[renderEffectName]._detachCameras(_cam);
  22538. }
  22539. for (var i = 0; i < _cam.length; i++) {
  22540. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  22541. }
  22542. };
  22543. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  22544. var _this = this;
  22545. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22546. var pass = null;
  22547. for (var renderEffectName in this._renderEffects) {
  22548. pass = this._renderEffects[renderEffectName].getPass(passName);
  22549. if (pass != null) {
  22550. break;
  22551. }
  22552. }
  22553. if (pass === null) {
  22554. return;
  22555. }
  22556. for (var renderEffectName in this._renderEffects) {
  22557. this._renderEffects[renderEffectName]._disable(_cam);
  22558. }
  22559. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  22560. for (var i = 0; i < _cam.length; i++) {
  22561. var camera = _cam[i];
  22562. var cameraName = camera.name;
  22563. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22564. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22565. });
  22566. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  22567. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  22568. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  22569. }
  22570. };
  22571. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  22572. var _this = this;
  22573. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  22574. for (var i = 0; i < _cam.length; i++) {
  22575. var camera = _cam[i];
  22576. var cameraName = camera.name;
  22577. this._renderEffectsForIsolatedPass[cameraName] = this._renderEffectsForIsolatedPass[cameraName] || new BABYLON.PostProcessRenderEffect(this._engine, PostProcessRenderPipeline.PASS_EFFECT_NAME, function () {
  22578. return new BABYLON.DisplayPassPostProcess(PostProcessRenderPipeline.PASS_EFFECT_NAME, 1.0, null, null, _this._engine, true);
  22579. });
  22580. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  22581. }
  22582. for (var renderEffectName in this._renderEffects) {
  22583. this._renderEffects[renderEffectName]._enable(_cam);
  22584. }
  22585. };
  22586. PostProcessRenderPipeline.prototype._update = function () {
  22587. for (var renderEffectName in this._renderEffects) {
  22588. this._renderEffects[renderEffectName]._update();
  22589. }
  22590. for (var i = 0; i < this._cameras.length; i++) {
  22591. var cameraName = this._cameras[i].name;
  22592. if (this._renderEffectsForIsolatedPass[cameraName]) {
  22593. this._renderEffectsForIsolatedPass[cameraName]._update();
  22594. }
  22595. }
  22596. };
  22597. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  22598. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  22599. return PostProcessRenderPipeline;
  22600. })();
  22601. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  22602. })(BABYLON || (BABYLON = {}));
  22603. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.mapvar BABYLON;
  22604. (function (BABYLON) {
  22605. var PostProcessRenderPipelineManager = (function () {
  22606. function PostProcessRenderPipelineManager() {
  22607. this._renderPipelines = {};
  22608. }
  22609. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  22610. this._renderPipelines[renderPipeline._name] = renderPipeline;
  22611. };
  22612. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  22613. var renderPipeline = this._renderPipelines[renderPipelineName];
  22614. if (!renderPipeline) {
  22615. return;
  22616. }
  22617. renderPipeline._attachCameras(cameras, unique);
  22618. };
  22619. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  22620. var renderPipeline = this._renderPipelines[renderPipelineName];
  22621. if (!renderPipeline) {
  22622. return;
  22623. }
  22624. renderPipeline._detachCameras(cameras);
  22625. };
  22626. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22627. var renderPipeline = this._renderPipelines[renderPipelineName];
  22628. if (!renderPipeline) {
  22629. return;
  22630. }
  22631. renderPipeline._enableEffect(renderEffectName, cameras);
  22632. };
  22633. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  22634. var renderPipeline = this._renderPipelines[renderPipelineName];
  22635. if (!renderPipeline) {
  22636. return;
  22637. }
  22638. renderPipeline._disableEffect(renderEffectName, cameras);
  22639. };
  22640. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  22641. var renderPipeline = this._renderPipelines[renderPipelineName];
  22642. if (!renderPipeline) {
  22643. return;
  22644. }
  22645. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  22646. };
  22647. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  22648. var renderPipeline = this._renderPipelines[renderPipelineName];
  22649. if (!renderPipeline) {
  22650. return;
  22651. }
  22652. renderPipeline._disableDisplayOnlyPass(cameras);
  22653. };
  22654. PostProcessRenderPipelineManager.prototype.update = function () {
  22655. for (var renderPipelineName in this._renderPipelines) {
  22656. this._renderPipelines[renderPipelineName]._update();
  22657. }
  22658. };
  22659. return PostProcessRenderPipelineManager;
  22660. })();
  22661. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  22662. })(BABYLON || (BABYLON = {}));
  22663. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  22664. var BABYLON;
  22665. (function (BABYLON) {
  22666. var DisplayPassPostProcess = (function (_super) {
  22667. __extends(DisplayPassPostProcess, _super);
  22668. function DisplayPassPostProcess(name, ratio, camera, samplingMode, engine, reusable) {
  22669. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], ratio, camera, samplingMode, engine, reusable);
  22670. }
  22671. return DisplayPassPostProcess;
  22672. })(BABYLON.PostProcess);
  22673. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  22674. })(BABYLON || (BABYLON = {}));
  22675. //# sourceMappingURL=babylon.displayPassPostProcess.js.mapvar BABYLON;
  22676. (function (BABYLON) {
  22677. var BoundingBoxRenderer = (function () {
  22678. function BoundingBoxRenderer(scene) {
  22679. this.frontColor = new BABYLON.Color3(1, 1, 1);
  22680. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  22681. this.showBackLines = true;
  22682. this.renderList = new BABYLON.SmartArray(32);
  22683. this._scene = scene;
  22684. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  22685. attributes: ["position"],
  22686. uniforms: ["worldViewProjection", "color"]
  22687. });
  22688. var engine = this._scene.getEngine();
  22689. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  22690. this._vb = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  22691. 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]);
  22692. }
  22693. BoundingBoxRenderer.prototype.reset = function () {
  22694. this.renderList.reset();
  22695. };
  22696. BoundingBoxRenderer.prototype.render = function () {
  22697. if (this.renderList.length === 0 || !this._colorShader.isReady()) {
  22698. return;
  22699. }
  22700. var engine = this._scene.getEngine();
  22701. engine.setDepthWrite(false);
  22702. this._colorShader._preBind();
  22703. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  22704. var boundingBox = this.renderList.data[boundingBoxIndex];
  22705. var min = boundingBox.minimum;
  22706. var max = boundingBox.maximum;
  22707. var diff = max.subtract(min);
  22708. var median = min.add(diff.scale(0.5));
  22709. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z).multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z)).multiply(boundingBox.getWorldMatrix());
  22710. // VBOs
  22711. engine.bindBuffers(this._vb.getBuffer(), this._ib, [3], 3 * 4, this._colorShader.getEffect());
  22712. if (this.showBackLines) {
  22713. // Back
  22714. engine.setDepthFunctionToGreaterOrEqual();
  22715. this._scene.resetCachedMaterial();
  22716. this._colorShader.setColor4("color", this.backColor.toColor4());
  22717. this._colorShader.bind(worldMatrix);
  22718. // Draw order
  22719. engine.draw(false, 0, 24);
  22720. }
  22721. // Front
  22722. engine.setDepthFunctionToLess();
  22723. this._scene.resetCachedMaterial();
  22724. this._colorShader.setColor4("color", this.frontColor.toColor4());
  22725. this._colorShader.bind(worldMatrix);
  22726. // Draw order
  22727. engine.draw(false, 0, 24);
  22728. }
  22729. this._colorShader.unbind();
  22730. engine.setDepthFunctionToLessOrEqual();
  22731. engine.setDepthWrite(true);
  22732. };
  22733. BoundingBoxRenderer.prototype.dispose = function () {
  22734. this._colorShader.dispose();
  22735. this._vb.dispose();
  22736. this._scene.getEngine()._releaseBuffer(this._ib);
  22737. };
  22738. return BoundingBoxRenderer;
  22739. })();
  22740. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  22741. })(BABYLON || (BABYLON = {}));
  22742. //# sourceMappingURL=babylon.boundingBoxRenderer.js.mapvar BABYLON;
  22743. (function (BABYLON) {
  22744. var Internals;
  22745. (function (Internals) {
  22746. /*
  22747. * Based on jsTGALoader - Javascript loader for TGA file
  22748. * By Vincent Thibault
  22749. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  22750. */
  22751. var TGATools = (function () {
  22752. function TGATools() {
  22753. }
  22754. TGATools.GetTGAHeader = function (data) {
  22755. var offset = 0;
  22756. var header = {
  22757. id_length: data[offset++],
  22758. colormap_type: data[offset++],
  22759. image_type: data[offset++],
  22760. colormap_index: data[offset++] | data[offset++] << 8,
  22761. colormap_length: data[offset++] | data[offset++] << 8,
  22762. colormap_size: data[offset++],
  22763. origin: [
  22764. data[offset++] | data[offset++] << 8,
  22765. data[offset++] | data[offset++] << 8
  22766. ],
  22767. width: data[offset++] | data[offset++] << 8,
  22768. height: data[offset++] | data[offset++] << 8,
  22769. pixel_size: data[offset++],
  22770. flags: data[offset++]
  22771. };
  22772. return header;
  22773. };
  22774. TGATools.UploadContent = function (gl, data) {
  22775. // Not enough data to contain header ?
  22776. if (data.length < 19) {
  22777. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  22778. return;
  22779. }
  22780. // Read Header
  22781. var offset = 18;
  22782. var header = TGATools.GetTGAHeader(data);
  22783. // Assume it's a valid Targa file.
  22784. if (header.id_length + offset > data.length) {
  22785. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  22786. return;
  22787. }
  22788. // Skip not needed data
  22789. offset += header.id_length;
  22790. var use_rle = false;
  22791. var use_pal = false;
  22792. var use_rgb = false;
  22793. var use_grey = false;
  22794. switch (header.image_type) {
  22795. case TGATools._TYPE_RLE_INDEXED:
  22796. use_rle = true;
  22797. case TGATools._TYPE_INDEXED:
  22798. use_pal = true;
  22799. break;
  22800. case TGATools._TYPE_RLE_RGB:
  22801. use_rle = true;
  22802. case TGATools._TYPE_RGB:
  22803. use_rgb = true;
  22804. break;
  22805. case TGATools._TYPE_RLE_GREY:
  22806. use_rle = true;
  22807. case TGATools._TYPE_GREY:
  22808. use_grey = true;
  22809. break;
  22810. }
  22811. var pixel_data;
  22812. var numAlphaBits = header.flags & 0xf;
  22813. var pixel_size = header.pixel_size >> 3;
  22814. var pixel_total = header.width * header.height * pixel_size;
  22815. // Read palettes
  22816. var palettes;
  22817. if (use_pal) {
  22818. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  22819. }
  22820. // Read LRE
  22821. if (use_rle) {
  22822. pixel_data = new Uint8Array(pixel_total);
  22823. var c, count, i;
  22824. var localOffset = 0;
  22825. var pixels = new Uint8Array(pixel_size);
  22826. while (offset < pixel_total && localOffset < pixel_total) {
  22827. c = data[offset++];
  22828. count = (c & 0x7f) + 1;
  22829. // RLE pixels
  22830. if (c & 0x80) {
  22831. for (i = 0; i < pixel_size; ++i) {
  22832. pixels[i] = data[offset++];
  22833. }
  22834. for (i = 0; i < count; ++i) {
  22835. pixel_data.set(pixels, localOffset + i * pixel_size);
  22836. }
  22837. localOffset += pixel_size * count;
  22838. }
  22839. else {
  22840. count *= pixel_size;
  22841. for (i = 0; i < count; ++i) {
  22842. pixel_data[localOffset + i] = data[offset++];
  22843. }
  22844. localOffset += count;
  22845. }
  22846. }
  22847. }
  22848. else {
  22849. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  22850. }
  22851. // Load to texture
  22852. var x_start, y_start, x_step, y_step, y_end, x_end;
  22853. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  22854. default:
  22855. case TGATools._ORIGIN_UL:
  22856. x_start = 0;
  22857. x_step = 1;
  22858. x_end = header.width;
  22859. y_start = 0;
  22860. y_step = 1;
  22861. y_end = header.height;
  22862. break;
  22863. case TGATools._ORIGIN_BL:
  22864. x_start = 0;
  22865. x_step = 1;
  22866. x_end = header.width;
  22867. y_start = header.height - 1;
  22868. y_step = -1;
  22869. y_end = -1;
  22870. break;
  22871. case TGATools._ORIGIN_UR:
  22872. x_start = header.width - 1;
  22873. x_step = -1;
  22874. x_end = -1;
  22875. y_start = 0;
  22876. y_step = 1;
  22877. y_end = header.height;
  22878. break;
  22879. case TGATools._ORIGIN_BR:
  22880. x_start = header.width - 1;
  22881. x_step = -1;
  22882. x_end = -1;
  22883. y_start = header.height - 1;
  22884. y_step = -1;
  22885. y_end = -1;
  22886. break;
  22887. }
  22888. // Load the specify method
  22889. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  22890. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  22891. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  22892. };
  22893. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22894. var image = pixel_data, colormap = palettes;
  22895. var width = header.width, height = header.height;
  22896. var color, i = 0, x, y;
  22897. var imageData = new Uint8Array(width * height * 4);
  22898. for (y = y_start; y !== y_end; y += y_step) {
  22899. for (x = x_start; x !== x_end; x += x_step, i++) {
  22900. color = image[i];
  22901. imageData[(x + width * y) * 4 + 3] = 255;
  22902. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  22903. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  22904. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  22905. }
  22906. }
  22907. return imageData;
  22908. };
  22909. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22910. var image = pixel_data;
  22911. var width = header.width, height = header.height;
  22912. var color, i = 0, x, y;
  22913. var imageData = new Uint8Array(width * height * 4);
  22914. for (y = y_start; y !== y_end; y += y_step) {
  22915. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22916. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  22917. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  22918. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  22919. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  22920. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  22921. }
  22922. }
  22923. return imageData;
  22924. };
  22925. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22926. var image = pixel_data;
  22927. var width = header.width, height = header.height;
  22928. var i = 0, x, y;
  22929. var imageData = new Uint8Array(width * height * 4);
  22930. for (y = y_start; y !== y_end; y += y_step) {
  22931. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  22932. imageData[(x + width * y) * 4 + 3] = 255;
  22933. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22934. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22935. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22936. }
  22937. }
  22938. return imageData;
  22939. };
  22940. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22941. var image = pixel_data;
  22942. var width = header.width, height = header.height;
  22943. var i = 0, x, y;
  22944. var imageData = new Uint8Array(width * height * 4);
  22945. for (y = y_start; y !== y_end; y += y_step) {
  22946. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  22947. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22948. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  22949. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  22950. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  22951. }
  22952. }
  22953. return imageData;
  22954. };
  22955. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22956. var image = pixel_data;
  22957. var width = header.width, height = header.height;
  22958. var color, i = 0, x, y;
  22959. var imageData = new Uint8Array(width * height * 4);
  22960. for (y = y_start; y !== y_end; y += y_step) {
  22961. for (x = x_start; x !== x_end; x += x_step, i++) {
  22962. color = image[i];
  22963. imageData[(x + width * y) * 4 + 0] = color;
  22964. imageData[(x + width * y) * 4 + 1] = color;
  22965. imageData[(x + width * y) * 4 + 2] = color;
  22966. imageData[(x + width * y) * 4 + 3] = 255;
  22967. }
  22968. }
  22969. return imageData;
  22970. };
  22971. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  22972. var image = pixel_data;
  22973. var width = header.width, height = header.height;
  22974. var i = 0, x, y;
  22975. var imageData = new Uint8Array(width * height * 4);
  22976. for (y = y_start; y !== y_end; y += y_step) {
  22977. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  22978. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  22979. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  22980. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  22981. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  22982. }
  22983. }
  22984. return imageData;
  22985. };
  22986. TGATools._TYPE_NO_DATA = 0;
  22987. TGATools._TYPE_INDEXED = 1;
  22988. TGATools._TYPE_RGB = 2;
  22989. TGATools._TYPE_GREY = 3;
  22990. TGATools._TYPE_RLE_INDEXED = 9;
  22991. TGATools._TYPE_RLE_RGB = 10;
  22992. TGATools._TYPE_RLE_GREY = 11;
  22993. TGATools._ORIGIN_MASK = 0x30;
  22994. TGATools._ORIGIN_SHIFT = 0x04;
  22995. TGATools._ORIGIN_BL = 0x00;
  22996. TGATools._ORIGIN_BR = 0x01;
  22997. TGATools._ORIGIN_UL = 0x02;
  22998. TGATools._ORIGIN_UR = 0x03;
  22999. return TGATools;
  23000. })();
  23001. Internals.TGATools = TGATools;
  23002. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23003. })(BABYLON || (BABYLON = {}));
  23004. //# sourceMappingURL=babylon.tools.tga.js.mapvar BABYLON;
  23005. (function (BABYLON) {
  23006. var Internals;
  23007. (function (Internals) {
  23008. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  23009. // All values and structures referenced from:
  23010. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  23011. var DDS_MAGIC = 0x20534444;
  23012. 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;
  23013. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  23014. 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;
  23015. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  23016. function FourCCToInt32(value) {
  23017. return value.charCodeAt(0) + (value.charCodeAt(1) << 8) + (value.charCodeAt(2) << 16) + (value.charCodeAt(3) << 24);
  23018. }
  23019. function Int32ToFourCC(value) {
  23020. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  23021. }
  23022. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  23023. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  23024. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  23025. var headerLengthInt = 31; // The header length in 32 bit ints
  23026. // Offsets into the header array
  23027. var off_magic = 0;
  23028. var off_size = 1;
  23029. var off_flags = 2;
  23030. var off_height = 3;
  23031. var off_width = 4;
  23032. var off_mipmapCount = 7;
  23033. var off_pfFlags = 20;
  23034. var off_pfFourCC = 21;
  23035. var off_RGBbpp = 22;
  23036. var off_RMask = 23;
  23037. var off_GMask = 24;
  23038. var off_BMask = 25;
  23039. var off_AMask = 26;
  23040. var off_caps1 = 27;
  23041. var off_caps2 = 28;
  23042. ;
  23043. var DDSTools = (function () {
  23044. function DDSTools() {
  23045. }
  23046. DDSTools.GetDDSInfo = function (arrayBuffer) {
  23047. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  23048. var mipmapCount = 1;
  23049. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  23050. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23051. }
  23052. return {
  23053. width: header[off_width],
  23054. height: header[off_height],
  23055. mipmapCount: mipmapCount,
  23056. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  23057. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  23058. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  23059. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  23060. };
  23061. };
  23062. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23063. var byteArray = new Uint8Array(dataLength);
  23064. var srcData = new Uint8Array(arrayBuffer);
  23065. var index = 0;
  23066. for (var y = height - 1; y >= 0; y--) {
  23067. for (var x = 0; x < width; x++) {
  23068. var srcPos = dataOffset + (x + y * width) * 4;
  23069. byteArray[index + 2] = srcData[srcPos];
  23070. byteArray[index + 1] = srcData[srcPos + 1];
  23071. byteArray[index] = srcData[srcPos + 2];
  23072. byteArray[index + 3] = srcData[srcPos + 3];
  23073. index += 4;
  23074. }
  23075. }
  23076. return byteArray;
  23077. };
  23078. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23079. var byteArray = new Uint8Array(dataLength);
  23080. var srcData = new Uint8Array(arrayBuffer);
  23081. var index = 0;
  23082. for (var y = height - 1; y >= 0; y--) {
  23083. for (var x = 0; x < width; x++) {
  23084. var srcPos = dataOffset + (x + y * width) * 3;
  23085. byteArray[index + 2] = srcData[srcPos];
  23086. byteArray[index + 1] = srcData[srcPos + 1];
  23087. byteArray[index] = srcData[srcPos + 2];
  23088. index += 3;
  23089. }
  23090. }
  23091. return byteArray;
  23092. };
  23093. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  23094. var byteArray = new Uint8Array(dataLength);
  23095. var srcData = new Uint8Array(arrayBuffer);
  23096. var index = 0;
  23097. for (var y = height - 1; y >= 0; y--) {
  23098. for (var x = 0; x < width; x++) {
  23099. var srcPos = dataOffset + (x + y * width);
  23100. byteArray[index] = srcData[srcPos];
  23101. index++;
  23102. }
  23103. }
  23104. return byteArray;
  23105. };
  23106. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  23107. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  23108. if (header[off_magic] != DDS_MAGIC) {
  23109. BABYLON.Tools.Error("Invalid magic number in DDS header");
  23110. return;
  23111. }
  23112. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  23113. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  23114. return;
  23115. }
  23116. if (info.isFourCC) {
  23117. fourCC = header[off_pfFourCC];
  23118. switch (fourCC) {
  23119. case FOURCC_DXT1:
  23120. blockBytes = 8;
  23121. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  23122. break;
  23123. case FOURCC_DXT3:
  23124. blockBytes = 16;
  23125. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  23126. break;
  23127. case FOURCC_DXT5:
  23128. blockBytes = 16;
  23129. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  23130. break;
  23131. default:
  23132. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  23133. return;
  23134. }
  23135. }
  23136. mipmapCount = 1;
  23137. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  23138. mipmapCount = Math.max(1, header[off_mipmapCount]);
  23139. }
  23140. var bpp = header[off_RGBbpp];
  23141. for (var face = 0; face < faces; face++) {
  23142. var sampler = faces == 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  23143. width = header[off_width];
  23144. height = header[off_height];
  23145. dataOffset = header[off_size] + 4;
  23146. for (i = 0; i < mipmapCount; ++i) {
  23147. if (info.isRGB) {
  23148. if (bpp == 24) {
  23149. dataLength = width * height * 3;
  23150. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23151. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  23152. }
  23153. else {
  23154. dataLength = width * height * 4;
  23155. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23156. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  23157. }
  23158. }
  23159. else if (info.isLuminance) {
  23160. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  23161. var unpaddedRowSize = width;
  23162. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  23163. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  23164. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  23165. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  23166. }
  23167. else {
  23168. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  23169. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  23170. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  23171. }
  23172. dataOffset += dataLength;
  23173. width *= 0.5;
  23174. height *= 0.5;
  23175. width = Math.max(1.0, width);
  23176. height = Math.max(1.0, height);
  23177. }
  23178. }
  23179. };
  23180. return DDSTools;
  23181. })();
  23182. Internals.DDSTools = DDSTools;
  23183. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  23184. })(BABYLON || (BABYLON = {}));
  23185. //# sourceMappingURL=babylon.tools.dds.js.mapvar BABYLON;
  23186. (function (BABYLON) {
  23187. var SmartArray = (function () {
  23188. function SmartArray(capacity) {
  23189. this.length = 0;
  23190. this._duplicateId = 0;
  23191. this.data = new Array(capacity);
  23192. this._id = SmartArray._GlobalId++;
  23193. }
  23194. SmartArray.prototype.push = function (value) {
  23195. this.data[this.length++] = value;
  23196. if (this.length > this.data.length) {
  23197. this.data.length *= 2;
  23198. }
  23199. if (!value.__smartArrayFlags) {
  23200. value.__smartArrayFlags = {};
  23201. }
  23202. value.__smartArrayFlags[this._id] = this._duplicateId;
  23203. };
  23204. SmartArray.prototype.pushNoDuplicate = function (value) {
  23205. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  23206. return;
  23207. }
  23208. this.push(value);
  23209. };
  23210. SmartArray.prototype.sort = function (compareFn) {
  23211. this.data.sort(compareFn);
  23212. };
  23213. SmartArray.prototype.reset = function () {
  23214. this.length = 0;
  23215. this._duplicateId++;
  23216. };
  23217. SmartArray.prototype.concat = function (array) {
  23218. if (array.length === 0) {
  23219. return;
  23220. }
  23221. if (this.length + array.length > this.data.length) {
  23222. this.data.length = (this.length + array.length) * 2;
  23223. }
  23224. for (var index = 0; index < array.length; index++) {
  23225. this.data[this.length++] = (array.data || array)[index];
  23226. }
  23227. };
  23228. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  23229. if (array.length === 0) {
  23230. return;
  23231. }
  23232. if (this.length + array.length > this.data.length) {
  23233. this.data.length = (this.length + array.length) * 2;
  23234. }
  23235. for (var index = 0; index < array.length; index++) {
  23236. var item = (array.data || array)[index];
  23237. this.pushNoDuplicate(item);
  23238. }
  23239. };
  23240. SmartArray.prototype.indexOf = function (value) {
  23241. var position = this.data.indexOf(value);
  23242. if (position >= this.length) {
  23243. return -1;
  23244. }
  23245. return position;
  23246. };
  23247. // Statics
  23248. SmartArray._GlobalId = 0;
  23249. return SmartArray;
  23250. })();
  23251. BABYLON.SmartArray = SmartArray;
  23252. })(BABYLON || (BABYLON = {}));
  23253. //# sourceMappingURL=babylon.smartArray.js.mapvar BABYLON;
  23254. (function (BABYLON) {
  23255. var CannonJSPlugin = (function () {
  23256. function CannonJSPlugin() {
  23257. this._registeredMeshes = [];
  23258. this._physicsMaterials = [];
  23259. this.updateBodyPosition = function (mesh) {
  23260. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23261. var registeredMesh = this._registeredMeshes[index];
  23262. if (registeredMesh.mesh === mesh || registeredMesh.mesh === mesh.parent) {
  23263. var body = registeredMesh.body;
  23264. var center = mesh.getBoundingInfo().boundingBox.center;
  23265. body.position.set(center.x, center.z, center.y);
  23266. body.quaternion.x = mesh.rotationQuaternion.x;
  23267. body.quaternion.z = mesh.rotationQuaternion.y;
  23268. body.quaternion.y = mesh.rotationQuaternion.z;
  23269. body.quaternion.w = -mesh.rotationQuaternion.w;
  23270. return;
  23271. }
  23272. }
  23273. };
  23274. }
  23275. CannonJSPlugin.prototype.initialize = function (iterations) {
  23276. if (iterations === void 0) { iterations = 10; }
  23277. this._world = new CANNON.World();
  23278. this._world.broadphase = new CANNON.NaiveBroadphase();
  23279. this._world.solver.iterations = iterations;
  23280. };
  23281. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  23282. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  23283. };
  23284. CannonJSPlugin.prototype.runOneStep = function (delta) {
  23285. this._world.step(delta);
  23286. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23287. var registeredMesh = this._registeredMeshes[index];
  23288. if (registeredMesh.isChild) {
  23289. continue;
  23290. }
  23291. // Body position
  23292. var bodyX = registeredMesh.body.position.x, bodyY = registeredMesh.body.position.y, bodyZ = registeredMesh.body.position.z;
  23293. var deltaPos = registeredMesh.delta;
  23294. if (deltaPos) {
  23295. registeredMesh.mesh.position.x = bodyX + deltaPos.x;
  23296. registeredMesh.mesh.position.y = bodyZ + deltaPos.y;
  23297. registeredMesh.mesh.position.z = bodyY + deltaPos.z;
  23298. }
  23299. else {
  23300. registeredMesh.mesh.position.x = bodyX;
  23301. registeredMesh.mesh.position.y = bodyZ;
  23302. registeredMesh.mesh.position.z = bodyY;
  23303. }
  23304. if (!registeredMesh.mesh.rotationQuaternion) {
  23305. registeredMesh.mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23306. }
  23307. registeredMesh.mesh.rotationQuaternion.x = registeredMesh.body.quaternion.x;
  23308. registeredMesh.mesh.rotationQuaternion.y = registeredMesh.body.quaternion.z;
  23309. registeredMesh.mesh.rotationQuaternion.z = registeredMesh.body.quaternion.y;
  23310. registeredMesh.mesh.rotationQuaternion.w = -registeredMesh.body.quaternion.w;
  23311. }
  23312. };
  23313. CannonJSPlugin.prototype.setGravity = function (gravity) {
  23314. this._world.gravity.set(gravity.x, gravity.z, gravity.y);
  23315. };
  23316. CannonJSPlugin.prototype.registerMesh = function (mesh, impostor, options) {
  23317. this.unregisterMesh(mesh);
  23318. mesh.computeWorldMatrix(true);
  23319. switch (impostor) {
  23320. case BABYLON.PhysicsEngine.SphereImpostor:
  23321. var bbox = mesh.getBoundingInfo().boundingBox;
  23322. var radiusX = bbox.maximumWorld.x - bbox.minimumWorld.x;
  23323. var radiusY = bbox.maximumWorld.y - bbox.minimumWorld.y;
  23324. var radiusZ = bbox.maximumWorld.z - bbox.minimumWorld.z;
  23325. return this._createSphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2, mesh, options);
  23326. case BABYLON.PhysicsEngine.BoxImpostor:
  23327. bbox = mesh.getBoundingInfo().boundingBox;
  23328. var min = bbox.minimumWorld;
  23329. var max = bbox.maximumWorld;
  23330. var box = max.subtract(min).scale(0.5);
  23331. return this._createBox(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z), mesh, options);
  23332. case BABYLON.PhysicsEngine.PlaneImpostor:
  23333. return this._createPlane(mesh, options);
  23334. case BABYLON.PhysicsEngine.MeshImpostor:
  23335. var rawVerts = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23336. var rawFaces = mesh.getIndices();
  23337. return this._createConvexPolyhedron(rawVerts, rawFaces, mesh, options);
  23338. }
  23339. return null;
  23340. };
  23341. CannonJSPlugin.prototype._createSphere = function (radius, mesh, options) {
  23342. var shape = new CANNON.Sphere(radius);
  23343. if (!options) {
  23344. return shape;
  23345. }
  23346. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23347. };
  23348. CannonJSPlugin.prototype._createBox = function (x, y, z, mesh, options) {
  23349. var shape = new CANNON.Box(new CANNON.Vec3(x, z, y));
  23350. if (!options) {
  23351. return shape;
  23352. }
  23353. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23354. };
  23355. CannonJSPlugin.prototype._createPlane = function (mesh, options) {
  23356. var shape = new CANNON.Plane();
  23357. if (!options) {
  23358. return shape;
  23359. }
  23360. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23361. };
  23362. CannonJSPlugin.prototype._createConvexPolyhedron = function (rawVerts, rawFaces, mesh, options) {
  23363. var verts = [], faces = [];
  23364. mesh.computeWorldMatrix(true);
  23365. for (var i = 0; i < rawVerts.length; i += 3) {
  23366. var transformed = BABYLON.Vector3.Zero();
  23367. BABYLON.Vector3.TransformNormalFromFloatsToRef(rawVerts[i], rawVerts[i + 1], rawVerts[i + 2], mesh.getWorldMatrix(), transformed);
  23368. verts.push(new CANNON.Vec3(transformed.x, transformed.z, transformed.y));
  23369. }
  23370. for (var j = 0; j < rawFaces.length; j += 3) {
  23371. faces.push([rawFaces[j], rawFaces[j + 2], rawFaces[j + 1]]);
  23372. }
  23373. var shape = new CANNON.ConvexPolyhedron(verts, faces);
  23374. if (!options) {
  23375. return shape;
  23376. }
  23377. return this._createRigidBodyFromShape(shape, mesh, options.mass, options.friction, options.restitution);
  23378. };
  23379. CannonJSPlugin.prototype._addMaterial = function (friction, restitution) {
  23380. var index;
  23381. var mat;
  23382. for (index = 0; index < this._physicsMaterials.length; index++) {
  23383. mat = this._physicsMaterials[index];
  23384. if (mat.friction === friction && mat.restitution === restitution) {
  23385. return mat;
  23386. }
  23387. }
  23388. var currentMat = new CANNON.Material();
  23389. currentMat.friction = friction;
  23390. currentMat.restitution = restitution;
  23391. this._physicsMaterials.push(currentMat);
  23392. for (index = 0; index < this._physicsMaterials.length; index++) {
  23393. mat = this._physicsMaterials[index];
  23394. var contactMaterial = new CANNON.ContactMaterial(mat, currentMat, mat.friction * currentMat.friction, mat.restitution * currentMat.restitution);
  23395. contactMaterial.contactEquationStiffness = 1e10;
  23396. contactMaterial.contactEquationRegularizationTime = 10;
  23397. this._world.addContactMaterial(contactMaterial);
  23398. }
  23399. return currentMat;
  23400. };
  23401. CannonJSPlugin.prototype._createRigidBodyFromShape = function (shape, mesh, mass, friction, restitution) {
  23402. var initialRotation = null;
  23403. if (mesh.rotationQuaternion) {
  23404. initialRotation = mesh.rotationQuaternion.clone();
  23405. mesh.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 1);
  23406. }
  23407. // The delta between the mesh position and the mesh bounding box center
  23408. var bbox = mesh.getBoundingInfo().boundingBox;
  23409. var deltaPosition = mesh.position.subtract(bbox.center);
  23410. var material = this._addMaterial(friction, restitution);
  23411. var body = new CANNON.RigidBody(mass, shape, material);
  23412. if (initialRotation) {
  23413. body.quaternion.x = initialRotation.x;
  23414. body.quaternion.z = initialRotation.y;
  23415. body.quaternion.y = initialRotation.z;
  23416. body.quaternion.w = -initialRotation.w;
  23417. }
  23418. body.position.set(bbox.center.x, bbox.center.z, bbox.center.y);
  23419. this._world.add(body);
  23420. this._registeredMeshes.push({ mesh: mesh, body: body, material: material, delta: deltaPosition });
  23421. return body;
  23422. };
  23423. CannonJSPlugin.prototype.registerMeshesAsCompound = function (parts, options) {
  23424. var compoundShape = new CANNON.Compound();
  23425. for (var index = 0; index < parts.length; index++) {
  23426. var mesh = parts[index].mesh;
  23427. var shape = this.registerMesh(mesh, parts[index].impostor);
  23428. if (index == 0) {
  23429. compoundShape.addChild(shape, new CANNON.Vec3(0, 0, 0));
  23430. }
  23431. else {
  23432. compoundShape.addChild(shape, new CANNON.Vec3(mesh.position.x, mesh.position.z, mesh.position.y));
  23433. }
  23434. }
  23435. var initialMesh = parts[0].mesh;
  23436. var body = this._createRigidBodyFromShape(compoundShape, initialMesh, options.mass, options.friction, options.restitution);
  23437. body.parts = parts;
  23438. return body;
  23439. };
  23440. CannonJSPlugin.prototype._unbindBody = function (body) {
  23441. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23442. var registeredMesh = this._registeredMeshes[index];
  23443. if (registeredMesh.body === body) {
  23444. registeredMesh.body = null;
  23445. registeredMesh.delta = 0;
  23446. }
  23447. }
  23448. };
  23449. CannonJSPlugin.prototype.unregisterMesh = function (mesh) {
  23450. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23451. var registeredMesh = this._registeredMeshes[index];
  23452. if (registeredMesh.mesh === mesh) {
  23453. // Remove body
  23454. if (registeredMesh.body) {
  23455. this._world.remove(registeredMesh.body);
  23456. this._unbindBody(registeredMesh.body);
  23457. }
  23458. this._registeredMeshes.splice(index, 1);
  23459. return;
  23460. }
  23461. }
  23462. };
  23463. CannonJSPlugin.prototype.applyImpulse = function (mesh, force, contactPoint) {
  23464. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.z, contactPoint.y);
  23465. var impulse = new CANNON.Vec3(force.x, force.z, force.y);
  23466. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23467. var registeredMesh = this._registeredMeshes[index];
  23468. if (registeredMesh.mesh === mesh) {
  23469. registeredMesh.body.applyImpulse(impulse, worldPoint);
  23470. return;
  23471. }
  23472. }
  23473. };
  23474. CannonJSPlugin.prototype.createLink = function (mesh1, mesh2, pivot1, pivot2) {
  23475. var body1 = null, body2 = null;
  23476. for (var index = 0; index < this._registeredMeshes.length; index++) {
  23477. var registeredMesh = this._registeredMeshes[index];
  23478. if (registeredMesh.mesh === mesh1) {
  23479. body1 = registeredMesh.body;
  23480. }
  23481. else if (registeredMesh.mesh === mesh2) {
  23482. body2 = registeredMesh.body;
  23483. }
  23484. }
  23485. if (!body1 || !body2) {
  23486. return false;
  23487. }
  23488. 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));
  23489. this._world.addConstraint(constraint);
  23490. return true;
  23491. };
  23492. CannonJSPlugin.prototype.dispose = function () {
  23493. while (this._registeredMeshes.length) {
  23494. this.unregisterMesh(this._registeredMeshes[0].mesh);
  23495. }
  23496. };
  23497. CannonJSPlugin.prototype.isSupported = function () {
  23498. return window.CANNON !== undefined;
  23499. };
  23500. return CannonJSPlugin;
  23501. })();
  23502. BABYLON.CannonJSPlugin = CannonJSPlugin;
  23503. })(BABYLON || (BABYLON = {}));
  23504. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  23505. var BABYLON;
  23506. (function (BABYLON) {
  23507. var Condition = (function () {
  23508. function Condition(actionManager) {
  23509. this._actionManager = actionManager;
  23510. }
  23511. Condition.prototype.isValid = function () {
  23512. return true;
  23513. };
  23514. Condition.prototype._getProperty = function (propertyPath) {
  23515. return this._actionManager._getProperty(propertyPath);
  23516. };
  23517. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  23518. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23519. };
  23520. return Condition;
  23521. })();
  23522. BABYLON.Condition = Condition;
  23523. var ValueCondition = (function (_super) {
  23524. __extends(ValueCondition, _super);
  23525. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  23526. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  23527. _super.call(this, actionManager);
  23528. this.propertyPath = propertyPath;
  23529. this.value = value;
  23530. this.operator = operator;
  23531. this._target = this._getEffectiveTarget(target, this.propertyPath);
  23532. this._property = this._getProperty(this.propertyPath);
  23533. }
  23534. Object.defineProperty(ValueCondition, "IsEqual", {
  23535. get: function () {
  23536. return ValueCondition._IsEqual;
  23537. },
  23538. enumerable: true,
  23539. configurable: true
  23540. });
  23541. Object.defineProperty(ValueCondition, "IsDifferent", {
  23542. get: function () {
  23543. return ValueCondition._IsDifferent;
  23544. },
  23545. enumerable: true,
  23546. configurable: true
  23547. });
  23548. Object.defineProperty(ValueCondition, "IsGreater", {
  23549. get: function () {
  23550. return ValueCondition._IsGreater;
  23551. },
  23552. enumerable: true,
  23553. configurable: true
  23554. });
  23555. Object.defineProperty(ValueCondition, "IsLesser", {
  23556. get: function () {
  23557. return ValueCondition._IsLesser;
  23558. },
  23559. enumerable: true,
  23560. configurable: true
  23561. });
  23562. // Methods
  23563. ValueCondition.prototype.isValid = function () {
  23564. switch (this.operator) {
  23565. case ValueCondition.IsGreater:
  23566. return this._target[this._property] > this.value;
  23567. case ValueCondition.IsLesser:
  23568. return this._target[this._property] < this.value;
  23569. case ValueCondition.IsEqual:
  23570. case ValueCondition.IsDifferent:
  23571. var check;
  23572. if (this.value.equals) {
  23573. check = this.value.equals(this._target[this._property]);
  23574. }
  23575. else {
  23576. check = this.value === this._target[this._property];
  23577. }
  23578. return this.operator === ValueCondition.IsEqual ? check : !check;
  23579. }
  23580. return false;
  23581. };
  23582. // Statics
  23583. ValueCondition._IsEqual = 0;
  23584. ValueCondition._IsDifferent = 1;
  23585. ValueCondition._IsGreater = 2;
  23586. ValueCondition._IsLesser = 3;
  23587. return ValueCondition;
  23588. })(Condition);
  23589. BABYLON.ValueCondition = ValueCondition;
  23590. var PredicateCondition = (function (_super) {
  23591. __extends(PredicateCondition, _super);
  23592. function PredicateCondition(actionManager, predicate) {
  23593. _super.call(this, actionManager);
  23594. this.predicate = predicate;
  23595. }
  23596. PredicateCondition.prototype.isValid = function () {
  23597. return this.predicate();
  23598. };
  23599. return PredicateCondition;
  23600. })(Condition);
  23601. BABYLON.PredicateCondition = PredicateCondition;
  23602. var StateCondition = (function (_super) {
  23603. __extends(StateCondition, _super);
  23604. function StateCondition(actionManager, target, value) {
  23605. _super.call(this, actionManager);
  23606. this.value = value;
  23607. this._target = target;
  23608. }
  23609. // Methods
  23610. StateCondition.prototype.isValid = function () {
  23611. return this._target.state === this.value;
  23612. };
  23613. return StateCondition;
  23614. })(Condition);
  23615. BABYLON.StateCondition = StateCondition;
  23616. })(BABYLON || (BABYLON = {}));
  23617. //# sourceMappingURL=babylon.condition.js.mapvar BABYLON;
  23618. (function (BABYLON) {
  23619. var Action = (function () {
  23620. function Action(triggerOptions, condition) {
  23621. this.triggerOptions = triggerOptions;
  23622. if (triggerOptions.parameter) {
  23623. this.trigger = triggerOptions.trigger;
  23624. this._triggerParameter = triggerOptions.parameter;
  23625. }
  23626. else {
  23627. this.trigger = triggerOptions;
  23628. }
  23629. this._nextActiveAction = this;
  23630. this._condition = condition;
  23631. }
  23632. // Methods
  23633. Action.prototype._prepare = function () {
  23634. };
  23635. Action.prototype.getTriggerParameter = function () {
  23636. return this._triggerParameter;
  23637. };
  23638. Action.prototype._executeCurrent = function (evt) {
  23639. if (this._nextActiveAction._condition) {
  23640. var condition = this._nextActiveAction._condition;
  23641. var currentRenderId = this._actionManager.getScene().getRenderId();
  23642. // We cache the current evaluation for the current frame
  23643. if (condition._evaluationId === currentRenderId) {
  23644. if (!condition._currentResult) {
  23645. return;
  23646. }
  23647. }
  23648. else {
  23649. condition._evaluationId = currentRenderId;
  23650. if (!condition.isValid()) {
  23651. condition._currentResult = false;
  23652. return;
  23653. }
  23654. condition._currentResult = true;
  23655. }
  23656. }
  23657. this._nextActiveAction.execute(evt);
  23658. if (this._nextActiveAction._child) {
  23659. if (!this._nextActiveAction._child._actionManager) {
  23660. this._nextActiveAction._child._actionManager = this._actionManager;
  23661. }
  23662. this._nextActiveAction = this._nextActiveAction._child;
  23663. }
  23664. else {
  23665. this._nextActiveAction = this;
  23666. }
  23667. };
  23668. Action.prototype.execute = function (evt) {
  23669. };
  23670. Action.prototype.then = function (action) {
  23671. this._child = action;
  23672. action._actionManager = this._actionManager;
  23673. action._prepare();
  23674. return action;
  23675. };
  23676. Action.prototype._getProperty = function (propertyPath) {
  23677. return this._actionManager._getProperty(propertyPath);
  23678. };
  23679. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  23680. return this._actionManager._getEffectiveTarget(target, propertyPath);
  23681. };
  23682. return Action;
  23683. })();
  23684. BABYLON.Action = Action;
  23685. })(BABYLON || (BABYLON = {}));
  23686. //# sourceMappingURL=babylon.action.js.mapvar BABYLON;
  23687. (function (BABYLON) {
  23688. /**
  23689. * ActionEvent is the event beint sent when an action is triggered.
  23690. */
  23691. var ActionEvent = (function () {
  23692. /**
  23693. * @constructor
  23694. * @param source The mesh that triggered the action.
  23695. * @param pointerX the X mouse cursor position at the time of the event
  23696. * @param pointerY the Y mouse cursor position at the time of the event
  23697. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  23698. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  23699. */
  23700. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent) {
  23701. this.source = source;
  23702. this.pointerX = pointerX;
  23703. this.pointerY = pointerY;
  23704. this.meshUnderPointer = meshUnderPointer;
  23705. this.sourceEvent = sourceEvent;
  23706. }
  23707. /**
  23708. * Helper function to auto-create an ActionEvent from a source mesh.
  23709. * @param source the source mesh that triggered the event
  23710. * @param evt {Event} The original (browser) event
  23711. */
  23712. ActionEvent.CreateNew = function (source, evt) {
  23713. var scene = source.getScene();
  23714. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23715. };
  23716. /**
  23717. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  23718. * @param scene the scene where the event occurred
  23719. * @param evt {Event} The original (browser) event
  23720. */
  23721. ActionEvent.CreateNewFromScene = function (scene, evt) {
  23722. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  23723. };
  23724. return ActionEvent;
  23725. })();
  23726. BABYLON.ActionEvent = ActionEvent;
  23727. /**
  23728. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  23729. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  23730. */
  23731. var ActionManager = (function () {
  23732. function ActionManager(scene) {
  23733. // Members
  23734. this.actions = new Array();
  23735. this._scene = scene;
  23736. scene._actionManagers.push(this);
  23737. }
  23738. Object.defineProperty(ActionManager, "NothingTrigger", {
  23739. get: function () {
  23740. return ActionManager._NothingTrigger;
  23741. },
  23742. enumerable: true,
  23743. configurable: true
  23744. });
  23745. Object.defineProperty(ActionManager, "OnPickTrigger", {
  23746. get: function () {
  23747. return ActionManager._OnPickTrigger;
  23748. },
  23749. enumerable: true,
  23750. configurable: true
  23751. });
  23752. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  23753. get: function () {
  23754. return ActionManager._OnLeftPickTrigger;
  23755. },
  23756. enumerable: true,
  23757. configurable: true
  23758. });
  23759. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  23760. get: function () {
  23761. return ActionManager._OnRightPickTrigger;
  23762. },
  23763. enumerable: true,
  23764. configurable: true
  23765. });
  23766. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  23767. get: function () {
  23768. return ActionManager._OnCenterPickTrigger;
  23769. },
  23770. enumerable: true,
  23771. configurable: true
  23772. });
  23773. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  23774. get: function () {
  23775. return ActionManager._OnPointerOverTrigger;
  23776. },
  23777. enumerable: true,
  23778. configurable: true
  23779. });
  23780. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  23781. get: function () {
  23782. return ActionManager._OnPointerOutTrigger;
  23783. },
  23784. enumerable: true,
  23785. configurable: true
  23786. });
  23787. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  23788. get: function () {
  23789. return ActionManager._OnEveryFrameTrigger;
  23790. },
  23791. enumerable: true,
  23792. configurable: true
  23793. });
  23794. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  23795. get: function () {
  23796. return ActionManager._OnIntersectionEnterTrigger;
  23797. },
  23798. enumerable: true,
  23799. configurable: true
  23800. });
  23801. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  23802. get: function () {
  23803. return ActionManager._OnIntersectionExitTrigger;
  23804. },
  23805. enumerable: true,
  23806. configurable: true
  23807. });
  23808. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  23809. get: function () {
  23810. return ActionManager._OnKeyDownTrigger;
  23811. },
  23812. enumerable: true,
  23813. configurable: true
  23814. });
  23815. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  23816. get: function () {
  23817. return ActionManager._OnKeyUpTrigger;
  23818. },
  23819. enumerable: true,
  23820. configurable: true
  23821. });
  23822. // Methods
  23823. ActionManager.prototype.dispose = function () {
  23824. var index = this._scene._actionManagers.indexOf(this);
  23825. if (index > -1) {
  23826. this._scene._actionManagers.splice(index, 1);
  23827. }
  23828. };
  23829. ActionManager.prototype.getScene = function () {
  23830. return this._scene;
  23831. };
  23832. /**
  23833. * Does this action manager handles actions of any of the given triggers
  23834. * @param {number[]} triggers - the triggers to be tested
  23835. * @return {boolean} whether one (or more) of the triggers is handeled
  23836. */
  23837. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  23838. for (var index = 0; index < this.actions.length; index++) {
  23839. var action = this.actions[index];
  23840. if (triggers.indexOf(action.trigger) > -1) {
  23841. return true;
  23842. }
  23843. }
  23844. return false;
  23845. };
  23846. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  23847. /**
  23848. * Does this action manager has pointer triggers
  23849. * @return {boolean} whether or not it has pointer triggers
  23850. */
  23851. get: function () {
  23852. for (var index = 0; index < this.actions.length; index++) {
  23853. var action = this.actions[index];
  23854. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  23855. return true;
  23856. }
  23857. }
  23858. return false;
  23859. },
  23860. enumerable: true,
  23861. configurable: true
  23862. });
  23863. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  23864. /**
  23865. * Does this action manager has pick triggers
  23866. * @return {boolean} whether or not it has pick triggers
  23867. */
  23868. get: function () {
  23869. for (var index = 0; index < this.actions.length; index++) {
  23870. var action = this.actions[index];
  23871. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnCenterPickTrigger) {
  23872. return true;
  23873. }
  23874. }
  23875. return false;
  23876. },
  23877. enumerable: true,
  23878. configurable: true
  23879. });
  23880. /**
  23881. * Registers an action to this action manager
  23882. * @param {BABYLON.Action} action - the action to be registered
  23883. * @return {BABYLON.Action} the action amended (prepared) after registration
  23884. */
  23885. ActionManager.prototype.registerAction = function (action) {
  23886. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  23887. if (this.getScene().actionManager !== this) {
  23888. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  23889. return null;
  23890. }
  23891. }
  23892. this.actions.push(action);
  23893. action._actionManager = this;
  23894. action._prepare();
  23895. return action;
  23896. };
  23897. /**
  23898. * Process a specific trigger
  23899. * @param {number} trigger - the trigger to process
  23900. * @param evt {BABYLON.ActionEvent} the event details to be processed
  23901. */
  23902. ActionManager.prototype.processTrigger = function (trigger, evt) {
  23903. for (var index = 0; index < this.actions.length; index++) {
  23904. var action = this.actions[index];
  23905. if (action.trigger === trigger) {
  23906. if (trigger === ActionManager.OnKeyUpTrigger || trigger === ActionManager.OnKeyDownTrigger) {
  23907. var parameter = action.getTriggerParameter();
  23908. if (parameter) {
  23909. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  23910. var actualkey = String.fromCharCode(unicode).toLowerCase();
  23911. if (actualkey !== parameter.toLowerCase()) {
  23912. continue;
  23913. }
  23914. }
  23915. }
  23916. action._executeCurrent(evt);
  23917. }
  23918. }
  23919. };
  23920. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  23921. var properties = propertyPath.split(".");
  23922. for (var index = 0; index < properties.length - 1; index++) {
  23923. target = target[properties[index]];
  23924. }
  23925. return target;
  23926. };
  23927. ActionManager.prototype._getProperty = function (propertyPath) {
  23928. var properties = propertyPath.split(".");
  23929. return properties[properties.length - 1];
  23930. };
  23931. // Statics
  23932. ActionManager._NothingTrigger = 0;
  23933. ActionManager._OnPickTrigger = 1;
  23934. ActionManager._OnLeftPickTrigger = 2;
  23935. ActionManager._OnRightPickTrigger = 3;
  23936. ActionManager._OnCenterPickTrigger = 4;
  23937. ActionManager._OnPointerOverTrigger = 5;
  23938. ActionManager._OnPointerOutTrigger = 6;
  23939. ActionManager._OnEveryFrameTrigger = 7;
  23940. ActionManager._OnIntersectionEnterTrigger = 8;
  23941. ActionManager._OnIntersectionExitTrigger = 9;
  23942. ActionManager._OnKeyDownTrigger = 10;
  23943. ActionManager._OnKeyUpTrigger = 11;
  23944. return ActionManager;
  23945. })();
  23946. BABYLON.ActionManager = ActionManager;
  23947. })(BABYLON || (BABYLON = {}));
  23948. //# sourceMappingURL=babylon.actionManager.js.map
  23949. var BABYLON;
  23950. (function (BABYLON) {
  23951. var InterpolateValueAction = (function (_super) {
  23952. __extends(InterpolateValueAction, _super);
  23953. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations) {
  23954. if (duration === void 0) { duration = 1000; }
  23955. _super.call(this, triggerOptions, condition);
  23956. this.propertyPath = propertyPath;
  23957. this.value = value;
  23958. this.duration = duration;
  23959. this.stopOtherAnimations = stopOtherAnimations;
  23960. this._target = target;
  23961. }
  23962. InterpolateValueAction.prototype._prepare = function () {
  23963. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  23964. this._property = this._getProperty(this.propertyPath);
  23965. };
  23966. InterpolateValueAction.prototype.execute = function () {
  23967. var scene = this._actionManager.getScene();
  23968. var keys = [
  23969. {
  23970. frame: 0,
  23971. value: this._target[this._property]
  23972. },
  23973. {
  23974. frame: 100,
  23975. value: this.value
  23976. }
  23977. ];
  23978. var dataType;
  23979. if (typeof this.value === "number") {
  23980. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  23981. }
  23982. else if (this.value instanceof BABYLON.Color3) {
  23983. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  23984. }
  23985. else if (this.value instanceof BABYLON.Vector3) {
  23986. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  23987. }
  23988. else if (this.value instanceof BABYLON.Matrix) {
  23989. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  23990. }
  23991. else if (this.value instanceof BABYLON.Quaternion) {
  23992. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  23993. }
  23994. else {
  23995. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  23996. return;
  23997. }
  23998. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  23999. animation.setKeys(keys);
  24000. if (this.stopOtherAnimations) {
  24001. scene.stopAnimation(this._target);
  24002. }
  24003. scene.beginDirectAnimation(this._target, [animation], 0, 100);
  24004. };
  24005. return InterpolateValueAction;
  24006. })(BABYLON.Action);
  24007. BABYLON.InterpolateValueAction = InterpolateValueAction;
  24008. })(BABYLON || (BABYLON = {}));
  24009. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  24010. var BABYLON;
  24011. (function (BABYLON) {
  24012. var SwitchBooleanAction = (function (_super) {
  24013. __extends(SwitchBooleanAction, _super);
  24014. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  24015. _super.call(this, triggerOptions, condition);
  24016. this.propertyPath = propertyPath;
  24017. this._target = target;
  24018. }
  24019. SwitchBooleanAction.prototype._prepare = function () {
  24020. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24021. this._property = this._getProperty(this.propertyPath);
  24022. };
  24023. SwitchBooleanAction.prototype.execute = function () {
  24024. this._target[this._property] = !this._target[this._property];
  24025. };
  24026. return SwitchBooleanAction;
  24027. })(BABYLON.Action);
  24028. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  24029. var SetStateAction = (function (_super) {
  24030. __extends(SetStateAction, _super);
  24031. function SetStateAction(triggerOptions, target, value, condition) {
  24032. _super.call(this, triggerOptions, condition);
  24033. this.value = value;
  24034. this._target = target;
  24035. }
  24036. SetStateAction.prototype.execute = function () {
  24037. this._target.state = this.value;
  24038. };
  24039. return SetStateAction;
  24040. })(BABYLON.Action);
  24041. BABYLON.SetStateAction = SetStateAction;
  24042. var SetValueAction = (function (_super) {
  24043. __extends(SetValueAction, _super);
  24044. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  24045. _super.call(this, triggerOptions, condition);
  24046. this.propertyPath = propertyPath;
  24047. this.value = value;
  24048. this._target = target;
  24049. }
  24050. SetValueAction.prototype._prepare = function () {
  24051. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24052. this._property = this._getProperty(this.propertyPath);
  24053. };
  24054. SetValueAction.prototype.execute = function () {
  24055. this._target[this._property] = this.value;
  24056. };
  24057. return SetValueAction;
  24058. })(BABYLON.Action);
  24059. BABYLON.SetValueAction = SetValueAction;
  24060. var IncrementValueAction = (function (_super) {
  24061. __extends(IncrementValueAction, _super);
  24062. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  24063. _super.call(this, triggerOptions, condition);
  24064. this.propertyPath = propertyPath;
  24065. this.value = value;
  24066. this._target = target;
  24067. }
  24068. IncrementValueAction.prototype._prepare = function () {
  24069. this._target = this._getEffectiveTarget(this._target, this.propertyPath);
  24070. this._property = this._getProperty(this.propertyPath);
  24071. if (typeof this._target[this._property] !== "number") {
  24072. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  24073. }
  24074. };
  24075. IncrementValueAction.prototype.execute = function () {
  24076. this._target[this._property] += this.value;
  24077. };
  24078. return IncrementValueAction;
  24079. })(BABYLON.Action);
  24080. BABYLON.IncrementValueAction = IncrementValueAction;
  24081. var PlayAnimationAction = (function (_super) {
  24082. __extends(PlayAnimationAction, _super);
  24083. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  24084. _super.call(this, triggerOptions, condition);
  24085. this.from = from;
  24086. this.to = to;
  24087. this.loop = loop;
  24088. this._target = target;
  24089. }
  24090. PlayAnimationAction.prototype._prepare = function () {
  24091. };
  24092. PlayAnimationAction.prototype.execute = function () {
  24093. var scene = this._actionManager.getScene();
  24094. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  24095. };
  24096. return PlayAnimationAction;
  24097. })(BABYLON.Action);
  24098. BABYLON.PlayAnimationAction = PlayAnimationAction;
  24099. var StopAnimationAction = (function (_super) {
  24100. __extends(StopAnimationAction, _super);
  24101. function StopAnimationAction(triggerOptions, target, condition) {
  24102. _super.call(this, triggerOptions, condition);
  24103. this._target = target;
  24104. }
  24105. StopAnimationAction.prototype._prepare = function () {
  24106. };
  24107. StopAnimationAction.prototype.execute = function () {
  24108. var scene = this._actionManager.getScene();
  24109. scene.stopAnimation(this._target);
  24110. };
  24111. return StopAnimationAction;
  24112. })(BABYLON.Action);
  24113. BABYLON.StopAnimationAction = StopAnimationAction;
  24114. var DoNothingAction = (function (_super) {
  24115. __extends(DoNothingAction, _super);
  24116. function DoNothingAction(triggerOptions, condition) {
  24117. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  24118. _super.call(this, triggerOptions, condition);
  24119. }
  24120. DoNothingAction.prototype.execute = function () {
  24121. };
  24122. return DoNothingAction;
  24123. })(BABYLON.Action);
  24124. BABYLON.DoNothingAction = DoNothingAction;
  24125. var CombineAction = (function (_super) {
  24126. __extends(CombineAction, _super);
  24127. function CombineAction(triggerOptions, children, condition) {
  24128. _super.call(this, triggerOptions, condition);
  24129. this.children = children;
  24130. }
  24131. CombineAction.prototype._prepare = function () {
  24132. for (var index = 0; index < this.children.length; index++) {
  24133. this.children[index]._actionManager = this._actionManager;
  24134. this.children[index]._prepare();
  24135. }
  24136. };
  24137. CombineAction.prototype.execute = function (evt) {
  24138. for (var index = 0; index < this.children.length; index++) {
  24139. this.children[index].execute(evt);
  24140. }
  24141. };
  24142. return CombineAction;
  24143. })(BABYLON.Action);
  24144. BABYLON.CombineAction = CombineAction;
  24145. var ExecuteCodeAction = (function (_super) {
  24146. __extends(ExecuteCodeAction, _super);
  24147. function ExecuteCodeAction(triggerOptions, func, condition) {
  24148. _super.call(this, triggerOptions, condition);
  24149. this.func = func;
  24150. }
  24151. ExecuteCodeAction.prototype.execute = function (evt) {
  24152. this.func(evt);
  24153. };
  24154. return ExecuteCodeAction;
  24155. })(BABYLON.Action);
  24156. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  24157. var SetParentAction = (function (_super) {
  24158. __extends(SetParentAction, _super);
  24159. function SetParentAction(triggerOptions, target, parent, condition) {
  24160. _super.call(this, triggerOptions, condition);
  24161. this._target = target;
  24162. this._parent = parent;
  24163. }
  24164. SetParentAction.prototype._prepare = function () {
  24165. };
  24166. SetParentAction.prototype.execute = function () {
  24167. if (this._target.parent === this._parent) {
  24168. return;
  24169. }
  24170. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  24171. invertParentWorldMatrix.invert();
  24172. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  24173. this._target.parent = this._parent;
  24174. };
  24175. return SetParentAction;
  24176. })(BABYLON.Action);
  24177. BABYLON.SetParentAction = SetParentAction;
  24178. var PlaySoundAction = (function (_super) {
  24179. __extends(PlaySoundAction, _super);
  24180. function PlaySoundAction(triggerOptions, sound, condition) {
  24181. _super.call(this, triggerOptions, condition);
  24182. this._sound = sound;
  24183. }
  24184. PlaySoundAction.prototype._prepare = function () {
  24185. };
  24186. PlaySoundAction.prototype.execute = function () {
  24187. if (this._sound !== undefined)
  24188. this._sound.play();
  24189. };
  24190. return PlaySoundAction;
  24191. })(BABYLON.Action);
  24192. BABYLON.PlaySoundAction = PlaySoundAction;
  24193. var StopSoundAction = (function (_super) {
  24194. __extends(StopSoundAction, _super);
  24195. function StopSoundAction(triggerOptions, sound, condition) {
  24196. _super.call(this, triggerOptions, condition);
  24197. this._sound = sound;
  24198. }
  24199. StopSoundAction.prototype._prepare = function () {
  24200. };
  24201. StopSoundAction.prototype.execute = function () {
  24202. if (this._sound !== undefined)
  24203. this._sound.stop();
  24204. };
  24205. return StopSoundAction;
  24206. })(BABYLON.Action);
  24207. BABYLON.StopSoundAction = StopSoundAction;
  24208. })(BABYLON || (BABYLON = {}));
  24209. //# sourceMappingURL=babylon.directActions.js.map
  24210. var BABYLON;
  24211. (function (BABYLON) {
  24212. var Geometry = (function () {
  24213. function Geometry(id, scene, vertexData, updatable, mesh) {
  24214. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24215. this._totalVertices = 0;
  24216. this._indices = [];
  24217. this.id = id;
  24218. this._engine = scene.getEngine();
  24219. this._meshes = [];
  24220. this._scene = scene;
  24221. // vertexData
  24222. if (vertexData) {
  24223. this.setAllVerticesData(vertexData, updatable);
  24224. }
  24225. else {
  24226. this._totalVertices = 0;
  24227. this._indices = [];
  24228. }
  24229. // applyToMesh
  24230. if (mesh) {
  24231. this.applyToMesh(mesh);
  24232. mesh.computeWorldMatrix(true);
  24233. }
  24234. }
  24235. Geometry.prototype.getScene = function () {
  24236. return this._scene;
  24237. };
  24238. Geometry.prototype.getEngine = function () {
  24239. return this._engine;
  24240. };
  24241. Geometry.prototype.isReady = function () {
  24242. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  24243. };
  24244. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  24245. vertexData.applyToGeometry(this, updatable);
  24246. };
  24247. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  24248. this._vertexBuffers = this._vertexBuffers || {};
  24249. if (this._vertexBuffers[kind]) {
  24250. this._vertexBuffers[kind].dispose();
  24251. }
  24252. this._vertexBuffers[kind] = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  24253. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24254. stride = this._vertexBuffers[kind].getStrideSize();
  24255. this._totalVertices = data.length / stride;
  24256. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24257. var meshes = this._meshes;
  24258. var numOfMeshes = meshes.length;
  24259. for (var index = 0; index < numOfMeshes; index++) {
  24260. var mesh = meshes[index];
  24261. mesh._resetPointsArrayCache();
  24262. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24263. mesh._createGlobalSubMesh();
  24264. mesh.computeWorldMatrix(true);
  24265. }
  24266. }
  24267. };
  24268. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  24269. var vertexBuffer = this.getVertexBuffer(kind);
  24270. if (!vertexBuffer) {
  24271. return;
  24272. }
  24273. vertexBuffer.updateDirectly(data, offset);
  24274. };
  24275. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  24276. var vertexBuffer = this.getVertexBuffer(kind);
  24277. if (!vertexBuffer) {
  24278. return;
  24279. }
  24280. vertexBuffer.update(data);
  24281. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24282. var extend;
  24283. var stride = vertexBuffer.getStrideSize();
  24284. this._totalVertices = data.length / stride;
  24285. if (updateExtends) {
  24286. extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices);
  24287. }
  24288. var meshes = this._meshes;
  24289. var numOfMeshes = meshes.length;
  24290. for (var index = 0; index < numOfMeshes; index++) {
  24291. var mesh = meshes[index];
  24292. mesh._resetPointsArrayCache();
  24293. if (updateExtends) {
  24294. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24295. }
  24296. }
  24297. }
  24298. };
  24299. Geometry.prototype.getTotalVertices = function () {
  24300. if (!this.isReady()) {
  24301. return 0;
  24302. }
  24303. return this._totalVertices;
  24304. };
  24305. Geometry.prototype.getVerticesData = function (kind) {
  24306. var vertexBuffer = this.getVertexBuffer(kind);
  24307. if (!vertexBuffer) {
  24308. return null;
  24309. }
  24310. return vertexBuffer.getData();
  24311. };
  24312. Geometry.prototype.getVertexBuffer = function (kind) {
  24313. if (!this.isReady()) {
  24314. return null;
  24315. }
  24316. return this._vertexBuffers[kind];
  24317. };
  24318. Geometry.prototype.getVertexBuffers = function () {
  24319. if (!this.isReady()) {
  24320. return null;
  24321. }
  24322. return this._vertexBuffers;
  24323. };
  24324. Geometry.prototype.isVerticesDataPresent = function (kind) {
  24325. if (!this._vertexBuffers) {
  24326. if (this._delayInfo) {
  24327. return this._delayInfo.indexOf(kind) !== -1;
  24328. }
  24329. return false;
  24330. }
  24331. return this._vertexBuffers[kind] !== undefined;
  24332. };
  24333. Geometry.prototype.getVerticesDataKinds = function () {
  24334. var result = [];
  24335. if (!this._vertexBuffers && this._delayInfo) {
  24336. for (var kind in this._delayInfo) {
  24337. result.push(kind);
  24338. }
  24339. }
  24340. else {
  24341. for (kind in this._vertexBuffers) {
  24342. result.push(kind);
  24343. }
  24344. }
  24345. return result;
  24346. };
  24347. Geometry.prototype.setIndices = function (indices, totalVertices) {
  24348. if (this._indexBuffer) {
  24349. this._engine._releaseBuffer(this._indexBuffer);
  24350. }
  24351. this._indices = indices;
  24352. if (this._meshes.length !== 0 && this._indices) {
  24353. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24354. }
  24355. if (totalVertices !== undefined) {
  24356. this._totalVertices = totalVertices;
  24357. }
  24358. var meshes = this._meshes;
  24359. var numOfMeshes = meshes.length;
  24360. for (var index = 0; index < numOfMeshes; index++) {
  24361. meshes[index]._createGlobalSubMesh();
  24362. }
  24363. };
  24364. Geometry.prototype.getTotalIndices = function () {
  24365. if (!this.isReady()) {
  24366. return 0;
  24367. }
  24368. return this._indices.length;
  24369. };
  24370. Geometry.prototype.getIndices = function () {
  24371. if (!this.isReady()) {
  24372. return null;
  24373. }
  24374. return this._indices;
  24375. };
  24376. Geometry.prototype.getIndexBuffer = function () {
  24377. if (!this.isReady()) {
  24378. return null;
  24379. }
  24380. return this._indexBuffer;
  24381. };
  24382. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  24383. var meshes = this._meshes;
  24384. var index = meshes.indexOf(mesh);
  24385. if (index === -1) {
  24386. return;
  24387. }
  24388. for (var kind in this._vertexBuffers) {
  24389. this._vertexBuffers[kind].dispose();
  24390. }
  24391. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  24392. this._indexBuffer = null;
  24393. }
  24394. meshes.splice(index, 1);
  24395. mesh._geometry = null;
  24396. if (meshes.length === 0 && shouldDispose) {
  24397. this.dispose();
  24398. }
  24399. };
  24400. Geometry.prototype.applyToMesh = function (mesh) {
  24401. if (mesh._geometry === this) {
  24402. return;
  24403. }
  24404. var previousGeometry = mesh._geometry;
  24405. if (previousGeometry) {
  24406. previousGeometry.releaseForMesh(mesh);
  24407. }
  24408. var meshes = this._meshes;
  24409. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  24410. mesh._geometry = this;
  24411. this._scene.pushGeometry(this);
  24412. meshes.push(mesh);
  24413. if (this.isReady()) {
  24414. this._applyToMesh(mesh);
  24415. }
  24416. else {
  24417. mesh._boundingInfo = this._boundingInfo;
  24418. }
  24419. };
  24420. Geometry.prototype._applyToMesh = function (mesh) {
  24421. var numOfMeshes = this._meshes.length;
  24422. for (var kind in this._vertexBuffers) {
  24423. if (numOfMeshes === 1) {
  24424. this._vertexBuffers[kind].create();
  24425. }
  24426. this._vertexBuffers[kind]._buffer.references = numOfMeshes;
  24427. if (kind === BABYLON.VertexBuffer.PositionKind) {
  24428. mesh._resetPointsArrayCache();
  24429. var extend = BABYLON.Tools.ExtractMinAndMax(this._vertexBuffers[kind].getData(), 0, this._totalVertices);
  24430. mesh._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24431. mesh._createGlobalSubMesh();
  24432. //bounding info was just created again, world matrix should be applied again.
  24433. mesh._updateBoundingInfo();
  24434. }
  24435. }
  24436. // indexBuffer
  24437. if (numOfMeshes === 1 && this._indices) {
  24438. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  24439. }
  24440. if (this._indexBuffer) {
  24441. this._indexBuffer.references = numOfMeshes;
  24442. }
  24443. };
  24444. Geometry.prototype.load = function (scene, onLoaded) {
  24445. var _this = this;
  24446. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  24447. return;
  24448. }
  24449. if (this.isReady()) {
  24450. if (onLoaded) {
  24451. onLoaded();
  24452. }
  24453. return;
  24454. }
  24455. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  24456. scene._addPendingData(this);
  24457. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  24458. _this._delayLoadingFunction(JSON.parse(data), _this);
  24459. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24460. _this._delayInfo = [];
  24461. scene._removePendingData(_this);
  24462. var meshes = _this._meshes;
  24463. var numOfMeshes = meshes.length;
  24464. for (var index = 0; index < numOfMeshes; index++) {
  24465. _this._applyToMesh(meshes[index]);
  24466. }
  24467. if (onLoaded) {
  24468. onLoaded();
  24469. }
  24470. }, function () {
  24471. }, scene.database);
  24472. };
  24473. Geometry.prototype.dispose = function () {
  24474. var meshes = this._meshes;
  24475. var numOfMeshes = meshes.length;
  24476. var index;
  24477. for (index = 0; index < numOfMeshes; index++) {
  24478. this.releaseForMesh(meshes[index]);
  24479. }
  24480. this._meshes = [];
  24481. for (var kind in this._vertexBuffers) {
  24482. this._vertexBuffers[kind].dispose();
  24483. }
  24484. this._vertexBuffers = [];
  24485. this._totalVertices = 0;
  24486. if (this._indexBuffer) {
  24487. this._engine._releaseBuffer(this._indexBuffer);
  24488. }
  24489. this._indexBuffer = null;
  24490. this._indices = [];
  24491. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24492. this.delayLoadingFile = null;
  24493. this._delayLoadingFunction = null;
  24494. this._delayInfo = [];
  24495. this._boundingInfo = null; // todo: .dispose()
  24496. var geometries = this._scene.getGeometries();
  24497. index = geometries.indexOf(this);
  24498. if (index > -1) {
  24499. geometries.splice(index, 1);
  24500. }
  24501. };
  24502. Geometry.prototype.copy = function (id) {
  24503. var vertexData = new BABYLON.VertexData();
  24504. vertexData.indices = [];
  24505. var indices = this.getIndices();
  24506. for (var index = 0; index < indices.length; index++) {
  24507. vertexData.indices.push(indices[index]);
  24508. }
  24509. var updatable = false;
  24510. var stopChecking = false;
  24511. for (var kind in this._vertexBuffers) {
  24512. vertexData.set(this.getVerticesData(kind), kind);
  24513. if (!stopChecking) {
  24514. updatable = this.getVertexBuffer(kind).isUpdatable();
  24515. stopChecking = !updatable;
  24516. }
  24517. }
  24518. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  24519. geometry.delayLoadState = this.delayLoadState;
  24520. geometry.delayLoadingFile = this.delayLoadingFile;
  24521. geometry._delayLoadingFunction = this._delayLoadingFunction;
  24522. for (kind in this._delayInfo) {
  24523. geometry._delayInfo = geometry._delayInfo || [];
  24524. geometry._delayInfo.push(kind);
  24525. }
  24526. // Bounding info
  24527. var extend = BABYLON.Tools.ExtractMinAndMax(this.getVerticesData(BABYLON.VertexBuffer.PositionKind), 0, this.getTotalVertices());
  24528. geometry._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  24529. return geometry;
  24530. };
  24531. // Statics
  24532. Geometry.ExtractFromMesh = function (mesh, id) {
  24533. var geometry = mesh._geometry;
  24534. if (!geometry) {
  24535. return null;
  24536. }
  24537. return geometry.copy(id);
  24538. };
  24539. // from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  24540. // be aware Math.random() could cause collisions
  24541. Geometry.RandomId = function () {
  24542. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  24543. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  24544. return v.toString(16);
  24545. });
  24546. };
  24547. return Geometry;
  24548. })();
  24549. BABYLON.Geometry = Geometry;
  24550. /////// Primitives //////////////////////////////////////////////
  24551. var Geometry;
  24552. (function (Geometry) {
  24553. var Primitives;
  24554. (function (Primitives) {
  24555. /// Abstract class
  24556. var _Primitive = (function (_super) {
  24557. __extends(_Primitive, _super);
  24558. function _Primitive(id, scene, vertexData, canBeRegenerated, mesh) {
  24559. this._beingRegenerated = true;
  24560. this._canBeRegenerated = canBeRegenerated;
  24561. _super.call(this, id, scene, vertexData, false, mesh); // updatable = false to be sure not to update vertices
  24562. this._beingRegenerated = false;
  24563. }
  24564. _Primitive.prototype.canBeRegenerated = function () {
  24565. return this._canBeRegenerated;
  24566. };
  24567. _Primitive.prototype.regenerate = function () {
  24568. if (!this._canBeRegenerated) {
  24569. return;
  24570. }
  24571. this._beingRegenerated = true;
  24572. this.setAllVerticesData(this._regenerateVertexData(), false);
  24573. this._beingRegenerated = false;
  24574. };
  24575. _Primitive.prototype.asNewGeometry = function (id) {
  24576. return _super.prototype.copy.call(this, id);
  24577. };
  24578. // overrides
  24579. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  24580. if (!this._beingRegenerated) {
  24581. return;
  24582. }
  24583. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  24584. };
  24585. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  24586. if (!this._beingRegenerated) {
  24587. return;
  24588. }
  24589. _super.prototype.setVerticesData.call(this, kind, data, false);
  24590. };
  24591. // to override
  24592. // protected
  24593. _Primitive.prototype._regenerateVertexData = function () {
  24594. throw new Error("Abstract method");
  24595. };
  24596. _Primitive.prototype.copy = function (id) {
  24597. throw new Error("Must be overriden in sub-classes.");
  24598. };
  24599. return _Primitive;
  24600. })(Geometry);
  24601. Primitives._Primitive = _Primitive;
  24602. var Ribbon = (function (_super) {
  24603. __extends(Ribbon, _super);
  24604. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  24605. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24606. this.pathArray = pathArray;
  24607. this.closeArray = closeArray;
  24608. this.closePath = closePath;
  24609. this.offset = offset;
  24610. this.side = side;
  24611. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24612. }
  24613. Ribbon.prototype._regenerateVertexData = function () {
  24614. return BABYLON.VertexData.CreateRibbon(this.pathArray, this.closeArray, this.closePath, this.offset, this.side);
  24615. };
  24616. Ribbon.prototype.copy = function (id) {
  24617. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  24618. };
  24619. return Ribbon;
  24620. })(_Primitive);
  24621. Primitives.Ribbon = Ribbon;
  24622. var Box = (function (_super) {
  24623. __extends(Box, _super);
  24624. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  24625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24626. this.size = size;
  24627. this.side = side;
  24628. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24629. }
  24630. Box.prototype._regenerateVertexData = function () {
  24631. return BABYLON.VertexData.CreateBox(this.size, this.side);
  24632. };
  24633. Box.prototype.copy = function (id) {
  24634. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24635. };
  24636. return Box;
  24637. })(_Primitive);
  24638. Primitives.Box = Box;
  24639. var Sphere = (function (_super) {
  24640. __extends(Sphere, _super);
  24641. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  24642. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24643. this.segments = segments;
  24644. this.diameter = diameter;
  24645. this.side = side;
  24646. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24647. }
  24648. Sphere.prototype._regenerateVertexData = function () {
  24649. return BABYLON.VertexData.CreateSphere(this.segments, this.diameter, this.side);
  24650. };
  24651. Sphere.prototype.copy = function (id) {
  24652. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  24653. };
  24654. return Sphere;
  24655. })(_Primitive);
  24656. Primitives.Sphere = Sphere;
  24657. var Cylinder = (function (_super) {
  24658. __extends(Cylinder, _super);
  24659. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  24660. if (subdivisions === void 0) { subdivisions = 1; }
  24661. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24662. this.height = height;
  24663. this.diameterTop = diameterTop;
  24664. this.diameterBottom = diameterBottom;
  24665. this.tessellation = tessellation;
  24666. this.subdivisions = subdivisions;
  24667. this.side = side;
  24668. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24669. }
  24670. Cylinder.prototype._regenerateVertexData = function () {
  24671. return BABYLON.VertexData.CreateCylinder(this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.side);
  24672. };
  24673. Cylinder.prototype.copy = function (id) {
  24674. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  24675. };
  24676. return Cylinder;
  24677. })(_Primitive);
  24678. Primitives.Cylinder = Cylinder;
  24679. var Torus = (function (_super) {
  24680. __extends(Torus, _super);
  24681. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  24682. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24683. this.diameter = diameter;
  24684. this.thickness = thickness;
  24685. this.tessellation = tessellation;
  24686. this.side = side;
  24687. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24688. }
  24689. Torus.prototype._regenerateVertexData = function () {
  24690. return BABYLON.VertexData.CreateTorus(this.diameter, this.thickness, this.tessellation, this.side);
  24691. };
  24692. Torus.prototype.copy = function (id) {
  24693. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  24694. };
  24695. return Torus;
  24696. })(_Primitive);
  24697. Primitives.Torus = Torus;
  24698. var Ground = (function (_super) {
  24699. __extends(Ground, _super);
  24700. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  24701. this.width = width;
  24702. this.height = height;
  24703. this.subdivisions = subdivisions;
  24704. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24705. }
  24706. Ground.prototype._regenerateVertexData = function () {
  24707. return BABYLON.VertexData.CreateGround(this.width, this.height, this.subdivisions);
  24708. };
  24709. Ground.prototype.copy = function (id) {
  24710. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  24711. };
  24712. return Ground;
  24713. })(_Primitive);
  24714. Primitives.Ground = Ground;
  24715. var TiledGround = (function (_super) {
  24716. __extends(TiledGround, _super);
  24717. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  24718. this.xmin = xmin;
  24719. this.zmin = zmin;
  24720. this.xmax = xmax;
  24721. this.zmax = zmax;
  24722. this.subdivisions = subdivisions;
  24723. this.precision = precision;
  24724. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24725. }
  24726. TiledGround.prototype._regenerateVertexData = function () {
  24727. return BABYLON.VertexData.CreateTiledGround(this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision);
  24728. };
  24729. TiledGround.prototype.copy = function (id) {
  24730. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  24731. };
  24732. return TiledGround;
  24733. })(_Primitive);
  24734. Primitives.TiledGround = TiledGround;
  24735. var Plane = (function (_super) {
  24736. __extends(Plane, _super);
  24737. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  24738. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24739. this.size = size;
  24740. this.side = side;
  24741. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24742. }
  24743. Plane.prototype._regenerateVertexData = function () {
  24744. return BABYLON.VertexData.CreatePlane(this.size, this.side);
  24745. };
  24746. Plane.prototype.copy = function (id) {
  24747. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  24748. };
  24749. return Plane;
  24750. })(_Primitive);
  24751. Primitives.Plane = Plane;
  24752. var TorusKnot = (function (_super) {
  24753. __extends(TorusKnot, _super);
  24754. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  24755. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  24756. this.radius = radius;
  24757. this.tube = tube;
  24758. this.radialSegments = radialSegments;
  24759. this.tubularSegments = tubularSegments;
  24760. this.p = p;
  24761. this.q = q;
  24762. this.side = side;
  24763. _super.call(this, id, scene, this._regenerateVertexData(), canBeRegenerated, mesh);
  24764. }
  24765. TorusKnot.prototype._regenerateVertexData = function () {
  24766. return BABYLON.VertexData.CreateTorusKnot(this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.side);
  24767. };
  24768. TorusKnot.prototype.copy = function (id) {
  24769. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  24770. };
  24771. return TorusKnot;
  24772. })(_Primitive);
  24773. Primitives.TorusKnot = TorusKnot;
  24774. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  24775. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  24776. })(BABYLON || (BABYLON = {}));
  24777. //# sourceMappingURL=babylon.geometry.js.map
  24778. var BABYLON;
  24779. (function (BABYLON) {
  24780. var Gamepads = (function () {
  24781. function Gamepads(ongamedpadconnected) {
  24782. var _this = this;
  24783. this.babylonGamepads = [];
  24784. this.oneGamepadConnected = false;
  24785. this.isMonitoring = false;
  24786. this.gamepadEventSupported = 'GamepadEvent' in window;
  24787. this.gamepadSupportAvailable = (navigator.getGamepads || !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  24788. 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=";
  24789. this._callbackGamepadConnected = ongamedpadconnected;
  24790. if (this.gamepadSupportAvailable) {
  24791. // Checking if the gamepad connected event is supported (like in Firefox)
  24792. if (this.gamepadEventSupported) {
  24793. window.addEventListener('gamepadconnected', function (evt) {
  24794. _this._onGamepadConnected(evt);
  24795. }, false);
  24796. window.addEventListener('gamepaddisconnected', function (evt) {
  24797. _this._onGamepadDisconnected(evt);
  24798. }, false);
  24799. }
  24800. else {
  24801. this._startMonitoringGamepads();
  24802. }
  24803. if (!this.oneGamepadConnected) {
  24804. this._insertGamepadDOMInstructions();
  24805. }
  24806. }
  24807. else {
  24808. this._insertGamepadDOMNotSupported();
  24809. }
  24810. }
  24811. Gamepads.prototype._insertGamepadDOMInstructions = function () {
  24812. Gamepads.gamepadDOMInfo = document.createElement("div");
  24813. var buttonAImage = document.createElement("img");
  24814. buttonAImage.src = this.buttonADataURL;
  24815. var spanMessage = document.createElement("span");
  24816. spanMessage.innerHTML = "<strong>to activate gamepad</strong>";
  24817. Gamepads.gamepadDOMInfo.appendChild(buttonAImage);
  24818. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24819. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24820. Gamepads.gamepadDOMInfo.style.width = "100%";
  24821. Gamepads.gamepadDOMInfo.style.height = "48px";
  24822. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24823. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24824. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24825. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24826. buttonAImage.style.position = "relative";
  24827. buttonAImage.style.bottom = "8px";
  24828. spanMessage.style.position = "relative";
  24829. spanMessage.style.fontSize = "32px";
  24830. spanMessage.style.bottom = "32px";
  24831. spanMessage.style.color = "green";
  24832. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24833. };
  24834. Gamepads.prototype._insertGamepadDOMNotSupported = function () {
  24835. Gamepads.gamepadDOMInfo = document.createElement("div");
  24836. var spanMessage = document.createElement("span");
  24837. spanMessage.innerHTML = "<strong>gamepad not supported</strong>";
  24838. Gamepads.gamepadDOMInfo.appendChild(spanMessage);
  24839. Gamepads.gamepadDOMInfo.style.position = "absolute";
  24840. Gamepads.gamepadDOMInfo.style.width = "100%";
  24841. Gamepads.gamepadDOMInfo.style.height = "40px";
  24842. Gamepads.gamepadDOMInfo.style.bottom = "0px";
  24843. Gamepads.gamepadDOMInfo.style.backgroundColor = "rgba(1, 1, 1, 0.15)";
  24844. Gamepads.gamepadDOMInfo.style.textAlign = "center";
  24845. Gamepads.gamepadDOMInfo.style.zIndex = "10";
  24846. spanMessage.style.position = "relative";
  24847. spanMessage.style.fontSize = "32px";
  24848. spanMessage.style.color = "red";
  24849. document.body.appendChild(Gamepads.gamepadDOMInfo);
  24850. };
  24851. Gamepads.prototype.dispose = function () {
  24852. if (Gamepads.gamepadDOMInfo) {
  24853. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24854. }
  24855. };
  24856. Gamepads.prototype._onGamepadConnected = function (evt) {
  24857. var newGamepad = this._addNewGamepad(evt.gamepad);
  24858. if (this._callbackGamepadConnected)
  24859. this._callbackGamepadConnected(newGamepad);
  24860. this._startMonitoringGamepads();
  24861. };
  24862. Gamepads.prototype._addNewGamepad = function (gamepad) {
  24863. if (!this.oneGamepadConnected) {
  24864. this.oneGamepadConnected = true;
  24865. if (Gamepads.gamepadDOMInfo) {
  24866. document.body.removeChild(Gamepads.gamepadDOMInfo);
  24867. Gamepads.gamepadDOMInfo = null;
  24868. }
  24869. }
  24870. var newGamepad;
  24871. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  24872. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  24873. }
  24874. else {
  24875. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  24876. }
  24877. this.babylonGamepads.push(newGamepad);
  24878. return newGamepad;
  24879. };
  24880. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  24881. for (var i in this.babylonGamepads) {
  24882. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  24883. this.babylonGamepads.splice(i, 1);
  24884. break;
  24885. }
  24886. }
  24887. // If no gamepads are left, stop the polling loop.
  24888. if (this.babylonGamepads.length == 0) {
  24889. this._stopMonitoringGamepads();
  24890. }
  24891. };
  24892. Gamepads.prototype._startMonitoringGamepads = function () {
  24893. if (!this.isMonitoring) {
  24894. this.isMonitoring = true;
  24895. this._checkGamepadsStatus();
  24896. }
  24897. };
  24898. Gamepads.prototype._stopMonitoringGamepads = function () {
  24899. this.isMonitoring = false;
  24900. };
  24901. Gamepads.prototype._checkGamepadsStatus = function () {
  24902. var _this = this;
  24903. // updating gamepad objects
  24904. this._updateGamepadObjects();
  24905. for (var i in this.babylonGamepads) {
  24906. this.babylonGamepads[i].update();
  24907. }
  24908. if (this.isMonitoring) {
  24909. if (window.requestAnimationFrame) {
  24910. window.requestAnimationFrame(function () {
  24911. _this._checkGamepadsStatus();
  24912. });
  24913. }
  24914. else if (window.mozRequestAnimationFrame) {
  24915. window.mozRequestAnimationFrame(function () {
  24916. _this._checkGamepadsStatus();
  24917. });
  24918. }
  24919. else if (window.webkitRequestAnimationFrame) {
  24920. window.webkitRequestAnimationFrame(function () {
  24921. _this._checkGamepadsStatus();
  24922. });
  24923. }
  24924. }
  24925. };
  24926. // This function is called only on Chrome, which does not yet support
  24927. // connection/disconnection events, but requires you to monitor
  24928. // an array for changes.
  24929. Gamepads.prototype._updateGamepadObjects = function () {
  24930. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  24931. for (var i = 0; i < gamepads.length; i++) {
  24932. if (gamepads[i]) {
  24933. if (!(gamepads[i].index in this.babylonGamepads)) {
  24934. var newGamepad = this._addNewGamepad(gamepads[i]);
  24935. if (this._callbackGamepadConnected) {
  24936. this._callbackGamepadConnected(newGamepad);
  24937. }
  24938. }
  24939. else {
  24940. this.babylonGamepads[i].browserGamepad = gamepads[i];
  24941. }
  24942. }
  24943. }
  24944. };
  24945. return Gamepads;
  24946. })();
  24947. BABYLON.Gamepads = Gamepads;
  24948. var StickValues = (function () {
  24949. function StickValues(x, y) {
  24950. this.x = x;
  24951. this.y = y;
  24952. }
  24953. return StickValues;
  24954. })();
  24955. BABYLON.StickValues = StickValues;
  24956. var Gamepad = (function () {
  24957. function Gamepad(id, index, browserGamepad) {
  24958. this.id = id;
  24959. this.index = index;
  24960. this.browserGamepad = browserGamepad;
  24961. if (this.browserGamepad.axes.length >= 2) {
  24962. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  24963. }
  24964. if (this.browserGamepad.axes.length >= 4) {
  24965. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  24966. }
  24967. }
  24968. Gamepad.prototype.onleftstickchanged = function (callback) {
  24969. this._onleftstickchanged = callback;
  24970. };
  24971. Gamepad.prototype.onrightstickchanged = function (callback) {
  24972. this._onrightstickchanged = callback;
  24973. };
  24974. Object.defineProperty(Gamepad.prototype, "leftStick", {
  24975. get: function () {
  24976. return this._leftStick;
  24977. },
  24978. set: function (newValues) {
  24979. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  24980. this._onleftstickchanged(newValues);
  24981. }
  24982. this._leftStick = newValues;
  24983. },
  24984. enumerable: true,
  24985. configurable: true
  24986. });
  24987. Object.defineProperty(Gamepad.prototype, "rightStick", {
  24988. get: function () {
  24989. return this._rightStick;
  24990. },
  24991. set: function (newValues) {
  24992. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  24993. this._onrightstickchanged(newValues);
  24994. }
  24995. this._rightStick = newValues;
  24996. },
  24997. enumerable: true,
  24998. configurable: true
  24999. });
  25000. Gamepad.prototype.update = function () {
  25001. if (this._leftStick) {
  25002. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  25003. }
  25004. if (this._rightStick) {
  25005. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  25006. }
  25007. };
  25008. return Gamepad;
  25009. })();
  25010. BABYLON.Gamepad = Gamepad;
  25011. var GenericPad = (function (_super) {
  25012. __extends(GenericPad, _super);
  25013. function GenericPad(id, index, gamepad) {
  25014. _super.call(this, id, index, gamepad);
  25015. this.id = id;
  25016. this.index = index;
  25017. this.gamepad = gamepad;
  25018. this._buttons = new Array(gamepad.buttons.length);
  25019. }
  25020. GenericPad.prototype.onbuttondown = function (callback) {
  25021. this._onbuttondown = callback;
  25022. };
  25023. GenericPad.prototype.onbuttonup = function (callback) {
  25024. this._onbuttonup = callback;
  25025. };
  25026. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  25027. if (newValue !== currentValue) {
  25028. if (this._onbuttondown && newValue === 1) {
  25029. this._onbuttondown(buttonIndex);
  25030. }
  25031. if (this._onbuttonup && newValue === 0) {
  25032. this._onbuttonup(buttonIndex);
  25033. }
  25034. }
  25035. return newValue;
  25036. };
  25037. GenericPad.prototype.update = function () {
  25038. _super.prototype.update.call(this);
  25039. for (var index = 0; index < this._buttons.length; index++) {
  25040. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  25041. }
  25042. };
  25043. return GenericPad;
  25044. })(Gamepad);
  25045. BABYLON.GenericPad = GenericPad;
  25046. (function (Xbox360Button) {
  25047. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  25048. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  25049. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  25050. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  25051. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  25052. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  25053. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  25054. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  25055. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  25056. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  25057. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  25058. var Xbox360Button = BABYLON.Xbox360Button;
  25059. (function (Xbox360Dpad) {
  25060. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  25061. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  25062. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  25063. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  25064. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  25065. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  25066. var Xbox360Pad = (function (_super) {
  25067. __extends(Xbox360Pad, _super);
  25068. function Xbox360Pad() {
  25069. _super.apply(this, arguments);
  25070. this._leftTrigger = 0;
  25071. this._rightTrigger = 0;
  25072. this._buttonA = 0;
  25073. this._buttonB = 0;
  25074. this._buttonX = 0;
  25075. this._buttonY = 0;
  25076. this._buttonBack = 0;
  25077. this._buttonStart = 0;
  25078. this._buttonLB = 0;
  25079. this._buttonRB = 0;
  25080. this._buttonLeftStick = 0;
  25081. this._buttonRightStick = 0;
  25082. this._dPadUp = 0;
  25083. this._dPadDown = 0;
  25084. this._dPadLeft = 0;
  25085. this._dPadRight = 0;
  25086. }
  25087. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  25088. this._onlefttriggerchanged = callback;
  25089. };
  25090. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  25091. this._onrighttriggerchanged = callback;
  25092. };
  25093. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  25094. get: function () {
  25095. return this._leftTrigger;
  25096. },
  25097. set: function (newValue) {
  25098. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  25099. this._onlefttriggerchanged(newValue);
  25100. }
  25101. this._leftTrigger = newValue;
  25102. },
  25103. enumerable: true,
  25104. configurable: true
  25105. });
  25106. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  25107. get: function () {
  25108. return this._rightTrigger;
  25109. },
  25110. set: function (newValue) {
  25111. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  25112. this._onrighttriggerchanged(newValue);
  25113. }
  25114. this._rightTrigger = newValue;
  25115. },
  25116. enumerable: true,
  25117. configurable: true
  25118. });
  25119. Xbox360Pad.prototype.onbuttondown = function (callback) {
  25120. this._onbuttondown = callback;
  25121. };
  25122. Xbox360Pad.prototype.onbuttonup = function (callback) {
  25123. this._onbuttonup = callback;
  25124. };
  25125. Xbox360Pad.prototype.ondpaddown = function (callback) {
  25126. this._ondpaddown = callback;
  25127. };
  25128. Xbox360Pad.prototype.ondpadup = function (callback) {
  25129. this._ondpadup = callback;
  25130. };
  25131. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  25132. if (newValue !== currentValue) {
  25133. if (this._onbuttondown && newValue === 1) {
  25134. this._onbuttondown(buttonType);
  25135. }
  25136. if (this._onbuttonup && newValue === 0) {
  25137. this._onbuttonup(buttonType);
  25138. }
  25139. }
  25140. return newValue;
  25141. };
  25142. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  25143. if (newValue !== currentValue) {
  25144. if (this._ondpaddown && newValue === 1) {
  25145. this._ondpaddown(buttonType);
  25146. }
  25147. if (this._ondpadup && newValue === 0) {
  25148. this._ondpadup(buttonType);
  25149. }
  25150. }
  25151. return newValue;
  25152. };
  25153. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  25154. get: function () {
  25155. return this._buttonA;
  25156. },
  25157. set: function (value) {
  25158. this._buttonA = this._setButtonValue(value, this._buttonA, 0 /* A */);
  25159. },
  25160. enumerable: true,
  25161. configurable: true
  25162. });
  25163. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  25164. get: function () {
  25165. return this._buttonB;
  25166. },
  25167. set: function (value) {
  25168. this._buttonB = this._setButtonValue(value, this._buttonB, 1 /* B */);
  25169. },
  25170. enumerable: true,
  25171. configurable: true
  25172. });
  25173. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  25174. get: function () {
  25175. return this._buttonX;
  25176. },
  25177. set: function (value) {
  25178. this._buttonX = this._setButtonValue(value, this._buttonX, 2 /* X */);
  25179. },
  25180. enumerable: true,
  25181. configurable: true
  25182. });
  25183. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  25184. get: function () {
  25185. return this._buttonY;
  25186. },
  25187. set: function (value) {
  25188. this._buttonY = this._setButtonValue(value, this._buttonY, 3 /* Y */);
  25189. },
  25190. enumerable: true,
  25191. configurable: true
  25192. });
  25193. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  25194. get: function () {
  25195. return this._buttonStart;
  25196. },
  25197. set: function (value) {
  25198. this._buttonStart = this._setButtonValue(value, this._buttonStart, 4 /* Start */);
  25199. },
  25200. enumerable: true,
  25201. configurable: true
  25202. });
  25203. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  25204. get: function () {
  25205. return this._buttonBack;
  25206. },
  25207. set: function (value) {
  25208. this._buttonBack = this._setButtonValue(value, this._buttonBack, 5 /* Back */);
  25209. },
  25210. enumerable: true,
  25211. configurable: true
  25212. });
  25213. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  25214. get: function () {
  25215. return this._buttonLB;
  25216. },
  25217. set: function (value) {
  25218. this._buttonLB = this._setButtonValue(value, this._buttonLB, 6 /* LB */);
  25219. },
  25220. enumerable: true,
  25221. configurable: true
  25222. });
  25223. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  25224. get: function () {
  25225. return this._buttonRB;
  25226. },
  25227. set: function (value) {
  25228. this._buttonRB = this._setButtonValue(value, this._buttonRB, 7 /* RB */);
  25229. },
  25230. enumerable: true,
  25231. configurable: true
  25232. });
  25233. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  25234. get: function () {
  25235. return this._buttonLeftStick;
  25236. },
  25237. set: function (value) {
  25238. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, 8 /* LeftStick */);
  25239. },
  25240. enumerable: true,
  25241. configurable: true
  25242. });
  25243. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  25244. get: function () {
  25245. return this._buttonRightStick;
  25246. },
  25247. set: function (value) {
  25248. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, 9 /* RightStick */);
  25249. },
  25250. enumerable: true,
  25251. configurable: true
  25252. });
  25253. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  25254. get: function () {
  25255. return this._dPadUp;
  25256. },
  25257. set: function (value) {
  25258. this._dPadUp = this._setDPadValue(value, this._dPadUp, 0 /* Up */);
  25259. },
  25260. enumerable: true,
  25261. configurable: true
  25262. });
  25263. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  25264. get: function () {
  25265. return this._dPadDown;
  25266. },
  25267. set: function (value) {
  25268. this._dPadDown = this._setDPadValue(value, this._dPadDown, 1 /* Down */);
  25269. },
  25270. enumerable: true,
  25271. configurable: true
  25272. });
  25273. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  25274. get: function () {
  25275. return this._dPadLeft;
  25276. },
  25277. set: function (value) {
  25278. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, 2 /* Left */);
  25279. },
  25280. enumerable: true,
  25281. configurable: true
  25282. });
  25283. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  25284. get: function () {
  25285. return this._dPadRight;
  25286. },
  25287. set: function (value) {
  25288. this._dPadRight = this._setDPadValue(value, this._dPadRight, 3 /* Right */);
  25289. },
  25290. enumerable: true,
  25291. configurable: true
  25292. });
  25293. Xbox360Pad.prototype.update = function () {
  25294. _super.prototype.update.call(this);
  25295. this.buttonA = this.browserGamepad.buttons[0].value;
  25296. this.buttonB = this.browserGamepad.buttons[1].value;
  25297. this.buttonX = this.browserGamepad.buttons[2].value;
  25298. this.buttonY = this.browserGamepad.buttons[3].value;
  25299. this.buttonLB = this.browserGamepad.buttons[4].value;
  25300. this.buttonRB = this.browserGamepad.buttons[5].value;
  25301. this.leftTrigger = this.browserGamepad.buttons[6].value;
  25302. this.rightTrigger = this.browserGamepad.buttons[7].value;
  25303. this.buttonBack = this.browserGamepad.buttons[8].value;
  25304. this.buttonStart = this.browserGamepad.buttons[9].value;
  25305. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  25306. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  25307. this.dPadUp = this.browserGamepad.buttons[12].value;
  25308. this.dPadDown = this.browserGamepad.buttons[13].value;
  25309. this.dPadLeft = this.browserGamepad.buttons[14].value;
  25310. this.dPadRight = this.browserGamepad.buttons[15].value;
  25311. };
  25312. return Xbox360Pad;
  25313. })(Gamepad);
  25314. BABYLON.Xbox360Pad = Xbox360Pad;
  25315. })(BABYLON || (BABYLON = {}));
  25316. //# sourceMappingURL=babylon.gamepads.js.map
  25317. var BABYLON;
  25318. (function (BABYLON) {
  25319. // We're mainly based on the logic defined into the FreeCamera code
  25320. var GamepadCamera = (function (_super) {
  25321. __extends(GamepadCamera, _super);
  25322. function GamepadCamera(name, position, scene) {
  25323. var _this = this;
  25324. _super.call(this, name, position, scene);
  25325. this.angularSensibility = 200;
  25326. this.moveSensibility = 75;
  25327. this._gamepads = new BABYLON.Gamepads(function (gamepad) {
  25328. _this._onNewGameConnected(gamepad);
  25329. });
  25330. }
  25331. GamepadCamera.prototype._onNewGameConnected = function (gamepad) {
  25332. // Only the first gamepad can control the camera
  25333. if (gamepad.index === 0) {
  25334. this._gamepad = gamepad;
  25335. }
  25336. };
  25337. GamepadCamera.prototype._checkInputs = function () {
  25338. if (!this._gamepad) {
  25339. return;
  25340. }
  25341. var LSValues = this._gamepad.leftStick;
  25342. var normalizedLX = LSValues.x / this.moveSensibility;
  25343. var normalizedLY = LSValues.y / this.moveSensibility;
  25344. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  25345. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  25346. var RSValues = this._gamepad.rightStick;
  25347. var normalizedRX = RSValues.x / this.angularSensibility;
  25348. var normalizedRY = RSValues.y / this.angularSensibility;
  25349. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  25350. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  25351. ;
  25352. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(this.rotation.y, this.rotation.x, 0);
  25353. var speed = this._computeLocalCameraSpeed() * 50.0;
  25354. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  25355. this.cameraDirection = this.cameraDirection.add(deltaTransform);
  25356. this.cameraRotation = this.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  25357. };
  25358. GamepadCamera.prototype.dispose = function () {
  25359. this._gamepads.dispose();
  25360. _super.prototype.dispose.call(this);
  25361. };
  25362. return GamepadCamera;
  25363. })(BABYLON.FreeCamera);
  25364. BABYLON.GamepadCamera = GamepadCamera;
  25365. })(BABYLON || (BABYLON = {}));
  25366. //# sourceMappingURL=babylon.gamepadCamera.js.map
  25367. var BABYLON;
  25368. (function (BABYLON) {
  25369. var LinesMesh = (function (_super) {
  25370. __extends(LinesMesh, _super);
  25371. function LinesMesh(name, scene, updatable) {
  25372. if (updatable === void 0) { updatable = false; }
  25373. _super.call(this, name, scene);
  25374. this.color = new BABYLON.Color3(1, 1, 1);
  25375. this.alpha = 1;
  25376. this._indices = new Array();
  25377. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  25378. attributes: ["position"],
  25379. uniforms: ["worldViewProjection", "color"],
  25380. needAlphaBlending: true
  25381. });
  25382. }
  25383. Object.defineProperty(LinesMesh.prototype, "material", {
  25384. get: function () {
  25385. return this._colorShader;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. Object.defineProperty(LinesMesh.prototype, "isPickable", {
  25391. get: function () {
  25392. return false;
  25393. },
  25394. enumerable: true,
  25395. configurable: true
  25396. });
  25397. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  25398. get: function () {
  25399. return false;
  25400. },
  25401. enumerable: true,
  25402. configurable: true
  25403. });
  25404. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  25405. var engine = this.getScene().getEngine();
  25406. var indexToBind = this._geometry.getIndexBuffer();
  25407. // VBOs
  25408. engine.bindBuffers(this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).getBuffer(), indexToBind, [3], 3 * 4, this._colorShader.getEffect());
  25409. // Color
  25410. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  25411. };
  25412. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  25413. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  25414. return;
  25415. }
  25416. var engine = this.getScene().getEngine();
  25417. // Draw order
  25418. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  25419. };
  25420. LinesMesh.prototype.intersects = function (ray, fastCheck) {
  25421. return null;
  25422. };
  25423. LinesMesh.prototype.dispose = function (doNotRecurse) {
  25424. this._colorShader.dispose();
  25425. _super.prototype.dispose.call(this, doNotRecurse);
  25426. };
  25427. return LinesMesh;
  25428. })(BABYLON.Mesh);
  25429. BABYLON.LinesMesh = LinesMesh;
  25430. })(BABYLON || (BABYLON = {}));
  25431. //# sourceMappingURL=babylon.linesMesh.js.mapvar BABYLON;
  25432. (function (BABYLON) {
  25433. var OutlineRenderer = (function () {
  25434. function OutlineRenderer(scene) {
  25435. this._scene = scene;
  25436. }
  25437. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  25438. var _this = this;
  25439. if (useOverlay === void 0) { useOverlay = false; }
  25440. var scene = this._scene;
  25441. var engine = this._scene.getEngine();
  25442. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  25443. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  25444. return;
  25445. }
  25446. var mesh = subMesh.getRenderingMesh();
  25447. var material = subMesh.getMaterial();
  25448. engine.enableEffect(this._effect);
  25449. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  25450. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  25451. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  25452. // Bones
  25453. if (mesh.useBones) {
  25454. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  25455. }
  25456. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  25457. // Alpha test
  25458. if (material && material.needAlphaTesting()) {
  25459. var alphaTexture = material.getAlphaTestTexture();
  25460. this._effect.setTexture("diffuseSampler", alphaTexture);
  25461. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  25462. }
  25463. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) {
  25464. _this._effect.setMatrix("world", world);
  25465. });
  25466. };
  25467. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  25468. var defines = [];
  25469. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  25470. var mesh = subMesh.getMesh();
  25471. var material = subMesh.getMaterial();
  25472. // Alpha test
  25473. if (material && material.needAlphaTesting()) {
  25474. defines.push("#define ALPHATEST");
  25475. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  25476. attribs.push(BABYLON.VertexBuffer.UVKind);
  25477. defines.push("#define UV1");
  25478. }
  25479. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  25480. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  25481. defines.push("#define UV2");
  25482. }
  25483. }
  25484. // Bones
  25485. if (mesh.useBones) {
  25486. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25487. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25488. defines.push("#define BONES");
  25489. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  25490. }
  25491. // Instances
  25492. if (useInstances) {
  25493. defines.push("#define INSTANCES");
  25494. attribs.push("world0");
  25495. attribs.push("world1");
  25496. attribs.push("world2");
  25497. attribs.push("world3");
  25498. }
  25499. // Get correct effect
  25500. var join = defines.join("\n");
  25501. if (this._cachedDefines !== join) {
  25502. this._cachedDefines = join;
  25503. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  25504. }
  25505. return this._effect.isReady();
  25506. };
  25507. return OutlineRenderer;
  25508. })();
  25509. BABYLON.OutlineRenderer = OutlineRenderer;
  25510. })(BABYLON || (BABYLON = {}));
  25511. //# sourceMappingURL=babylon.outlineRenderer.js.mapvar BABYLON;
  25512. (function (BABYLON) {
  25513. var MeshAssetTask = (function () {
  25514. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  25515. this.name = name;
  25516. this.meshesNames = meshesNames;
  25517. this.rootUrl = rootUrl;
  25518. this.sceneFilename = sceneFilename;
  25519. this.isCompleted = false;
  25520. }
  25521. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25522. var _this = this;
  25523. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  25524. _this.loadedMeshes = meshes;
  25525. _this.loadedParticleSystems = particleSystems;
  25526. _this.loadedSkeletons = skeletons;
  25527. _this.isCompleted = true;
  25528. if (_this.onSuccess) {
  25529. _this.onSuccess(_this);
  25530. }
  25531. onSuccess();
  25532. }, null, function () {
  25533. if (_this.onError) {
  25534. _this.onError(_this);
  25535. }
  25536. onError();
  25537. });
  25538. };
  25539. return MeshAssetTask;
  25540. })();
  25541. BABYLON.MeshAssetTask = MeshAssetTask;
  25542. var TextFileAssetTask = (function () {
  25543. function TextFileAssetTask(name, url) {
  25544. this.name = name;
  25545. this.url = url;
  25546. this.isCompleted = false;
  25547. }
  25548. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25549. var _this = this;
  25550. BABYLON.Tools.LoadFile(this.url, function (data) {
  25551. _this.text = data;
  25552. _this.isCompleted = true;
  25553. if (_this.onSuccess) {
  25554. _this.onSuccess(_this);
  25555. }
  25556. onSuccess();
  25557. }, null, scene.database, false, function () {
  25558. if (_this.onError) {
  25559. _this.onError(_this);
  25560. }
  25561. onError();
  25562. });
  25563. };
  25564. return TextFileAssetTask;
  25565. })();
  25566. BABYLON.TextFileAssetTask = TextFileAssetTask;
  25567. var BinaryFileAssetTask = (function () {
  25568. function BinaryFileAssetTask(name, url) {
  25569. this.name = name;
  25570. this.url = url;
  25571. this.isCompleted = false;
  25572. }
  25573. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25574. var _this = this;
  25575. BABYLON.Tools.LoadFile(this.url, function (data) {
  25576. _this.data = data;
  25577. _this.isCompleted = true;
  25578. if (_this.onSuccess) {
  25579. _this.onSuccess(_this);
  25580. }
  25581. onSuccess();
  25582. }, null, scene.database, true, function () {
  25583. if (_this.onError) {
  25584. _this.onError(_this);
  25585. }
  25586. onError();
  25587. });
  25588. };
  25589. return BinaryFileAssetTask;
  25590. })();
  25591. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  25592. var ImageAssetTask = (function () {
  25593. function ImageAssetTask(name, url) {
  25594. this.name = name;
  25595. this.url = url;
  25596. this.isCompleted = false;
  25597. }
  25598. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25599. var _this = this;
  25600. var img = new Image();
  25601. img.onload = function () {
  25602. _this.image = img;
  25603. _this.isCompleted = true;
  25604. if (_this.onSuccess) {
  25605. _this.onSuccess(_this);
  25606. }
  25607. onSuccess();
  25608. };
  25609. img.onerror = function () {
  25610. if (_this.onError) {
  25611. _this.onError(_this);
  25612. }
  25613. onError();
  25614. };
  25615. img.src = this.url;
  25616. };
  25617. return ImageAssetTask;
  25618. })();
  25619. BABYLON.ImageAssetTask = ImageAssetTask;
  25620. var TextureAssetTask = (function () {
  25621. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  25622. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25623. this.name = name;
  25624. this.url = url;
  25625. this.noMipmap = noMipmap;
  25626. this.invertY = invertY;
  25627. this.samplingMode = samplingMode;
  25628. this.isCompleted = false;
  25629. }
  25630. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  25631. var _this = this;
  25632. var onload = function () {
  25633. _this.isCompleted = true;
  25634. if (_this.onSuccess) {
  25635. _this.onSuccess(_this);
  25636. }
  25637. onSuccess();
  25638. };
  25639. var onerror = function () {
  25640. if (_this.onError) {
  25641. _this.onError(_this);
  25642. }
  25643. onError();
  25644. };
  25645. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onError);
  25646. };
  25647. return TextureAssetTask;
  25648. })();
  25649. BABYLON.TextureAssetTask = TextureAssetTask;
  25650. var AssetsManager = (function () {
  25651. function AssetsManager(scene) {
  25652. this._tasks = new Array();
  25653. this._waitingTasksCount = 0;
  25654. this.useDefaultLoadingScreen = true;
  25655. this._scene = scene;
  25656. }
  25657. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  25658. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  25659. this._tasks.push(task);
  25660. return task;
  25661. };
  25662. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  25663. var task = new TextFileAssetTask(taskName, url);
  25664. this._tasks.push(task);
  25665. return task;
  25666. };
  25667. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  25668. var task = new BinaryFileAssetTask(taskName, url);
  25669. this._tasks.push(task);
  25670. return task;
  25671. };
  25672. AssetsManager.prototype.addImageTask = function (taskName, url) {
  25673. var task = new ImageAssetTask(taskName, url);
  25674. this._tasks.push(task);
  25675. return task;
  25676. };
  25677. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  25678. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25679. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  25680. this._tasks.push(task);
  25681. return task;
  25682. };
  25683. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  25684. this._waitingTasksCount--;
  25685. if (this._waitingTasksCount === 0) {
  25686. if (this.onFinish) {
  25687. this.onFinish(this._tasks);
  25688. }
  25689. this._scene.getEngine().hideLoadingUI();
  25690. }
  25691. };
  25692. AssetsManager.prototype._runTask = function (task) {
  25693. var _this = this;
  25694. task.run(this._scene, function () {
  25695. if (_this.onTaskSuccess) {
  25696. _this.onTaskSuccess(task);
  25697. }
  25698. _this._decreaseWaitingTasksCount();
  25699. }, function () {
  25700. if (_this.onTaskError) {
  25701. _this.onTaskError(task);
  25702. }
  25703. _this._decreaseWaitingTasksCount();
  25704. });
  25705. };
  25706. AssetsManager.prototype.reset = function () {
  25707. this._tasks = new Array();
  25708. return this;
  25709. };
  25710. AssetsManager.prototype.load = function () {
  25711. this._waitingTasksCount = this._tasks.length;
  25712. if (this._waitingTasksCount === 0) {
  25713. if (this.onFinish) {
  25714. this.onFinish(this._tasks);
  25715. }
  25716. return this;
  25717. }
  25718. if (this.useDefaultLoadingScreen) {
  25719. this._scene.getEngine().displayLoadingUI();
  25720. }
  25721. for (var index = 0; index < this._tasks.length; index++) {
  25722. var task = this._tasks[index];
  25723. this._runTask(task);
  25724. }
  25725. return this;
  25726. };
  25727. return AssetsManager;
  25728. })();
  25729. BABYLON.AssetsManager = AssetsManager;
  25730. })(BABYLON || (BABYLON = {}));
  25731. //# sourceMappingURL=babylon.assetsManager.js.map
  25732. var BABYLON;
  25733. (function (BABYLON) {
  25734. var VRDeviceOrientationCamera = (function (_super) {
  25735. __extends(VRDeviceOrientationCamera, _super);
  25736. function VRDeviceOrientationCamera(name, position, scene) {
  25737. _super.call(this, name, position, scene);
  25738. this._alpha = 0;
  25739. this._beta = 0;
  25740. this._gamma = 0;
  25741. }
  25742. VRDeviceOrientationCamera.prototype._onOrientationEvent = function (evt) {
  25743. this._alpha = +evt.alpha | 0;
  25744. this._beta = +evt.beta | 0;
  25745. this._gamma = +evt.gamma | 0;
  25746. if (this._gamma < 0) {
  25747. this._gamma = 90 + this._gamma;
  25748. }
  25749. else {
  25750. // Incline it in the correct angle.
  25751. this._gamma = 270 - this._gamma;
  25752. }
  25753. this.rotation.x = this._gamma / 180.0 * Math.PI;
  25754. this.rotation.y = -this._alpha / 180.0 * Math.PI;
  25755. this.rotation.z = this._beta / 180.0 * Math.PI;
  25756. };
  25757. return VRDeviceOrientationCamera;
  25758. })(BABYLON.OculusCamera);
  25759. BABYLON.VRDeviceOrientationCamera = VRDeviceOrientationCamera;
  25760. })(BABYLON || (BABYLON = {}));
  25761. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  25762. var BABYLON;
  25763. (function (BABYLON) {
  25764. var WebVRCamera = (function (_super) {
  25765. __extends(WebVRCamera, _super);
  25766. function WebVRCamera(name, position, scene) {
  25767. _super.call(this, name, position, scene);
  25768. this._hmdDevice = null;
  25769. this._sensorDevice = null;
  25770. this._cacheState = null;
  25771. this._cacheQuaternion = new BABYLON.Quaternion();
  25772. this._cacheRotation = BABYLON.Vector3.Zero();
  25773. this._vrEnabled = false;
  25774. this._getWebVRDevices = this._getWebVRDevices.bind(this);
  25775. }
  25776. WebVRCamera.prototype._getWebVRDevices = function (devices) {
  25777. var size = devices.length;
  25778. var i = 0;
  25779. // Reset devices.
  25780. this._sensorDevice = null;
  25781. this._hmdDevice = null;
  25782. while (i < size && this._hmdDevice === null) {
  25783. if (devices[i] instanceof HMDVRDevice) {
  25784. this._hmdDevice = devices[i];
  25785. }
  25786. i++;
  25787. }
  25788. i = 0;
  25789. while (i < size && this._sensorDevice === null) {
  25790. if (devices[i] instanceof PositionSensorVRDevice && (!this._hmdDevice || devices[i].hardwareUnitId === this._hmdDevice.hardwareUnitId)) {
  25791. this._sensorDevice = devices[i];
  25792. }
  25793. i++;
  25794. }
  25795. this._vrEnabled = this._sensorDevice && this._hmdDevice ? true : false;
  25796. };
  25797. WebVRCamera.prototype._update = function () {
  25798. if (this._vrEnabled) {
  25799. this._cacheState = this._sensorDevice.getState();
  25800. this._cacheQuaternion.copyFromFloats(this._cacheState.orientation.x, this._cacheState.orientation.y, this._cacheState.orientation.z, this._cacheState.orientation.w);
  25801. this._cacheQuaternion.toEulerAnglesToRef(this._cacheRotation);
  25802. this.rotation.x = -this._cacheRotation.z;
  25803. this.rotation.y = -this._cacheRotation.y;
  25804. this.rotation.z = this._cacheRotation.x;
  25805. }
  25806. _super.prototype._update.call(this);
  25807. };
  25808. WebVRCamera.prototype.attachControl = function (element, noPreventDefault) {
  25809. _super.prototype.attachControl.call(this, element, noPreventDefault);
  25810. if (navigator.getVRDevices) {
  25811. navigator.getVRDevices().then(this._getWebVRDevices);
  25812. }
  25813. else if (navigator.mozGetVRDevices) {
  25814. navigator.mozGetVRDevices(this._getWebVRDevices);
  25815. }
  25816. };
  25817. WebVRCamera.prototype.detachControl = function (element) {
  25818. _super.prototype.detachControl.call(this, element);
  25819. this._vrEnabled = false;
  25820. };
  25821. return WebVRCamera;
  25822. })(BABYLON.OculusCamera);
  25823. BABYLON.WebVRCamera = WebVRCamera;
  25824. })(BABYLON || (BABYLON = {}));
  25825. //# sourceMappingURL=babylon.webVRCamera.js.map
  25826. var BABYLON;
  25827. (function (BABYLON) {
  25828. // Standard optimizations
  25829. var SceneOptimization = (function () {
  25830. function SceneOptimization(priority) {
  25831. if (priority === void 0) { priority = 0; }
  25832. this.priority = priority;
  25833. this.apply = function (scene) {
  25834. return true; // Return true if everything that can be done was applied
  25835. };
  25836. }
  25837. return SceneOptimization;
  25838. })();
  25839. BABYLON.SceneOptimization = SceneOptimization;
  25840. var TextureOptimization = (function (_super) {
  25841. __extends(TextureOptimization, _super);
  25842. function TextureOptimization(priority, maximumSize) {
  25843. var _this = this;
  25844. if (priority === void 0) { priority = 0; }
  25845. if (maximumSize === void 0) { maximumSize = 1024; }
  25846. _super.call(this, priority);
  25847. this.priority = priority;
  25848. this.maximumSize = maximumSize;
  25849. this.apply = function (scene) {
  25850. var allDone = true;
  25851. for (var index = 0; index < scene.textures.length; index++) {
  25852. var texture = scene.textures[index];
  25853. if (!texture.canRescale) {
  25854. continue;
  25855. }
  25856. var currentSize = texture.getSize();
  25857. var maxDimension = Math.max(currentSize.width, currentSize.height);
  25858. if (maxDimension > _this.maximumSize) {
  25859. texture.scale(0.5);
  25860. allDone = false;
  25861. }
  25862. }
  25863. return allDone;
  25864. };
  25865. }
  25866. return TextureOptimization;
  25867. })(SceneOptimization);
  25868. BABYLON.TextureOptimization = TextureOptimization;
  25869. var HardwareScalingOptimization = (function (_super) {
  25870. __extends(HardwareScalingOptimization, _super);
  25871. function HardwareScalingOptimization(priority, maximumScale) {
  25872. var _this = this;
  25873. if (priority === void 0) { priority = 0; }
  25874. if (maximumScale === void 0) { maximumScale = 2; }
  25875. _super.call(this, priority);
  25876. this.priority = priority;
  25877. this.maximumScale = maximumScale;
  25878. this._currentScale = 1;
  25879. this.apply = function (scene) {
  25880. _this._currentScale++;
  25881. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  25882. return _this._currentScale >= _this.maximumScale;
  25883. };
  25884. }
  25885. return HardwareScalingOptimization;
  25886. })(SceneOptimization);
  25887. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  25888. var ShadowsOptimization = (function (_super) {
  25889. __extends(ShadowsOptimization, _super);
  25890. function ShadowsOptimization() {
  25891. _super.apply(this, arguments);
  25892. this.apply = function (scene) {
  25893. scene.shadowsEnabled = false;
  25894. return true;
  25895. };
  25896. }
  25897. return ShadowsOptimization;
  25898. })(SceneOptimization);
  25899. BABYLON.ShadowsOptimization = ShadowsOptimization;
  25900. var PostProcessesOptimization = (function (_super) {
  25901. __extends(PostProcessesOptimization, _super);
  25902. function PostProcessesOptimization() {
  25903. _super.apply(this, arguments);
  25904. this.apply = function (scene) {
  25905. scene.postProcessesEnabled = false;
  25906. return true;
  25907. };
  25908. }
  25909. return PostProcessesOptimization;
  25910. })(SceneOptimization);
  25911. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  25912. var LensFlaresOptimization = (function (_super) {
  25913. __extends(LensFlaresOptimization, _super);
  25914. function LensFlaresOptimization() {
  25915. _super.apply(this, arguments);
  25916. this.apply = function (scene) {
  25917. scene.lensFlaresEnabled = false;
  25918. return true;
  25919. };
  25920. }
  25921. return LensFlaresOptimization;
  25922. })(SceneOptimization);
  25923. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  25924. var ParticlesOptimization = (function (_super) {
  25925. __extends(ParticlesOptimization, _super);
  25926. function ParticlesOptimization() {
  25927. _super.apply(this, arguments);
  25928. this.apply = function (scene) {
  25929. scene.particlesEnabled = false;
  25930. return true;
  25931. };
  25932. }
  25933. return ParticlesOptimization;
  25934. })(SceneOptimization);
  25935. BABYLON.ParticlesOptimization = ParticlesOptimization;
  25936. var RenderTargetsOptimization = (function (_super) {
  25937. __extends(RenderTargetsOptimization, _super);
  25938. function RenderTargetsOptimization() {
  25939. _super.apply(this, arguments);
  25940. this.apply = function (scene) {
  25941. scene.renderTargetsEnabled = false;
  25942. return true;
  25943. };
  25944. }
  25945. return RenderTargetsOptimization;
  25946. })(SceneOptimization);
  25947. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  25948. var MergeMeshesOptimization = (function (_super) {
  25949. __extends(MergeMeshesOptimization, _super);
  25950. function MergeMeshesOptimization() {
  25951. var _this = this;
  25952. _super.apply(this, arguments);
  25953. this._canBeMerged = function (abstractMesh) {
  25954. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  25955. return false;
  25956. }
  25957. var mesh = abstractMesh;
  25958. if (!mesh.isVisible || !mesh.isEnabled()) {
  25959. return false;
  25960. }
  25961. if (mesh.instances.length > 0) {
  25962. return false;
  25963. }
  25964. if (mesh.skeleton || mesh.hasLODLevels) {
  25965. return false;
  25966. }
  25967. return true;
  25968. };
  25969. this.apply = function (scene) {
  25970. var globalPool = scene.meshes.slice(0);
  25971. var globalLength = globalPool.length;
  25972. for (var index = 0; index < globalLength; index++) {
  25973. var currentPool = new Array();
  25974. var current = globalPool[index];
  25975. // Checks
  25976. if (!_this._canBeMerged(current)) {
  25977. continue;
  25978. }
  25979. currentPool.push(current);
  25980. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  25981. var otherMesh = globalPool[subIndex];
  25982. if (!_this._canBeMerged(otherMesh)) {
  25983. continue;
  25984. }
  25985. if (otherMesh.material !== current.material) {
  25986. continue;
  25987. }
  25988. if (otherMesh.checkCollisions !== current.checkCollisions) {
  25989. continue;
  25990. }
  25991. currentPool.push(otherMesh);
  25992. globalLength--;
  25993. globalPool.splice(subIndex, 1);
  25994. subIndex--;
  25995. }
  25996. if (currentPool.length < 2) {
  25997. continue;
  25998. }
  25999. // Merge meshes
  26000. BABYLON.Mesh.MergeMeshes(currentPool);
  26001. }
  26002. return true;
  26003. };
  26004. }
  26005. return MergeMeshesOptimization;
  26006. })(SceneOptimization);
  26007. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  26008. // Options
  26009. var SceneOptimizerOptions = (function () {
  26010. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  26011. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  26012. if (trackerDuration === void 0) { trackerDuration = 2000; }
  26013. this.targetFrameRate = targetFrameRate;
  26014. this.trackerDuration = trackerDuration;
  26015. this.optimizations = new Array();
  26016. }
  26017. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  26018. var result = new SceneOptimizerOptions(targetFrameRate);
  26019. var priority = 0;
  26020. result.optimizations.push(new MergeMeshesOptimization(priority));
  26021. result.optimizations.push(new ShadowsOptimization(priority));
  26022. result.optimizations.push(new LensFlaresOptimization(priority));
  26023. // Next priority
  26024. priority++;
  26025. result.optimizations.push(new PostProcessesOptimization(priority));
  26026. result.optimizations.push(new ParticlesOptimization(priority));
  26027. // Next priority
  26028. priority++;
  26029. result.optimizations.push(new TextureOptimization(priority, 1024));
  26030. return result;
  26031. };
  26032. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  26033. var result = new SceneOptimizerOptions(targetFrameRate);
  26034. var priority = 0;
  26035. result.optimizations.push(new MergeMeshesOptimization(priority));
  26036. result.optimizations.push(new ShadowsOptimization(priority));
  26037. result.optimizations.push(new LensFlaresOptimization(priority));
  26038. // Next priority
  26039. priority++;
  26040. result.optimizations.push(new PostProcessesOptimization(priority));
  26041. result.optimizations.push(new ParticlesOptimization(priority));
  26042. // Next priority
  26043. priority++;
  26044. result.optimizations.push(new TextureOptimization(priority, 512));
  26045. // Next priority
  26046. priority++;
  26047. result.optimizations.push(new RenderTargetsOptimization(priority));
  26048. // Next priority
  26049. priority++;
  26050. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  26051. return result;
  26052. };
  26053. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  26054. var result = new SceneOptimizerOptions(targetFrameRate);
  26055. var priority = 0;
  26056. result.optimizations.push(new MergeMeshesOptimization(priority));
  26057. result.optimizations.push(new ShadowsOptimization(priority));
  26058. result.optimizations.push(new LensFlaresOptimization(priority));
  26059. // Next priority
  26060. priority++;
  26061. result.optimizations.push(new PostProcessesOptimization(priority));
  26062. result.optimizations.push(new ParticlesOptimization(priority));
  26063. // Next priority
  26064. priority++;
  26065. result.optimizations.push(new TextureOptimization(priority, 256));
  26066. // Next priority
  26067. priority++;
  26068. result.optimizations.push(new RenderTargetsOptimization(priority));
  26069. // Next priority
  26070. priority++;
  26071. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  26072. return result;
  26073. };
  26074. return SceneOptimizerOptions;
  26075. })();
  26076. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  26077. // Scene optimizer tool
  26078. var SceneOptimizer = (function () {
  26079. function SceneOptimizer() {
  26080. }
  26081. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  26082. // TODO: add an epsilon
  26083. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  26084. if (onSuccess) {
  26085. onSuccess();
  26086. }
  26087. return;
  26088. }
  26089. // Apply current level of optimizations
  26090. var allDone = true;
  26091. var noOptimizationApplied = true;
  26092. for (var index = 0; index < options.optimizations.length; index++) {
  26093. var optimization = options.optimizations[index];
  26094. if (optimization.priority === currentPriorityLevel) {
  26095. noOptimizationApplied = false;
  26096. allDone = allDone && optimization.apply(scene);
  26097. }
  26098. }
  26099. // If no optimization was applied, this is a failure :(
  26100. if (noOptimizationApplied) {
  26101. if (onFailure) {
  26102. onFailure();
  26103. }
  26104. return;
  26105. }
  26106. // If all optimizations were done, move to next level
  26107. if (allDone) {
  26108. currentPriorityLevel++;
  26109. }
  26110. // Let's the system running for a specific amount of time before checking FPS
  26111. scene.executeWhenReady(function () {
  26112. setTimeout(function () {
  26113. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  26114. }, options.trackerDuration);
  26115. });
  26116. };
  26117. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  26118. if (!options) {
  26119. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  26120. }
  26121. // Let's the system running for a specific amount of time before checking FPS
  26122. scene.executeWhenReady(function () {
  26123. setTimeout(function () {
  26124. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  26125. }, options.trackerDuration);
  26126. });
  26127. };
  26128. return SceneOptimizer;
  26129. })();
  26130. BABYLON.SceneOptimizer = SceneOptimizer;
  26131. })(BABYLON || (BABYLON = {}));
  26132. //# sourceMappingURL=babylon.sceneOptimizer.js.mapvar BABYLON;
  26133. (function (BABYLON) {
  26134. var Internals;
  26135. (function (Internals) {
  26136. var MeshLODLevel = (function () {
  26137. function MeshLODLevel(distance, mesh) {
  26138. this.distance = distance;
  26139. this.mesh = mesh;
  26140. }
  26141. return MeshLODLevel;
  26142. })();
  26143. Internals.MeshLODLevel = MeshLODLevel;
  26144. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  26145. })(BABYLON || (BABYLON = {}));
  26146. //# sourceMappingURL=babylon.meshLODLevel.js.mapvar BABYLON;
  26147. (function (BABYLON) {
  26148. var AudioEngine = (function () {
  26149. function AudioEngine() {
  26150. this.audioContext = null;
  26151. this.canUseWebAudio = false;
  26152. this.WarnedWebAudioUnsupported = false;
  26153. try {
  26154. if (typeof AudioContext !== 'undefined') {
  26155. this.audioContext = new AudioContext();
  26156. this.canUseWebAudio = true;
  26157. }
  26158. else if (typeof webkitAudioContext !== 'undefined') {
  26159. this.audioContext = new webkitAudioContext();
  26160. this.canUseWebAudio = true;
  26161. }
  26162. }
  26163. catch (e) {
  26164. this.canUseWebAudio = false;
  26165. BABYLON.Tools.Error("Web Audio: " + e.message);
  26166. }
  26167. // create a global volume gain node
  26168. if (this.canUseWebAudio) {
  26169. this.masterGain = this.audioContext.createGain();
  26170. this.masterGain.gain.value = 1;
  26171. this.masterGain.connect(this.audioContext.destination);
  26172. }
  26173. }
  26174. AudioEngine.prototype.dispose = function () {
  26175. if (this.canUseWebAudio) {
  26176. if (this._connectedAnalyser) {
  26177. this._connectedAnalyser.stopDebugCanvas();
  26178. this._connectedAnalyser.dispose();
  26179. this.masterGain.disconnect();
  26180. this.masterGain.connect(this.audioContext.destination);
  26181. this._connectedAnalyser = null;
  26182. }
  26183. this.masterGain.gain.value = 1;
  26184. }
  26185. this.WarnedWebAudioUnsupported = false;
  26186. };
  26187. AudioEngine.prototype.getGlobalVolume = function () {
  26188. if (this.canUseWebAudio) {
  26189. return this.masterGain.gain.value;
  26190. }
  26191. else {
  26192. return -1;
  26193. }
  26194. };
  26195. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  26196. if (this.canUseWebAudio) {
  26197. this.masterGain.gain.value = newVolume;
  26198. }
  26199. };
  26200. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  26201. if (this._connectedAnalyser) {
  26202. this._connectedAnalyser.stopDebugCanvas();
  26203. }
  26204. this._connectedAnalyser = analyser;
  26205. if (this.canUseWebAudio) {
  26206. this.masterGain.disconnect();
  26207. this._connectedAnalyser.connectAudioNodes(this.masterGain, this.audioContext.destination);
  26208. }
  26209. };
  26210. return AudioEngine;
  26211. })();
  26212. BABYLON.AudioEngine = AudioEngine;
  26213. })(BABYLON || (BABYLON = {}));
  26214. //# sourceMappingURL=babylon.audioengine.js.mapvar BABYLON;
  26215. (function (BABYLON) {
  26216. var Sound = (function () {
  26217. /**
  26218. * Create a sound and attach it to a scene
  26219. * @param name Name of your sound
  26220. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  26221. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  26222. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel
  26223. */
  26224. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  26225. var _this = this;
  26226. this.autoplay = false;
  26227. this.loop = false;
  26228. this.useCustomAttenuation = false;
  26229. this.spatialSound = false;
  26230. this.refDistance = 1;
  26231. this.rolloffFactor = 1;
  26232. this.maxDistance = 100;
  26233. this.distanceModel = "linear";
  26234. this.panningModel = "HRTF";
  26235. this._playbackRate = 1;
  26236. this._startTime = 0;
  26237. this._startOffset = 0;
  26238. this._position = BABYLON.Vector3.Zero();
  26239. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  26240. this._volume = 1;
  26241. this._isLoaded = false;
  26242. this._isReadyToPlay = false;
  26243. this.isPlaying = false;
  26244. this.isPaused = false;
  26245. this._isDirectional = false;
  26246. // Used if you'd like to create a directional sound.
  26247. // If not set, the sound will be omnidirectional
  26248. this._coneInnerAngle = 360;
  26249. this._coneOuterAngle = 360;
  26250. this._coneOuterGain = 0;
  26251. this.name = name;
  26252. this._scene = scene;
  26253. this._readyToPlayCallback = readyToPlayCallback;
  26254. // Default custom attenuation function is a linear attenuation
  26255. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  26256. if (currentDistance < maxDistance) {
  26257. return currentVolume * (1 - currentDistance / maxDistance);
  26258. }
  26259. else {
  26260. return 0;
  26261. }
  26262. };
  26263. if (options) {
  26264. this.autoplay = options.autoplay || false;
  26265. this.loop = options.loop || false;
  26266. // if volume === 0, we need another way to check this option
  26267. if (options.volume !== undefined) {
  26268. this._volume = options.volume;
  26269. }
  26270. this.spatialSound = options.spatialSound || false;
  26271. this.maxDistance = options.maxDistance || 100;
  26272. this.useCustomAttenuation = options.useCustomAttenuation || false;
  26273. this.rolloffFactor = options.rolloffFactor || 1;
  26274. this.refDistance = options.refDistance || 1;
  26275. this.distanceModel = options.distanceModel || "linear";
  26276. this.panningModel = options.panningModel || "HRTF";
  26277. this._playbackRate = options.playbackRate || 1;
  26278. }
  26279. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26280. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  26281. this._soundGain.gain.value = this._volume;
  26282. this._inputAudioNode = this._soundGain;
  26283. this._ouputAudioNode = this._soundGain;
  26284. if (this.spatialSound) {
  26285. this._createSpatialParameters();
  26286. }
  26287. this._scene.mainSoundTrack.AddSound(this);
  26288. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  26289. if (urlOrArrayBuffer) {
  26290. // If it's an URL
  26291. if (typeof (urlOrArrayBuffer) === "string") {
  26292. BABYLON.Tools.LoadFile(urlOrArrayBuffer, function (data) {
  26293. _this._soundLoaded(data);
  26294. }, null, null, true);
  26295. }
  26296. else {
  26297. if (urlOrArrayBuffer instanceof ArrayBuffer) {
  26298. this._soundLoaded(urlOrArrayBuffer);
  26299. }
  26300. else {
  26301. BABYLON.Tools.Error("Parameter must be a URL to the sound or an ArrayBuffer of the sound.");
  26302. }
  26303. }
  26304. }
  26305. }
  26306. else {
  26307. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  26308. this._scene.mainSoundTrack.AddSound(this);
  26309. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  26310. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  26311. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  26312. }
  26313. }
  26314. }
  26315. Sound.prototype.dispose = function () {
  26316. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  26317. if (this.isPlaying) {
  26318. this.stop();
  26319. }
  26320. this._isReadyToPlay = false;
  26321. if (this.soundTrackId === -1) {
  26322. this._scene.mainSoundTrack.RemoveSound(this);
  26323. }
  26324. else {
  26325. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  26326. }
  26327. if (this._soundGain) {
  26328. this._soundGain.disconnect();
  26329. this._soundGain = null;
  26330. }
  26331. if (this._soundPanner) {
  26332. this._soundPanner.disconnect();
  26333. this._soundPanner = null;
  26334. }
  26335. if (this._soundSource) {
  26336. this._soundSource.disconnect();
  26337. this._soundSource = null;
  26338. }
  26339. this._audioBuffer = null;
  26340. if (this._connectedMesh) {
  26341. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  26342. this._connectedMesh = null;
  26343. }
  26344. }
  26345. };
  26346. Sound.prototype._soundLoaded = function (audioData) {
  26347. var _this = this;
  26348. this._isLoaded = true;
  26349. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  26350. _this._audioBuffer = buffer;
  26351. _this._isReadyToPlay = true;
  26352. if (_this.autoplay) {
  26353. _this.play();
  26354. }
  26355. if (_this._readyToPlayCallback) {
  26356. _this._readyToPlayCallback();
  26357. }
  26358. }, function (error) {
  26359. BABYLON.Tools.Error("Error while decoding audio data: " + error.err);
  26360. });
  26361. };
  26362. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  26363. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26364. this._audioBuffer = audioBuffer;
  26365. this._isReadyToPlay = true;
  26366. }
  26367. };
  26368. Sound.prototype.updateOptions = function (options) {
  26369. if (options) {
  26370. this.loop = options.loop || this.loop;
  26371. this.maxDistance = options.maxDistance || this.maxDistance;
  26372. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  26373. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  26374. this.refDistance = options.refDistance || this.refDistance;
  26375. this.distanceModel = options.distanceModel || this.distanceModel;
  26376. this.panningModel = options.panningModel || this.panningModel;
  26377. this._playbackRate = options.playbackRate || this._playbackRate;
  26378. }
  26379. };
  26380. Sound.prototype._createSpatialParameters = function () {
  26381. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26382. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  26383. if (this.useCustomAttenuation) {
  26384. // Tricks to disable in a way embedded Web Audio attenuation
  26385. this._soundPanner.distanceModel = "linear";
  26386. this._soundPanner.maxDistance = Number.MAX_VALUE;
  26387. this._soundPanner.refDistance = 1;
  26388. this._soundPanner.rolloffFactor = 1;
  26389. this._soundPanner.panningModel = "HRTF";
  26390. }
  26391. else {
  26392. this._soundPanner.distanceModel = this.distanceModel;
  26393. this._soundPanner.maxDistance = this.maxDistance;
  26394. this._soundPanner.refDistance = this.refDistance;
  26395. this._soundPanner.rolloffFactor = this.rolloffFactor;
  26396. this._soundPanner.panningModel = this.panningModel;
  26397. }
  26398. this._soundPanner.connect(this._ouputAudioNode);
  26399. this._inputAudioNode = this._soundPanner;
  26400. }
  26401. };
  26402. Sound.prototype.switchPanningModelToHRTF = function () {
  26403. this._switchPanningModel("HRTF");
  26404. };
  26405. Sound.prototype.switchPanningModelToEqualPower = function () {
  26406. this._switchPanningModel("equalpower");
  26407. };
  26408. Sound.prototype._switchPanningModel = function (newModel) {
  26409. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  26410. this._soundPanner.panningModel = newModel;
  26411. }
  26412. };
  26413. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  26414. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26415. this._ouputAudioNode.disconnect();
  26416. this._ouputAudioNode.connect(soundTrackAudioNode);
  26417. }
  26418. };
  26419. /**
  26420. * Transform this sound into a directional source
  26421. * @param coneInnerAngle Size of the inner cone in degree
  26422. * @param coneOuterAngle Size of the outer cone in degree
  26423. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  26424. */
  26425. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  26426. if (coneOuterAngle < coneInnerAngle) {
  26427. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  26428. return;
  26429. }
  26430. this._coneInnerAngle = coneInnerAngle;
  26431. this._coneOuterAngle = coneOuterAngle;
  26432. this._coneOuterGain = coneOuterGain;
  26433. this._isDirectional = true;
  26434. if (this.isPlaying && this.loop) {
  26435. this.stop();
  26436. this.play();
  26437. }
  26438. };
  26439. Sound.prototype.setPosition = function (newPosition) {
  26440. this._position = newPosition;
  26441. if (this.isPlaying && this.spatialSound) {
  26442. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26443. }
  26444. };
  26445. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  26446. this._localDirection = newLocalDirection;
  26447. if (this._connectedMesh && this.isPlaying) {
  26448. this._updateDirection();
  26449. }
  26450. };
  26451. Sound.prototype._updateDirection = function () {
  26452. var mat = this._connectedMesh.getWorldMatrix();
  26453. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  26454. direction.normalize();
  26455. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  26456. };
  26457. Sound.prototype.updateDistanceFromListener = function () {
  26458. if (this._connectedMesh && this.useCustomAttenuation) {
  26459. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  26460. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  26461. }
  26462. };
  26463. Sound.prototype.setAttenuationFunction = function (callback) {
  26464. this._customAttenuationFunction = callback;
  26465. };
  26466. /**
  26467. * Play the sound
  26468. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  26469. */
  26470. Sound.prototype.play = function (time) {
  26471. var _this = this;
  26472. if (this._isReadyToPlay && this._scene.audioEnabled) {
  26473. try {
  26474. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26475. if (!this._soundSource) {
  26476. if (this.spatialSound) {
  26477. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  26478. if (this._isDirectional) {
  26479. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  26480. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  26481. this._soundPanner.coneOuterGain = this._coneOuterGain;
  26482. if (this._connectedMesh) {
  26483. this._updateDirection();
  26484. }
  26485. else {
  26486. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  26487. }
  26488. }
  26489. }
  26490. }
  26491. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  26492. this._soundSource.buffer = this._audioBuffer;
  26493. this._soundSource.connect(this._inputAudioNode);
  26494. this._soundSource.loop = this.loop;
  26495. this._soundSource.playbackRate.value = this._playbackRate;
  26496. this._startTime = startTime;
  26497. this._soundSource.onended = function () {
  26498. _this._onended();
  26499. };
  26500. this._soundSource.start(this._startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : 0);
  26501. this.isPlaying = true;
  26502. this.isPaused = false;
  26503. }
  26504. catch (ex) {
  26505. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  26506. }
  26507. }
  26508. };
  26509. Sound.prototype._onended = function () {
  26510. this.isPlaying = false;
  26511. if (this.onended) {
  26512. this.onended();
  26513. }
  26514. };
  26515. /**
  26516. * Stop the sound
  26517. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  26518. */
  26519. Sound.prototype.stop = function (time) {
  26520. if (this.isPlaying) {
  26521. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  26522. this._soundSource.stop(stopTime);
  26523. this.isPlaying = false;
  26524. }
  26525. };
  26526. Sound.prototype.pause = function () {
  26527. if (this.isPlaying) {
  26528. this.stop(0);
  26529. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  26530. this.isPaused = true;
  26531. }
  26532. };
  26533. Sound.prototype.setVolume = function (newVolume, time) {
  26534. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26535. if (time) {
  26536. this._soundGain.gain.linearRampToValueAtTime(this._volume, BABYLON.Engine.audioEngine.audioContext.currentTime);
  26537. this._soundGain.gain.linearRampToValueAtTime(newVolume, time);
  26538. }
  26539. else {
  26540. this._soundGain.gain.value = newVolume;
  26541. }
  26542. }
  26543. this._volume = newVolume;
  26544. };
  26545. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  26546. this._playbackRate = newPlaybackRate;
  26547. if (this.isPlaying) {
  26548. this._soundSource.playbackRate.value = this._playbackRate;
  26549. }
  26550. };
  26551. Sound.prototype.getVolume = function () {
  26552. return this._volume;
  26553. };
  26554. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  26555. var _this = this;
  26556. this._connectedMesh = meshToConnectTo;
  26557. if (!this.spatialSound) {
  26558. this._createSpatialParameters();
  26559. this.spatialSound = true;
  26560. if (this.isPlaying && this.loop) {
  26561. this.stop();
  26562. this.play();
  26563. }
  26564. }
  26565. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  26566. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  26567. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  26568. };
  26569. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  26570. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  26571. if (this._isDirectional && this.isPlaying) {
  26572. this._updateDirection();
  26573. }
  26574. };
  26575. return Sound;
  26576. })();
  26577. BABYLON.Sound = Sound;
  26578. })(BABYLON || (BABYLON = {}));
  26579. //# sourceMappingURL=babylon.sound.js.mapvar BABYLON;
  26580. (function (BABYLON) {
  26581. var SoundTrack = (function () {
  26582. function SoundTrack(scene, options) {
  26583. this.id = -1;
  26584. this._isMainTrack = false;
  26585. this._scene = scene;
  26586. this._audioEngine = BABYLON.Engine.audioEngine;
  26587. this.soundCollection = new Array();
  26588. if (this._audioEngine.canUseWebAudio) {
  26589. this._trackGain = this._audioEngine.audioContext.createGain();
  26590. this._trackGain.connect(this._audioEngine.masterGain);
  26591. if (options) {
  26592. if (options.volume) {
  26593. this._trackGain.gain.value = options.volume;
  26594. }
  26595. if (options.mainTrack) {
  26596. this._isMainTrack = options.mainTrack;
  26597. }
  26598. }
  26599. }
  26600. if (!this._isMainTrack) {
  26601. this._scene.soundTracks.push(this);
  26602. this.id = this._scene.soundTracks.length - 1;
  26603. }
  26604. }
  26605. SoundTrack.prototype.dispose = function () {
  26606. if (this._audioEngine.canUseWebAudio) {
  26607. if (this._connectedAnalyser) {
  26608. this._connectedAnalyser.stopDebugCanvas();
  26609. }
  26610. while (this.soundCollection.length) {
  26611. this.soundCollection[0].dispose();
  26612. }
  26613. this._trackGain.disconnect();
  26614. this._trackGain = null;
  26615. }
  26616. };
  26617. SoundTrack.prototype.AddSound = function (sound) {
  26618. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26619. sound.connectToSoundTrackAudioNode(this._trackGain);
  26620. }
  26621. if (sound.soundTrackId) {
  26622. if (sound.soundTrackId === -1) {
  26623. this._scene.mainSoundTrack.RemoveSound(sound);
  26624. }
  26625. else {
  26626. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  26627. }
  26628. }
  26629. this.soundCollection.push(sound);
  26630. sound.soundTrackId = this.id;
  26631. };
  26632. SoundTrack.prototype.RemoveSound = function (sound) {
  26633. var index = this.soundCollection.indexOf(sound);
  26634. if (index !== -1) {
  26635. this.soundCollection.splice(index, 1);
  26636. }
  26637. };
  26638. SoundTrack.prototype.setVolume = function (newVolume) {
  26639. if (this._audioEngine.canUseWebAudio) {
  26640. this._trackGain.gain.value = newVolume;
  26641. }
  26642. };
  26643. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  26644. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26645. for (var i = 0; i < this.soundCollection.length; i++) {
  26646. this.soundCollection[i].switchPanningModelToHRTF();
  26647. }
  26648. }
  26649. };
  26650. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  26651. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  26652. for (var i = 0; i < this.soundCollection.length; i++) {
  26653. this.soundCollection[i].switchPanningModelToEqualPower();
  26654. }
  26655. }
  26656. };
  26657. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  26658. if (this._connectedAnalyser) {
  26659. this._connectedAnalyser.stopDebugCanvas();
  26660. }
  26661. this._connectedAnalyser = analyser;
  26662. if (this._audioEngine.canUseWebAudio) {
  26663. this._trackGain.disconnect();
  26664. this._connectedAnalyser.connectAudioNodes(this._trackGain, this._audioEngine.masterGain);
  26665. }
  26666. };
  26667. return SoundTrack;
  26668. })();
  26669. BABYLON.SoundTrack = SoundTrack;
  26670. })(BABYLON || (BABYLON = {}));
  26671. //# sourceMappingURL=babylon.soundtrack.js.mapvar BABYLON;
  26672. (function (BABYLON) {
  26673. var DebugLayer = (function () {
  26674. function DebugLayer(scene) {
  26675. var _this = this;
  26676. this._transformationMatrix = BABYLON.Matrix.Identity();
  26677. this._enabled = false;
  26678. this._labelsEnabled = false;
  26679. this._displayStatistics = true;
  26680. this._displayTree = false;
  26681. this._displayLogs = false;
  26682. this._identityMatrix = BABYLON.Matrix.Identity();
  26683. this.axisRatio = 0.02;
  26684. this.accentColor = "orange";
  26685. this._scene = scene;
  26686. this._syncPositions = function () {
  26687. var engine = _this._scene.getEngine();
  26688. var canvasRect = engine.getRenderingCanvasClientRect();
  26689. if (_this._showUI) {
  26690. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  26691. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  26692. _this._statsDiv.style.width = "400px";
  26693. _this._statsDiv.style.height = "auto";
  26694. _this._statsSubsetDiv.style.maxHeight = "240px";
  26695. _this._optionsDiv.style.left = "0px";
  26696. _this._optionsDiv.style.top = "10px";
  26697. _this._optionsDiv.style.width = "200px";
  26698. _this._optionsDiv.style.height = "auto";
  26699. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  26700. _this._logDiv.style.left = "0px";
  26701. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  26702. _this._logDiv.style.width = "600px";
  26703. _this._logDiv.style.height = "160px";
  26704. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  26705. _this._treeDiv.style.top = "10px";
  26706. _this._treeDiv.style.width = "300px";
  26707. _this._treeDiv.style.height = "auto";
  26708. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  26709. }
  26710. _this._globalDiv.style.left = canvasRect.left + "px";
  26711. _this._globalDiv.style.top = canvasRect.top + "px";
  26712. _this._drawingCanvas.style.left = "0px";
  26713. _this._drawingCanvas.style.top = "0px";
  26714. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  26715. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  26716. var devicePixelRatio = window.devicePixelRatio || 1;
  26717. var context = _this._drawingContext;
  26718. var backingStoreRatio = context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || context.backingStorePixelRatio || 1;
  26719. _this._ratio = devicePixelRatio / backingStoreRatio;
  26720. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  26721. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  26722. };
  26723. this._onCanvasClick = function (evt) {
  26724. _this._clickPosition = {
  26725. x: evt.clientX * _this._ratio,
  26726. y: evt.clientY * _this._ratio
  26727. };
  26728. };
  26729. this._syncData = function () {
  26730. if (_this._showUI) {
  26731. if (_this._displayStatistics) {
  26732. _this._displayStats();
  26733. _this._statsDiv.style.display = "";
  26734. }
  26735. else {
  26736. _this._statsDiv.style.display = "none";
  26737. }
  26738. if (_this._displayLogs) {
  26739. _this._logDiv.style.display = "";
  26740. }
  26741. else {
  26742. _this._logDiv.style.display = "none";
  26743. }
  26744. if (_this._displayTree) {
  26745. _this._treeDiv.style.display = "";
  26746. if (_this._needToRefreshMeshesTree) {
  26747. _this._needToRefreshMeshesTree = false;
  26748. _this._refreshMeshesTreeContent();
  26749. }
  26750. }
  26751. else {
  26752. _this._treeDiv.style.display = "none";
  26753. }
  26754. }
  26755. if (_this._labelsEnabled || !_this._showUI) {
  26756. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  26757. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  26758. var engine = _this._scene.getEngine();
  26759. var viewport = _this._camera.viewport;
  26760. var globalViewport = viewport.toGlobal(engine);
  26761. // Meshes
  26762. var meshes = _this._camera.getActiveMeshes();
  26763. for (var index = 0; index < meshes.length; index++) {
  26764. var mesh = meshes.data[index];
  26765. var position = mesh.getBoundingInfo().boundingSphere.center;
  26766. var projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26767. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  26768. _this._renderAxis(projectedPosition, mesh, globalViewport);
  26769. }
  26770. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  26771. _this._renderLabel(mesh.name, projectedPosition, 12, function () {
  26772. mesh.renderOverlay = !mesh.renderOverlay;
  26773. }, function () {
  26774. return mesh.renderOverlay ? 'red' : 'black';
  26775. });
  26776. }
  26777. }
  26778. // Cameras
  26779. var cameras = _this._scene.cameras;
  26780. for (index = 0; index < cameras.length; index++) {
  26781. var camera = cameras[index];
  26782. if (camera === _this._camera) {
  26783. continue;
  26784. }
  26785. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  26786. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  26787. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  26788. _this._camera.detachControl(engine.getRenderingCanvas());
  26789. _this._camera = camera;
  26790. _this._camera.attachControl(engine.getRenderingCanvas());
  26791. }, function () {
  26792. return "purple";
  26793. });
  26794. }
  26795. }
  26796. // Lights
  26797. var lights = _this._scene.lights;
  26798. for (index = 0; index < lights.length; index++) {
  26799. var light = lights[index];
  26800. if (light.position) {
  26801. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  26802. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  26803. _this._renderLabel(light.name, projectedPosition, -20, function () {
  26804. light.setEnabled(!light.isEnabled());
  26805. }, function () {
  26806. return light.isEnabled() ? "orange" : "gray";
  26807. });
  26808. }
  26809. }
  26810. }
  26811. }
  26812. _this._clickPosition = undefined;
  26813. };
  26814. }
  26815. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  26816. while (this._treeSubsetDiv.hasChildNodes()) {
  26817. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  26818. }
  26819. // Add meshes
  26820. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  26821. sortedArray.sort(function (a, b) {
  26822. if (a.name === b.name) {
  26823. return 0;
  26824. }
  26825. return (a.name > b.name) ? 1 : -1;
  26826. });
  26827. for (var index = 0; index < sortedArray.length; index++) {
  26828. var mesh = sortedArray[index];
  26829. if (!mesh.isEnabled()) {
  26830. continue;
  26831. }
  26832. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  26833. m.isVisible = element.checked;
  26834. }, mesh);
  26835. }
  26836. };
  26837. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  26838. this._drawingContext.beginPath();
  26839. this._drawingContext.moveTo(zero.x, zero.y);
  26840. this._drawingContext.lineTo(unit.x, unit.y);
  26841. this._drawingContext.strokeStyle = color;
  26842. this._drawingContext.lineWidth = 4;
  26843. this._drawingContext.stroke();
  26844. this._drawingContext.font = "normal 14px Segoe UI";
  26845. this._drawingContext.fillStyle = color;
  26846. this._drawingContext.fillText(label, unitText.x, unitText.y);
  26847. };
  26848. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  26849. var position = mesh.getBoundingInfo().boundingSphere.center;
  26850. var worldMatrix = mesh.getWorldMatrix();
  26851. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  26852. var unit = (unprojectedVector.subtract(position)).length();
  26853. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26854. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26855. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  26856. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26857. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  26858. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  26859. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  26860. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  26861. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  26862. };
  26863. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  26864. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  26865. this._drawingContext.font = "normal 12px Segoe UI";
  26866. var textMetrics = this._drawingContext.measureText(text);
  26867. var centerX = projectedPosition.x - textMetrics.width / 2;
  26868. var centerY = projectedPosition.y;
  26869. var clientRect = this._drawingCanvas.getBoundingClientRect();
  26870. if (this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  26871. onClick();
  26872. }
  26873. this._drawingContext.beginPath();
  26874. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  26875. this._drawingContext.fillStyle = getFillStyle();
  26876. this._drawingContext.globalAlpha = 0.5;
  26877. this._drawingContext.fill();
  26878. this._drawingContext.globalAlpha = 1.0;
  26879. this._drawingContext.strokeStyle = '#FFFFFF';
  26880. this._drawingContext.lineWidth = 1;
  26881. this._drawingContext.stroke();
  26882. this._drawingContext.fillStyle = "#FFFFFF";
  26883. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  26884. this._drawingContext.beginPath();
  26885. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  26886. this._drawingContext.fill();
  26887. }
  26888. };
  26889. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  26890. if (!this._clickPosition) {
  26891. return false;
  26892. }
  26893. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  26894. return false;
  26895. }
  26896. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  26897. return false;
  26898. }
  26899. return true;
  26900. };
  26901. DebugLayer.prototype.isVisible = function () {
  26902. return this._enabled;
  26903. };
  26904. DebugLayer.prototype.hide = function () {
  26905. if (!this._enabled) {
  26906. return;
  26907. }
  26908. this._enabled = false;
  26909. var engine = this._scene.getEngine();
  26910. this._scene.unregisterAfterRender(this._syncData);
  26911. document.body.removeChild(this._globalDiv);
  26912. window.removeEventListener("resize", this._syncPositions);
  26913. this._scene.forceShowBoundingBoxes = false;
  26914. this._scene.forceWireframe = false;
  26915. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  26916. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  26917. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  26918. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  26919. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  26920. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  26921. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  26922. this._scene.shadowsEnabled = true;
  26923. this._scene.particlesEnabled = true;
  26924. this._scene.postProcessesEnabled = true;
  26925. this._scene.collisionsEnabled = true;
  26926. this._scene.lightsEnabled = true;
  26927. this._scene.texturesEnabled = true;
  26928. this._scene.lensFlaresEnabled = true;
  26929. this._scene.proceduralTexturesEnabled = true;
  26930. this._scene.renderTargetsEnabled = true;
  26931. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  26932. };
  26933. DebugLayer.prototype.show = function (showUI, camera) {
  26934. if (showUI === void 0) { showUI = true; }
  26935. if (camera === void 0) { camera = null; }
  26936. if (this._enabled) {
  26937. return;
  26938. }
  26939. if (camera) {
  26940. this._camera = camera;
  26941. }
  26942. else {
  26943. this._camera = this._scene.activeCamera;
  26944. }
  26945. this._enabled = true;
  26946. this._showUI = showUI;
  26947. var engine = this._scene.getEngine();
  26948. this._globalDiv = document.createElement("div");
  26949. document.body.appendChild(this._globalDiv);
  26950. this._generateDOMelements();
  26951. window.addEventListener("resize", this._syncPositions);
  26952. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  26953. this._syncPositions();
  26954. this._scene.registerAfterRender(this._syncData);
  26955. };
  26956. DebugLayer.prototype._clearLabels = function () {
  26957. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  26958. for (var index = 0; index < this._scene.meshes.length; index++) {
  26959. var mesh = this._scene.meshes[index];
  26960. mesh.renderOverlay = false;
  26961. }
  26962. };
  26963. DebugLayer.prototype._generateheader = function (root, text) {
  26964. var header = document.createElement("div");
  26965. header.innerHTML = text + "&nbsp;";
  26966. header.style.textAlign = "right";
  26967. header.style.width = "100%";
  26968. header.style.color = "white";
  26969. header.style.backgroundColor = "Black";
  26970. header.style.padding = "5px 5px 4px 0px";
  26971. header.style.marginLeft = "-5px";
  26972. header.style.fontWeight = "bold";
  26973. root.appendChild(header);
  26974. };
  26975. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  26976. var label = document.createElement("label");
  26977. label.innerHTML = title;
  26978. label.style.color = color;
  26979. root.appendChild(label);
  26980. root.appendChild(document.createElement("br"));
  26981. };
  26982. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  26983. if (tag === void 0) { tag = null; }
  26984. var label = document.createElement("label");
  26985. var boundingBoxesCheckbox = document.createElement("input");
  26986. boundingBoxesCheckbox.type = "checkbox";
  26987. boundingBoxesCheckbox.checked = initialState;
  26988. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  26989. task(evt.target, tag);
  26990. });
  26991. label.appendChild(boundingBoxesCheckbox);
  26992. var container = document.createElement("span");
  26993. var leftPart = document.createElement("span");
  26994. var rightPart = document.createElement("span");
  26995. rightPart.style.cssFloat = "right";
  26996. leftPart.innerHTML = leftTitle;
  26997. rightPart.innerHTML = rightTitle;
  26998. rightPart.style.fontSize = "12px";
  26999. rightPart.style.maxWidth = "200px";
  27000. container.appendChild(leftPart);
  27001. container.appendChild(rightPart);
  27002. label.appendChild(container);
  27003. root.appendChild(label);
  27004. root.appendChild(document.createElement("br"));
  27005. };
  27006. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  27007. if (tag === void 0) { tag = null; }
  27008. var label = document.createElement("label");
  27009. var checkBox = document.createElement("input");
  27010. checkBox.type = "checkbox";
  27011. checkBox.checked = initialState;
  27012. checkBox.addEventListener("change", function (evt) {
  27013. task(evt.target, tag);
  27014. });
  27015. label.appendChild(checkBox);
  27016. label.appendChild(document.createTextNode(title));
  27017. root.appendChild(label);
  27018. root.appendChild(document.createElement("br"));
  27019. };
  27020. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  27021. if (tag === void 0) { tag = null; }
  27022. var button = document.createElement("button");
  27023. button.innerHTML = title;
  27024. button.style.height = "20px";
  27025. button.style.color = "#222222";
  27026. button.addEventListener("click", function (evt) {
  27027. task(evt.target, tag);
  27028. });
  27029. root.appendChild(button);
  27030. root.appendChild(document.createElement("br"));
  27031. };
  27032. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  27033. if (tag === void 0) { tag = null; }
  27034. var label = document.createElement("label");
  27035. var boundingBoxesRadio = document.createElement("input");
  27036. boundingBoxesRadio.type = "radio";
  27037. boundingBoxesRadio.name = name;
  27038. boundingBoxesRadio.checked = initialState;
  27039. boundingBoxesRadio.addEventListener("change", function (evt) {
  27040. task(evt.target, tag);
  27041. });
  27042. label.appendChild(boundingBoxesRadio);
  27043. label.appendChild(document.createTextNode(title));
  27044. root.appendChild(label);
  27045. root.appendChild(document.createElement("br"));
  27046. };
  27047. DebugLayer.prototype._generateDOMelements = function () {
  27048. var _this = this;
  27049. this._globalDiv.id = "DebugLayer";
  27050. this._globalDiv.style.position = "absolute";
  27051. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  27052. this._globalDiv.style.fontSize = "14px";
  27053. this._globalDiv.style.color = "white";
  27054. // Drawing canvas
  27055. this._drawingCanvas = document.createElement("canvas");
  27056. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  27057. this._drawingCanvas.style.position = "absolute";
  27058. this._drawingCanvas.style.pointerEvents = "none";
  27059. this._drawingContext = this._drawingCanvas.getContext("2d");
  27060. this._globalDiv.appendChild(this._drawingCanvas);
  27061. if (this._showUI) {
  27062. var background = "rgba(128, 128, 128, 0.4)";
  27063. var border = "rgb(180, 180, 180) solid 1px";
  27064. // Stats
  27065. this._statsDiv = document.createElement("div");
  27066. this._statsDiv.id = "DebugLayerStats";
  27067. this._statsDiv.style.border = border;
  27068. this._statsDiv.style.position = "absolute";
  27069. this._statsDiv.style.background = background;
  27070. this._statsDiv.style.padding = "0px 0px 0px 5px";
  27071. this._generateheader(this._statsDiv, "STATISTICS");
  27072. this._statsSubsetDiv = document.createElement("div");
  27073. this._statsSubsetDiv.style.paddingTop = "5px";
  27074. this._statsSubsetDiv.style.paddingBottom = "5px";
  27075. this._statsSubsetDiv.style.overflowY = "auto";
  27076. this._statsDiv.appendChild(this._statsSubsetDiv);
  27077. // Tree
  27078. this._treeDiv = document.createElement("div");
  27079. this._treeDiv.id = "DebugLayerTree";
  27080. this._treeDiv.style.border = border;
  27081. this._treeDiv.style.position = "absolute";
  27082. this._treeDiv.style.background = background;
  27083. this._treeDiv.style.padding = "0px 0px 0px 5px";
  27084. this._treeDiv.style.display = "none";
  27085. this._generateheader(this._treeDiv, "MESHES TREE");
  27086. this._treeSubsetDiv = document.createElement("div");
  27087. this._treeSubsetDiv.style.paddingTop = "5px";
  27088. this._treeSubsetDiv.style.paddingRight = "5px";
  27089. this._treeSubsetDiv.style.overflowY = "auto";
  27090. this._treeSubsetDiv.style.maxHeight = "300px";
  27091. this._treeDiv.appendChild(this._treeSubsetDiv);
  27092. this._needToRefreshMeshesTree = true;
  27093. // Logs
  27094. this._logDiv = document.createElement("div");
  27095. this._logDiv.style.border = border;
  27096. this._logDiv.id = "DebugLayerLogs";
  27097. this._logDiv.style.position = "absolute";
  27098. this._logDiv.style.background = background;
  27099. this._logDiv.style.padding = "0px 0px 0px 5px";
  27100. this._logDiv.style.display = "none";
  27101. this._generateheader(this._logDiv, "LOGS");
  27102. this._logSubsetDiv = document.createElement("div");
  27103. this._logSubsetDiv.style.height = "127px";
  27104. this._logSubsetDiv.style.paddingTop = "5px";
  27105. this._logSubsetDiv.style.overflowY = "auto";
  27106. this._logSubsetDiv.style.fontSize = "12px";
  27107. this._logSubsetDiv.style.fontFamily = "consolas";
  27108. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  27109. this._logDiv.appendChild(this._logSubsetDiv);
  27110. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  27111. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  27112. };
  27113. // Options
  27114. this._optionsDiv = document.createElement("div");
  27115. this._optionsDiv.id = "DebugLayerOptions";
  27116. this._optionsDiv.style.border = border;
  27117. this._optionsDiv.style.position = "absolute";
  27118. this._optionsDiv.style.background = background;
  27119. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  27120. this._optionsDiv.style.overflowY = "auto";
  27121. this._generateheader(this._optionsDiv, "OPTIONS");
  27122. this._optionsSubsetDiv = document.createElement("div");
  27123. this._optionsSubsetDiv.style.paddingTop = "5px";
  27124. this._optionsSubsetDiv.style.paddingBottom = "5px";
  27125. this._optionsSubsetDiv.style.overflowY = "auto";
  27126. this._optionsSubsetDiv.style.maxHeight = "200px";
  27127. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  27128. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  27129. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) {
  27130. _this._displayStatistics = element.checked;
  27131. });
  27132. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) {
  27133. _this._displayLogs = element.checked;
  27134. });
  27135. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  27136. _this._displayTree = element.checked;
  27137. _this._needToRefreshMeshesTree = true;
  27138. });
  27139. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27140. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  27141. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) {
  27142. _this._scene.forceShowBoundingBoxes = element.checked;
  27143. });
  27144. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  27145. _this._labelsEnabled = element.checked;
  27146. if (!_this._labelsEnabled) {
  27147. _this._clearLabels();
  27148. }
  27149. });
  27150. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  27151. if (element.checked) {
  27152. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  27153. }
  27154. else {
  27155. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  27156. }
  27157. });
  27158. ;
  27159. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27160. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  27161. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  27162. if (element.checked) {
  27163. _this._scene.forceWireframe = false;
  27164. _this._scene.forcePointsCloud = false;
  27165. }
  27166. });
  27167. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  27168. if (element.checked) {
  27169. _this._scene.forceWireframe = true;
  27170. _this._scene.forcePointsCloud = false;
  27171. }
  27172. });
  27173. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  27174. if (element.checked) {
  27175. _this._scene.forceWireframe = false;
  27176. _this._scene.forcePointsCloud = true;
  27177. }
  27178. });
  27179. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27180. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  27181. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) {
  27182. BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked;
  27183. });
  27184. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) {
  27185. BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked;
  27186. });
  27187. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) {
  27188. BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked;
  27189. });
  27190. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) {
  27191. BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked;
  27192. });
  27193. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) {
  27194. BABYLON.StandardMaterial.BumpTextureEnabled = element.checked;
  27195. });
  27196. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) {
  27197. BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked;
  27198. });
  27199. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) {
  27200. BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked;
  27201. });
  27202. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) {
  27203. BABYLON.StandardMaterial.FresnelEnabled = element.checked;
  27204. });
  27205. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27206. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  27207. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) {
  27208. _this._scene.animationsEnabled = element.checked;
  27209. });
  27210. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) {
  27211. _this._scene.collisionsEnabled = element.checked;
  27212. });
  27213. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) {
  27214. _this._scene.fogEnabled = element.checked;
  27215. });
  27216. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) {
  27217. _this._scene.lensFlaresEnabled = element.checked;
  27218. });
  27219. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) {
  27220. _this._scene.lightsEnabled = element.checked;
  27221. });
  27222. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) {
  27223. _this._scene.particlesEnabled = element.checked;
  27224. });
  27225. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) {
  27226. _this._scene.postProcessesEnabled = element.checked;
  27227. });
  27228. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) {
  27229. _this._scene.proceduralTexturesEnabled = element.checked;
  27230. });
  27231. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) {
  27232. _this._scene.renderTargetsEnabled = element.checked;
  27233. });
  27234. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) {
  27235. _this._scene.shadowsEnabled = element.checked;
  27236. });
  27237. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) {
  27238. _this._scene.skeletonsEnabled = element.checked;
  27239. });
  27240. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) {
  27241. _this._scene.spritesEnabled = element.checked;
  27242. });
  27243. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) {
  27244. _this._scene.texturesEnabled = element.checked;
  27245. });
  27246. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27247. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27248. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  27249. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", true, function (element) {
  27250. if (element.checked) {
  27251. _this._scene.switchAudioModeForHeadphones();
  27252. }
  27253. });
  27254. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", false, function (element) {
  27255. if (element.checked) {
  27256. _this._scene.switchAudioModeForNormalSpeakers();
  27257. }
  27258. });
  27259. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  27260. _this._scene.audioEnabled = !element.checked;
  27261. });
  27262. }
  27263. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27264. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  27265. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) {
  27266. _this._scene.dumpNextRenderTargets = true;
  27267. });
  27268. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  27269. this._globalDiv.appendChild(this._statsDiv);
  27270. this._globalDiv.appendChild(this._logDiv);
  27271. this._globalDiv.appendChild(this._optionsDiv);
  27272. this._globalDiv.appendChild(this._treeDiv);
  27273. }
  27274. };
  27275. DebugLayer.prototype._displayStats = function () {
  27276. var scene = this._scene;
  27277. var engine = scene.getEngine();
  27278. var glInfo = engine.getGlInfo();
  27279. 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>";
  27280. if (this.customStatsFunction) {
  27281. this._statsSubsetDiv.innerHTML += this._statsSubsetDiv.innerHTML;
  27282. }
  27283. };
  27284. return DebugLayer;
  27285. })();
  27286. BABYLON.DebugLayer = DebugLayer;
  27287. })(BABYLON || (BABYLON = {}));
  27288. //# sourceMappingURL=babylon.debugLayer.js.map
  27289. var BABYLON;
  27290. (function (BABYLON) {
  27291. var RawTexture = (function (_super) {
  27292. __extends(RawTexture, _super);
  27293. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  27294. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27295. if (invertY === void 0) { invertY = false; }
  27296. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27297. _super.call(this, null, scene, !generateMipMaps, invertY);
  27298. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  27299. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27300. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27301. }
  27302. // Statics
  27303. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27304. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27305. if (invertY === void 0) { invertY = false; }
  27306. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27307. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  27308. };
  27309. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27310. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27311. if (invertY === void 0) { invertY = false; }
  27312. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27313. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27314. };
  27315. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27316. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27317. if (invertY === void 0) { invertY = false; }
  27318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27319. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  27320. };
  27321. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27322. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27323. if (invertY === void 0) { invertY = false; }
  27324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27325. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  27326. };
  27327. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  27328. if (generateMipMaps === void 0) { generateMipMaps = true; }
  27329. if (invertY === void 0) { invertY = false; }
  27330. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27331. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  27332. };
  27333. return RawTexture;
  27334. })(BABYLON.Texture);
  27335. BABYLON.RawTexture = RawTexture;
  27336. })(BABYLON || (BABYLON = {}));
  27337. //# sourceMappingURL=babylon.rawTexture.js.map
  27338. var BABYLON;
  27339. (function (BABYLON) {
  27340. var IndexedVector2 = (function (_super) {
  27341. __extends(IndexedVector2, _super);
  27342. function IndexedVector2(original, index) {
  27343. _super.call(this, original.x, original.y);
  27344. this.index = index;
  27345. }
  27346. return IndexedVector2;
  27347. })(BABYLON.Vector2);
  27348. var PolygonPoints = (function () {
  27349. function PolygonPoints() {
  27350. this.elements = new Array();
  27351. }
  27352. PolygonPoints.prototype.add = function (originalPoints) {
  27353. var _this = this;
  27354. var result = new Array();
  27355. originalPoints.forEach(function (point) {
  27356. if (result.length === 0 || !(BABYLON.Tools.WithinEpsilon(point.x, result[0].x, 0.00001) && BABYLON.Tools.WithinEpsilon(point.y, result[0].y, 0.00001))) {
  27357. var newPoint = new IndexedVector2(point, _this.elements.length);
  27358. result.push(newPoint);
  27359. _this.elements.push(newPoint);
  27360. }
  27361. });
  27362. return result;
  27363. };
  27364. PolygonPoints.prototype.computeBounds = function () {
  27365. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27366. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  27367. this.elements.forEach(function (point) {
  27368. // x
  27369. if (point.x < lmin.x) {
  27370. lmin.x = point.x;
  27371. }
  27372. else if (point.x > lmax.x) {
  27373. lmax.x = point.x;
  27374. }
  27375. // y
  27376. if (point.y < lmin.y) {
  27377. lmin.y = point.y;
  27378. }
  27379. else if (point.y > lmax.y) {
  27380. lmax.y = point.y;
  27381. }
  27382. });
  27383. return {
  27384. min: lmin,
  27385. max: lmax,
  27386. width: lmax.x - lmin.x,
  27387. height: lmax.y - lmin.y
  27388. };
  27389. };
  27390. return PolygonPoints;
  27391. })();
  27392. var Polygon = (function () {
  27393. function Polygon() {
  27394. }
  27395. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  27396. return [
  27397. new BABYLON.Vector2(xmin, ymin),
  27398. new BABYLON.Vector2(xmax, ymin),
  27399. new BABYLON.Vector2(xmax, ymax),
  27400. new BABYLON.Vector2(xmin, ymax)
  27401. ];
  27402. };
  27403. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  27404. if (cx === void 0) { cx = 0; }
  27405. if (cy === void 0) { cy = 0; }
  27406. if (numberOfSides === void 0) { numberOfSides = 32; }
  27407. var result = new Array();
  27408. var angle = 0;
  27409. var increment = (Math.PI * 2) / numberOfSides;
  27410. for (var i = 0; i < numberOfSides; i++) {
  27411. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  27412. angle -= increment;
  27413. }
  27414. return result;
  27415. };
  27416. Polygon.Parse = function (input) {
  27417. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  27418. var i, result = [];
  27419. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  27420. result.push(new poly2tri.Point(floats[i], floats[i + 1]));
  27421. }
  27422. return result;
  27423. };
  27424. Polygon.StartingAt = function (x, y) {
  27425. return BABYLON.Path2.StartingAt(x, y);
  27426. };
  27427. return Polygon;
  27428. })();
  27429. BABYLON.Polygon = Polygon;
  27430. var PolygonMeshBuilder = (function () {
  27431. function PolygonMeshBuilder(name, contours, scene) {
  27432. this._points = new PolygonPoints();
  27433. if (!("poly2tri" in window)) {
  27434. throw "PolygonMeshBuilder cannot be used because poly2tri is not referenced";
  27435. }
  27436. this._name = name;
  27437. this._scene = scene;
  27438. var points;
  27439. if (contours instanceof BABYLON.Path2) {
  27440. points = contours.getPoints();
  27441. }
  27442. else {
  27443. points = contours;
  27444. }
  27445. this._swctx = new poly2tri.SweepContext(this._points.add(points));
  27446. }
  27447. PolygonMeshBuilder.prototype.addHole = function (hole) {
  27448. this._swctx.addHole(this._points.add(hole));
  27449. return this;
  27450. };
  27451. PolygonMeshBuilder.prototype.build = function (updatable) {
  27452. if (updatable === void 0) { updatable = false; }
  27453. var result = new BABYLON.Mesh(this._name, this._scene);
  27454. var normals = [];
  27455. var positions = [];
  27456. var uvs = [];
  27457. var bounds = this._points.computeBounds();
  27458. this._points.elements.forEach(function (p) {
  27459. normals.push(0, 1.0, 0);
  27460. positions.push(p.x, 0, p.y);
  27461. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  27462. });
  27463. var indices = [];
  27464. this._swctx.triangulate();
  27465. this._swctx.getTriangles().forEach(function (triangle) {
  27466. triangle.getPoints().forEach(function (point) {
  27467. indices.push(point.index);
  27468. });
  27469. });
  27470. result.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind, updatable);
  27471. result.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind, updatable);
  27472. result.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind, updatable);
  27473. result.setIndices(indices);
  27474. return result;
  27475. };
  27476. return PolygonMeshBuilder;
  27477. })();
  27478. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  27479. })(BABYLON || (BABYLON = {}));
  27480. //# sourceMappingURL=babylon.polygonMesh.js.mapvar BABYLON;
  27481. (function (BABYLON) {
  27482. var SimplificationSettings = (function () {
  27483. function SimplificationSettings(quality, distance) {
  27484. this.quality = quality;
  27485. this.distance = distance;
  27486. }
  27487. return SimplificationSettings;
  27488. })();
  27489. BABYLON.SimplificationSettings = SimplificationSettings;
  27490. /**
  27491. * The implemented types of simplification.
  27492. * At the moment only Quadratic Error Decimation is implemented.
  27493. */
  27494. (function (SimplificationType) {
  27495. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  27496. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  27497. var SimplificationType = BABYLON.SimplificationType;
  27498. var DecimationTriangle = (function () {
  27499. function DecimationTriangle(vertices) {
  27500. this.vertices = vertices;
  27501. this.error = new Array(4);
  27502. this.deleted = false;
  27503. this.isDirty = false;
  27504. this.borderFactor = 0;
  27505. }
  27506. return DecimationTriangle;
  27507. })();
  27508. BABYLON.DecimationTriangle = DecimationTriangle;
  27509. var DecimationVertex = (function () {
  27510. function DecimationVertex(position, normal, uv, id) {
  27511. this.position = position;
  27512. this.normal = normal;
  27513. this.uv = uv;
  27514. this.id = id;
  27515. this.isBorder = true;
  27516. this.q = new QuadraticMatrix();
  27517. this.triangleCount = 0;
  27518. this.triangleStart = 0;
  27519. }
  27520. return DecimationVertex;
  27521. })();
  27522. BABYLON.DecimationVertex = DecimationVertex;
  27523. var QuadraticMatrix = (function () {
  27524. function QuadraticMatrix(data) {
  27525. this.data = new Array(10);
  27526. for (var i = 0; i < 10; ++i) {
  27527. if (data && data[i]) {
  27528. this.data[i] = data[i];
  27529. }
  27530. else {
  27531. this.data[i] = 0;
  27532. }
  27533. }
  27534. }
  27535. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  27536. 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];
  27537. return det;
  27538. };
  27539. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  27540. for (var i = 0; i < 10; ++i) {
  27541. this.data[i] += matrix.data[i];
  27542. }
  27543. };
  27544. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  27545. for (var i = 0; i < 10; ++i) {
  27546. this.data[i] += data[i];
  27547. }
  27548. };
  27549. QuadraticMatrix.prototype.add = function (matrix) {
  27550. var m = new QuadraticMatrix();
  27551. for (var i = 0; i < 10; ++i) {
  27552. m.data[i] = this.data[i] + matrix.data[i];
  27553. }
  27554. return m;
  27555. };
  27556. QuadraticMatrix.FromData = function (a, b, c, d) {
  27557. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  27558. };
  27559. //returning an array to avoid garbage collection
  27560. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  27561. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  27562. };
  27563. return QuadraticMatrix;
  27564. })();
  27565. BABYLON.QuadraticMatrix = QuadraticMatrix;
  27566. var Reference = (function () {
  27567. function Reference(vertexId, triangleId) {
  27568. this.vertexId = vertexId;
  27569. this.triangleId = triangleId;
  27570. }
  27571. return Reference;
  27572. })();
  27573. BABYLON.Reference = Reference;
  27574. /**
  27575. * An implementation of the Quadratic Error simplification algorithm.
  27576. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  27577. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  27578. * @author RaananW
  27579. */
  27580. var QuadraticErrorSimplification = (function () {
  27581. function QuadraticErrorSimplification(_mesh) {
  27582. this._mesh = _mesh;
  27583. this.initialised = false;
  27584. this.syncIterations = 5000;
  27585. this.aggressiveness = 7;
  27586. this.decimationIterations = 100;
  27587. }
  27588. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  27589. var _this = this;
  27590. this.initWithMesh(this._mesh, function () {
  27591. _this.runDecimation(settings, successCallback);
  27592. });
  27593. };
  27594. QuadraticErrorSimplification.prototype.runDecimation = function (settings, successCallback) {
  27595. var _this = this;
  27596. var targetCount = ~~(this.triangles.length * settings.quality);
  27597. var deletedTriangles = 0;
  27598. var triangleCount = this.triangles.length;
  27599. var iterationFunction = function (iteration, callback) {
  27600. setTimeout(function () {
  27601. if (iteration % 5 === 0) {
  27602. _this.updateMesh(iteration === 0);
  27603. }
  27604. for (var i = 0; i < _this.triangles.length; ++i) {
  27605. _this.triangles[i].isDirty = false;
  27606. }
  27607. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  27608. var trianglesIterator = function (i) {
  27609. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  27610. var t = _this.triangles[tIdx];
  27611. if (!t)
  27612. return;
  27613. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  27614. return;
  27615. }
  27616. for (var j = 0; j < 3; ++j) {
  27617. if (t.error[j] < threshold) {
  27618. var deleted0 = [];
  27619. var deleted1 = [];
  27620. var i0 = t.vertices[j];
  27621. var i1 = t.vertices[(j + 1) % 3];
  27622. var v0 = _this.vertices[i0];
  27623. var v1 = _this.vertices[i1];
  27624. if (v0.isBorder !== v1.isBorder)
  27625. continue;
  27626. var p = BABYLON.Vector3.Zero();
  27627. var n = BABYLON.Vector3.Zero();
  27628. var uv = BABYLON.Vector2.Zero();
  27629. var color = new BABYLON.Color4(0, 0, 0, 1);
  27630. _this.calculateError(v0, v1, p, n, uv, color);
  27631. var delTr = [];
  27632. if (_this.isFlipped(v0, i1, p, deleted0, t.borderFactor, delTr))
  27633. continue;
  27634. if (_this.isFlipped(v1, i0, p, deleted1, t.borderFactor, delTr))
  27635. continue;
  27636. if (delTr.length == 2 || delTr[0] === delTr[1]) {
  27637. continue;
  27638. }
  27639. v0.normal = n;
  27640. if (v0.uv)
  27641. v0.uv = uv;
  27642. else if (v0.color)
  27643. v0.color = color;
  27644. v0.q = v1.q.add(v0.q);
  27645. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  27646. continue;
  27647. if (p.equals(v0.position))
  27648. continue;
  27649. v0.position = p;
  27650. var tStart = _this.references.length;
  27651. deletedTriangles = _this.updateTriangles(v0.id, v0, deleted0, deletedTriangles);
  27652. deletedTriangles = _this.updateTriangles(v0.id, v1, deleted1, deletedTriangles);
  27653. var tCount = _this.references.length - tStart;
  27654. if (tCount <= v0.triangleCount) {
  27655. if (tCount) {
  27656. for (var c = 0; c < tCount; c++) {
  27657. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  27658. }
  27659. }
  27660. }
  27661. else {
  27662. v0.triangleStart = tStart;
  27663. }
  27664. v0.triangleCount = tCount;
  27665. break;
  27666. }
  27667. }
  27668. };
  27669. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () {
  27670. return (triangleCount - deletedTriangles <= targetCount);
  27671. });
  27672. }, 0);
  27673. };
  27674. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  27675. if (triangleCount - deletedTriangles <= targetCount)
  27676. loop.breakLoop();
  27677. else {
  27678. iterationFunction(loop.index, function () {
  27679. loop.executeNext();
  27680. });
  27681. }
  27682. }, function () {
  27683. setTimeout(function () {
  27684. successCallback(_this.reconstructMesh());
  27685. }, 0);
  27686. });
  27687. };
  27688. QuadraticErrorSimplification.prototype.initWithMesh = function (mesh, callback) {
  27689. var _this = this;
  27690. if (!mesh)
  27691. return;
  27692. this.vertices = [];
  27693. this.triangles = [];
  27694. this._mesh = mesh;
  27695. //It is assumed that a mesh has positions, normals and either uvs or colors.
  27696. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27697. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27698. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27699. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  27700. var indices = mesh.getIndices();
  27701. var vertexInit = function (i) {
  27702. var vertex = new DecimationVertex(BABYLON.Vector3.FromArray(positionData, i * 3), BABYLON.Vector3.FromArray(normalData, i * 3), null, i);
  27703. if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27704. vertex.uv = BABYLON.Vector2.FromArray(uvs, i * 2);
  27705. }
  27706. else if (_this._mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27707. vertex.color = BABYLON.Color4.FromArray(colorsData, i * 4);
  27708. }
  27709. _this.vertices.push(vertex);
  27710. };
  27711. var totalVertices = mesh.getTotalVertices();
  27712. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, this.syncIterations, vertexInit, function () {
  27713. var indicesInit = function (i) {
  27714. var pos = i * 3;
  27715. var i0 = indices[pos + 0];
  27716. var i1 = indices[pos + 1];
  27717. var i2 = indices[pos + 2];
  27718. var triangle = new DecimationTriangle([_this.vertices[i0].id, _this.vertices[i1].id, _this.vertices[i2].id]);
  27719. _this.triangles.push(triangle);
  27720. };
  27721. BABYLON.AsyncLoop.SyncAsyncForLoop(indices.length / 3, _this.syncIterations, indicesInit, function () {
  27722. _this.init(callback);
  27723. });
  27724. });
  27725. };
  27726. QuadraticErrorSimplification.prototype.init = function (callback) {
  27727. var _this = this;
  27728. var triangleInit1 = function (i) {
  27729. var t = _this.triangles[i];
  27730. 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();
  27731. for (var j = 0; j < 3; j++) {
  27732. _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))));
  27733. }
  27734. };
  27735. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  27736. var triangleInit2 = function (i) {
  27737. var t = _this.triangles[i];
  27738. for (var j = 0; j < 3; ++j) {
  27739. t.error[j] = _this.calculateError(_this.vertices[t.vertices[j]], _this.vertices[t.vertices[(j + 1) % 3]]);
  27740. }
  27741. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27742. };
  27743. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  27744. _this.initialised = true;
  27745. callback();
  27746. });
  27747. });
  27748. };
  27749. QuadraticErrorSimplification.prototype.reconstructMesh = function () {
  27750. var newTriangles = [];
  27751. var i;
  27752. for (i = 0; i < this.vertices.length; ++i) {
  27753. this.vertices[i].triangleCount = 0;
  27754. }
  27755. var t;
  27756. var j;
  27757. for (i = 0; i < this.triangles.length; ++i) {
  27758. if (!this.triangles[i].deleted) {
  27759. t = this.triangles[i];
  27760. for (j = 0; j < 3; ++j) {
  27761. this.vertices[t.vertices[j]].triangleCount = 1;
  27762. }
  27763. newTriangles.push(t);
  27764. }
  27765. }
  27766. var newVerticesOrder = [];
  27767. //compact vertices, get the IDs of the vertices used.
  27768. var dst = 0;
  27769. for (i = 0; i < this.vertices.length; ++i) {
  27770. if (this.vertices[i].triangleCount) {
  27771. this.vertices[i].triangleStart = dst;
  27772. this.vertices[dst].position = this.vertices[i].position;
  27773. this.vertices[dst].normal = this.vertices[i].normal;
  27774. this.vertices[dst].uv = this.vertices[i].uv;
  27775. this.vertices[dst].color = this.vertices[i].color;
  27776. newVerticesOrder.push(i);
  27777. dst++;
  27778. }
  27779. }
  27780. for (i = 0; i < newTriangles.length; ++i) {
  27781. t = newTriangles[i];
  27782. for (j = 0; j < 3; ++j) {
  27783. t.vertices[j] = this.vertices[t.vertices[j]].triangleStart;
  27784. }
  27785. }
  27786. this.vertices = this.vertices.slice(0, dst);
  27787. var newPositionData = [];
  27788. var newNormalData = [];
  27789. var newUVsData = [];
  27790. var newColorsData = [];
  27791. for (i = 0; i < newVerticesOrder.length; ++i) {
  27792. newPositionData.push(this.vertices[i].position.x);
  27793. newPositionData.push(this.vertices[i].position.y);
  27794. newPositionData.push(this.vertices[i].position.z);
  27795. newNormalData.push(this.vertices[i].normal.x);
  27796. newNormalData.push(this.vertices[i].normal.y);
  27797. newNormalData.push(this.vertices[i].normal.z);
  27798. if (this.vertices[i].uv) {
  27799. newUVsData.push(this.vertices[i].uv.x);
  27800. newUVsData.push(this.vertices[i].uv.y);
  27801. }
  27802. else if (this.vertices[i].color) {
  27803. newColorsData.push(this.vertices[i].color.r);
  27804. newColorsData.push(this.vertices[i].color.g);
  27805. newColorsData.push(this.vertices[i].color.b);
  27806. newColorsData.push(this.vertices[i].color.a);
  27807. }
  27808. }
  27809. var newIndicesArray = [];
  27810. for (i = 0; i < newTriangles.length; ++i) {
  27811. newIndicesArray.push(newTriangles[i].vertices[0]);
  27812. newIndicesArray.push(newTriangles[i].vertices[1]);
  27813. newIndicesArray.push(newTriangles[i].vertices[2]);
  27814. }
  27815. //not cloning, to avoid geometry problems. Creating a whole new mesh.
  27816. var newMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  27817. newMesh.material = this._mesh.material;
  27818. newMesh.parent = this._mesh.parent;
  27819. newMesh.setIndices(newIndicesArray);
  27820. newMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  27821. newMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  27822. if (newUVsData.length > 0)
  27823. newMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  27824. if (newColorsData.length > 0)
  27825. newMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  27826. //preparing the skeleton support
  27827. if (this._mesh.skeleton) {
  27828. }
  27829. return newMesh;
  27830. };
  27831. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, index2, point, deletedArray, borderFactor, delTr) {
  27832. for (var i = 0; i < vertex1.triangleCount; ++i) {
  27833. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  27834. if (t.deleted)
  27835. continue;
  27836. var s = this.references[vertex1.triangleStart + i].vertexId;
  27837. var id1 = t.vertices[(s + 1) % 3];
  27838. var id2 = t.vertices[(s + 2) % 3];
  27839. if ((id1 === index2 || id2 === index2) && borderFactor < 2) {
  27840. deletedArray[i] = true;
  27841. delTr.push(t);
  27842. continue;
  27843. }
  27844. var d1 = this.vertices[id1].position.subtract(point);
  27845. d1 = d1.normalize();
  27846. var d2 = this.vertices[id2].position.subtract(point);
  27847. d2 = d2.normalize();
  27848. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  27849. return true;
  27850. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  27851. deletedArray[i] = false;
  27852. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  27853. return true;
  27854. }
  27855. return false;
  27856. };
  27857. QuadraticErrorSimplification.prototype.updateTriangles = function (vertexId, vertex, deletedArray, deletedTriangles) {
  27858. var newDeleted = deletedTriangles;
  27859. for (var i = 0; i < vertex.triangleCount; ++i) {
  27860. var ref = this.references[vertex.triangleStart + i];
  27861. var t = this.triangles[ref.triangleId];
  27862. if (t.deleted)
  27863. continue;
  27864. if (deletedArray[i]) {
  27865. t.deleted = true;
  27866. newDeleted++;
  27867. continue;
  27868. }
  27869. t.vertices[ref.vertexId] = vertexId;
  27870. t.isDirty = true;
  27871. t.error[0] = this.calculateError(this.vertices[t.vertices[0]], this.vertices[t.vertices[1]]) + (t.borderFactor / 2);
  27872. t.error[1] = this.calculateError(this.vertices[t.vertices[1]], this.vertices[t.vertices[2]]) + (t.borderFactor / 2);
  27873. t.error[2] = this.calculateError(this.vertices[t.vertices[2]], this.vertices[t.vertices[0]]) + (t.borderFactor / 2);
  27874. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  27875. this.references.push(ref);
  27876. }
  27877. return newDeleted;
  27878. };
  27879. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  27880. for (var i = 0; i < this.vertices.length; ++i) {
  27881. var vCount = [];
  27882. var vId = [];
  27883. var v = this.vertices[i];
  27884. var j;
  27885. for (j = 0; j < v.triangleCount; ++j) {
  27886. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  27887. for (var ii = 0; ii < 3; ii++) {
  27888. var ofs = 0;
  27889. var id = triangle.vertices[ii];
  27890. while (ofs < vCount.length) {
  27891. if (vId[ofs] === id)
  27892. break;
  27893. ++ofs;
  27894. }
  27895. if (ofs === vCount.length) {
  27896. vCount.push(1);
  27897. vId.push(id);
  27898. }
  27899. else {
  27900. vCount[ofs]++;
  27901. }
  27902. }
  27903. }
  27904. for (j = 0; j < vCount.length; ++j) {
  27905. if (vCount[j] === 1) {
  27906. this.vertices[vId[j]].isBorder = true;
  27907. }
  27908. else {
  27909. this.vertices[vId[j]].isBorder = false;
  27910. }
  27911. }
  27912. }
  27913. };
  27914. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  27915. if (identifyBorders === void 0) { identifyBorders = false; }
  27916. var i;
  27917. if (!identifyBorders) {
  27918. var newTrianglesVector = [];
  27919. for (i = 0; i < this.triangles.length; ++i) {
  27920. if (!this.triangles[i].deleted) {
  27921. newTrianglesVector.push(this.triangles[i]);
  27922. }
  27923. }
  27924. this.triangles = newTrianglesVector;
  27925. }
  27926. for (i = 0; i < this.vertices.length; ++i) {
  27927. this.vertices[i].triangleCount = 0;
  27928. this.vertices[i].triangleStart = 0;
  27929. }
  27930. var t;
  27931. var j;
  27932. var v;
  27933. for (i = 0; i < this.triangles.length; ++i) {
  27934. t = this.triangles[i];
  27935. for (j = 0; j < 3; ++j) {
  27936. v = this.vertices[t.vertices[j]];
  27937. v.triangleCount++;
  27938. }
  27939. }
  27940. var tStart = 0;
  27941. for (i = 0; i < this.vertices.length; ++i) {
  27942. this.vertices[i].triangleStart = tStart;
  27943. tStart += this.vertices[i].triangleCount;
  27944. this.vertices[i].triangleCount = 0;
  27945. }
  27946. var newReferences = new Array(this.triangles.length * 3);
  27947. for (i = 0; i < this.triangles.length; ++i) {
  27948. t = this.triangles[i];
  27949. for (j = 0; j < 3; ++j) {
  27950. v = this.vertices[t.vertices[j]];
  27951. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  27952. v.triangleCount++;
  27953. }
  27954. }
  27955. this.references = newReferences;
  27956. if (identifyBorders) {
  27957. this.identifyBorder();
  27958. }
  27959. };
  27960. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  27961. var x = point.x;
  27962. var y = point.y;
  27963. var z = point.z;
  27964. 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];
  27965. };
  27966. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  27967. var q = vertex1.q.add(vertex2.q);
  27968. var border = vertex1.isBorder && vertex2.isBorder;
  27969. var error = 0;
  27970. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  27971. if (qDet !== 0 && !border) {
  27972. if (!pointResult) {
  27973. pointResult = BABYLON.Vector3.Zero();
  27974. }
  27975. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  27976. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  27977. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  27978. error = this.vertexError(q, pointResult);
  27979. //TODO this should be correctly calculated
  27980. if (normalResult) {
  27981. normalResult.copyFrom(vertex1.normal);
  27982. if (vertex1.uv)
  27983. uvResult.copyFrom(vertex1.uv);
  27984. else if (vertex1.color)
  27985. colorResult.copyFrom(vertex1.color);
  27986. }
  27987. }
  27988. else {
  27989. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  27990. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  27991. var error1 = this.vertexError(q, vertex1.position);
  27992. var error2 = this.vertexError(q, vertex2.position);
  27993. var error3 = this.vertexError(q, p3);
  27994. error = Math.min(error1, error2, error3);
  27995. if (error === error1) {
  27996. if (pointResult) {
  27997. pointResult.copyFrom(vertex1.position);
  27998. normalResult.copyFrom(vertex1.normal);
  27999. if (vertex1.uv)
  28000. uvResult.copyFrom(vertex1.uv);
  28001. else if (vertex1.color)
  28002. colorResult.copyFrom(vertex1.color);
  28003. }
  28004. }
  28005. else if (error === error2) {
  28006. if (pointResult) {
  28007. pointResult.copyFrom(vertex2.position);
  28008. normalResult.copyFrom(vertex2.normal);
  28009. if (vertex2.uv)
  28010. uvResult.copyFrom(vertex2.uv);
  28011. else if (vertex2.color)
  28012. colorResult.copyFrom(vertex2.color);
  28013. }
  28014. }
  28015. else {
  28016. if (pointResult) {
  28017. pointResult.copyFrom(p3);
  28018. normalResult.copyFrom(vertex1.normal);
  28019. if (vertex1.uv)
  28020. uvResult.copyFrom(vertex1.uv);
  28021. else if (vertex1.color)
  28022. colorResult.copyFrom(vertex1.color);
  28023. }
  28024. }
  28025. }
  28026. return error;
  28027. };
  28028. return QuadraticErrorSimplification;
  28029. })();
  28030. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  28031. })(BABYLON || (BABYLON = {}));
  28032. //# sourceMappingURL=babylon.meshSimplification.js.mapvar BABYLON;
  28033. (function (BABYLON) {
  28034. var Analyser = (function () {
  28035. function Analyser(scene) {
  28036. this.SMOOTHING = 0.75;
  28037. this.FFT_SIZE = 512;
  28038. this.BARGRAPHAMPLITUDE = 256;
  28039. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  28040. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  28041. this._scene = scene;
  28042. this._audioEngine = BABYLON.Engine.audioEngine;
  28043. if (this._audioEngine.canUseWebAudio) {
  28044. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  28045. this._webAudioAnalyser.minDecibels = -140;
  28046. this._webAudioAnalyser.maxDecibels = 0;
  28047. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28048. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  28049. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  28050. }
  28051. }
  28052. Analyser.prototype.getFrequencyBinCount = function () {
  28053. if (this._audioEngine.canUseWebAudio) {
  28054. return this._webAudioAnalyser.frequencyBinCount;
  28055. }
  28056. else {
  28057. return 0;
  28058. }
  28059. };
  28060. Analyser.prototype.getByteFrequencyData = function () {
  28061. if (this._audioEngine.canUseWebAudio) {
  28062. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28063. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28064. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  28065. }
  28066. return this._byteFreqs;
  28067. };
  28068. Analyser.prototype.getByteTimeDomainData = function () {
  28069. if (this._audioEngine.canUseWebAudio) {
  28070. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28071. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28072. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  28073. }
  28074. return this._byteTime;
  28075. };
  28076. Analyser.prototype.getFloatFrequencyData = function () {
  28077. if (this._audioEngine.canUseWebAudio) {
  28078. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  28079. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  28080. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  28081. }
  28082. return this._floatFreqs;
  28083. };
  28084. Analyser.prototype.drawDebugCanvas = function () {
  28085. var _this = this;
  28086. if (this._audioEngine.canUseWebAudio) {
  28087. if (!this._debugCanvas) {
  28088. this._debugCanvas = document.createElement("canvas");
  28089. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  28090. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  28091. this._debugCanvas.style.position = "absolute";
  28092. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  28093. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  28094. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  28095. document.body.appendChild(this._debugCanvas);
  28096. this._registerFunc = function () {
  28097. _this.drawDebugCanvas();
  28098. };
  28099. this._scene.registerBeforeRender(this._registerFunc);
  28100. }
  28101. if (this._registerFunc) {
  28102. var workingArray = this.getByteFrequencyData();
  28103. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  28104. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  28105. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  28106. var value = workingArray[i];
  28107. var percent = value / this.BARGRAPHAMPLITUDE;
  28108. var height = this.DEBUGCANVASSIZE.height * percent;
  28109. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  28110. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  28111. var hue = i / this.getFrequencyBinCount() * 360;
  28112. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  28113. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  28114. }
  28115. }
  28116. }
  28117. };
  28118. Analyser.prototype.stopDebugCanvas = function () {
  28119. if (this._debugCanvas) {
  28120. this._scene.unregisterBeforeRender(this._registerFunc);
  28121. this._registerFunc = null;
  28122. document.body.removeChild(this._debugCanvas);
  28123. this._debugCanvas = null;
  28124. this._debugCanvasContext = null;
  28125. }
  28126. };
  28127. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  28128. if (this._audioEngine.canUseWebAudio) {
  28129. inputAudioNode.connect(this._webAudioAnalyser);
  28130. this._webAudioAnalyser.connect(outputAudioNode);
  28131. }
  28132. };
  28133. Analyser.prototype.dispose = function () {
  28134. if (this._audioEngine.canUseWebAudio) {
  28135. this._webAudioAnalyser.disconnect();
  28136. }
  28137. };
  28138. return Analyser;
  28139. })();
  28140. BABYLON.Analyser = Analyser;
  28141. })(BABYLON || (BABYLON = {}));
  28142. //# sourceMappingURL=babylon.analyser.js.mapvar BABYLON;
  28143. (function (BABYLON) {
  28144. var DepthRenderer = (function () {
  28145. function DepthRenderer(scene, type) {
  28146. var _this = this;
  28147. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  28148. this._viewMatrix = BABYLON.Matrix.Zero();
  28149. this._projectionMatrix = BABYLON.Matrix.Zero();
  28150. this._transformMatrix = BABYLON.Matrix.Zero();
  28151. this._worldViewProjection = BABYLON.Matrix.Zero();
  28152. this._scene = scene;
  28153. var engine = scene.getEngine();
  28154. // Render target
  28155. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  28156. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28157. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28158. this._depthMap.refreshRate = 1;
  28159. this._depthMap.renderParticles = false;
  28160. this._depthMap.renderList = null;
  28161. // Custom render function
  28162. var renderSubMesh = function (subMesh) {
  28163. var mesh = subMesh.getRenderingMesh();
  28164. var scene = _this._scene;
  28165. var engine = scene.getEngine();
  28166. // Culling
  28167. engine.setState(subMesh.getMaterial().backFaceCulling);
  28168. // Managing instances
  28169. var batch = mesh._getInstancesRenderList(subMesh._id);
  28170. if (batch.mustReturn) {
  28171. return;
  28172. }
  28173. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28174. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28175. engine.enableEffect(_this._effect);
  28176. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  28177. var material = subMesh.getMaterial();
  28178. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  28179. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  28180. // Alpha test
  28181. if (material && material.needAlphaTesting()) {
  28182. var alphaTexture = material.getAlphaTestTexture();
  28183. _this._effect.setTexture("diffuseSampler", alphaTexture);
  28184. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28185. }
  28186. // Bones
  28187. if (mesh.useBones) {
  28188. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28189. }
  28190. // Draw
  28191. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  28192. }
  28193. };
  28194. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  28195. var index;
  28196. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28197. renderSubMesh(opaqueSubMeshes.data[index]);
  28198. }
  28199. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28200. renderSubMesh(alphaTestSubMeshes.data[index]);
  28201. }
  28202. };
  28203. }
  28204. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  28205. var defines = [];
  28206. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28207. var mesh = subMesh.getMesh();
  28208. var scene = mesh.getScene();
  28209. var material = subMesh.getMaterial();
  28210. // Alpha test
  28211. if (material && material.needAlphaTesting()) {
  28212. defines.push("#define ALPHATEST");
  28213. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28214. attribs.push(BABYLON.VertexBuffer.UVKind);
  28215. defines.push("#define UV1");
  28216. }
  28217. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28218. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28219. defines.push("#define UV2");
  28220. }
  28221. }
  28222. // Bones
  28223. if (mesh.useBones) {
  28224. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28225. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28226. defines.push("#define BONES");
  28227. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28228. }
  28229. // Instances
  28230. if (useInstances) {
  28231. defines.push("#define INSTANCES");
  28232. attribs.push("world0");
  28233. attribs.push("world1");
  28234. attribs.push("world2");
  28235. attribs.push("world3");
  28236. }
  28237. // Get correct effect
  28238. var join = defines.join("\n");
  28239. if (this._cachedDefines !== join) {
  28240. this._cachedDefines = join;
  28241. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  28242. }
  28243. return this._effect.isReady();
  28244. };
  28245. DepthRenderer.prototype.getDepthMap = function () {
  28246. return this._depthMap;
  28247. };
  28248. // Methods
  28249. DepthRenderer.prototype.dispose = function () {
  28250. this._depthMap.dispose();
  28251. };
  28252. return DepthRenderer;
  28253. })();
  28254. BABYLON.DepthRenderer = DepthRenderer;
  28255. })(BABYLON || (BABYLON = {}));
  28256. //# sourceMappingURL=babylon.depthRenderer.js.map
  28257. var BABYLON;
  28258. (function (BABYLON) {
  28259. var SSAORenderingPipeline = (function (_super) {
  28260. __extends(SSAORenderingPipeline, _super);
  28261. /**
  28262. * @constructor
  28263. * @param {string} name - The rendering pipeline name
  28264. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28265. * @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)
  28266. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28267. */
  28268. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  28269. var _this = this;
  28270. _super.call(this, scene.getEngine(), name);
  28271. // Members
  28272. /**
  28273. * The PassPostProcess id in the pipeline that contains the original scene color
  28274. * @type {string}
  28275. */
  28276. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  28277. /**
  28278. * The SSAO PostProcess id in the pipeline
  28279. * @type {string}
  28280. */
  28281. this.SSAORenderEffect = "SSAORenderEffect";
  28282. /**
  28283. * The horizontal blur PostProcess id in the pipeline
  28284. * @type {string}
  28285. */
  28286. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  28287. /**
  28288. * The vertical blur PostProcess id in the pipeline
  28289. * @type {string}
  28290. */
  28291. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  28292. /**
  28293. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  28294. * @type {string}
  28295. */
  28296. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  28297. this._firstUpdate = true;
  28298. this._scene = scene;
  28299. // Set up assets
  28300. this._createRandomTexture();
  28301. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28302. var ssaoRatio = ratio.ssaoRatio || ratio;
  28303. var combineRatio = ratio.combineRatio || ratio;
  28304. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28305. this._createSSAOPostProcess(ssaoRatio);
  28306. this._blurHPostProcess = new BABYLON.BlurPostProcess("SSAOBlurH", new BABYLON.Vector2(2.0, 0.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28307. this._blurVPostProcess = new BABYLON.BlurPostProcess("SSAOBlurV", new BABYLON.Vector2(0.0, 2.0), 1.3, ssaoRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  28308. this._createSSAOCombinePostProcess(combineRatio);
  28309. // Set up pipeline
  28310. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () {
  28311. return _this._originalColorPostProcess;
  28312. }, true));
  28313. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () {
  28314. return _this._ssaoPostProcess;
  28315. }, true));
  28316. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () {
  28317. return _this._blurHPostProcess;
  28318. }, true));
  28319. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () {
  28320. return _this._blurVPostProcess;
  28321. }, true));
  28322. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () {
  28323. return _this._ssaoCombinePostProcess;
  28324. }, true));
  28325. // Finish
  28326. scene.postProcessRenderPipelineManager.addPipeline(this);
  28327. if (cameras)
  28328. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28329. }
  28330. // Public Methods
  28331. /**
  28332. * Returns the horizontal blur PostProcess
  28333. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  28334. */
  28335. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  28336. return this._blurHPostProcess;
  28337. };
  28338. /**
  28339. * Returns the vertical blur PostProcess
  28340. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  28341. */
  28342. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  28343. return this._blurVPostProcess;
  28344. };
  28345. /**
  28346. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  28347. */
  28348. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28349. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28350. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28351. this._originalColorPostProcess = undefined;
  28352. this._ssaoPostProcess = undefined;
  28353. this._blurHPostProcess = undefined;
  28354. this._blurVPostProcess = undefined;
  28355. this._ssaoCombinePostProcess = undefined;
  28356. this._randomTexture.dispose();
  28357. if (disableDepthRender)
  28358. this._scene.disableDepthRenderer();
  28359. };
  28360. // Private Methods
  28361. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  28362. var _this = this;
  28363. var sampleSphere = [
  28364. 0.5381,
  28365. 0.1856,
  28366. -0.4319,
  28367. 0.1379,
  28368. 0.2486,
  28369. 0.4430,
  28370. 0.3371,
  28371. 0.5679,
  28372. -0.0057,
  28373. -0.6999,
  28374. -0.0451,
  28375. -0.0019,
  28376. 0.0689,
  28377. -0.1598,
  28378. -0.8547,
  28379. 0.0560,
  28380. 0.0069,
  28381. -0.1843,
  28382. -0.0146,
  28383. 0.1402,
  28384. 0.0762,
  28385. 0.0100,
  28386. -0.1924,
  28387. -0.0344,
  28388. -0.3577,
  28389. -0.5301,
  28390. -0.4358,
  28391. -0.3169,
  28392. 0.1063,
  28393. 0.0158,
  28394. 0.0103,
  28395. -0.5869,
  28396. 0.0046,
  28397. -0.0897,
  28398. -0.4940,
  28399. 0.3287,
  28400. 0.7119,
  28401. -0.0154,
  28402. -0.0918,
  28403. -0.0533,
  28404. 0.0596,
  28405. -0.5411,
  28406. 0.0352,
  28407. -0.0631,
  28408. 0.5460,
  28409. -0.4776,
  28410. 0.2847,
  28411. -0.0271
  28412. ];
  28413. var samplesFactor = 1.0 / 16.0;
  28414. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", ["sampleSphere", "samplesFactor", "randTextureTiles"], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28415. this._ssaoPostProcess.onApply = function (effect) {
  28416. if (_this._firstUpdate) {
  28417. effect.setArray3("sampleSphere", sampleSphere);
  28418. effect.setFloat("samplesFactor", samplesFactor);
  28419. effect.setFloat("randTextureTiles", 4.0 / ratio);
  28420. _this._firstUpdate = false;
  28421. }
  28422. effect.setTexture("textureSampler", _this._depthTexture);
  28423. effect.setTexture("randomSampler", _this._randomTexture);
  28424. };
  28425. };
  28426. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  28427. var _this = this;
  28428. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28429. this._ssaoCombinePostProcess.onApply = function (effect) {
  28430. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  28431. };
  28432. };
  28433. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  28434. var size = 512;
  28435. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28436. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28437. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28438. var context = this._randomTexture.getContext();
  28439. var rand = function (min, max) {
  28440. return Math.random() * (max - min) + min;
  28441. };
  28442. for (var x = 0; x < size; x++) {
  28443. for (var y = 0; y < size; y++) {
  28444. var randVector = BABYLON.Vector3.Zero();
  28445. randVector.x = Math.floor(rand(0.0, 1.0) * 255);
  28446. randVector.y = Math.floor(rand(0.0, 1.0) * 255);
  28447. randVector.z = Math.floor(rand(0.0, 1.0) * 255);
  28448. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  28449. context.fillRect(x, y, 1, 1);
  28450. }
  28451. }
  28452. this._randomTexture.update(false);
  28453. };
  28454. return SSAORenderingPipeline;
  28455. })(BABYLON.PostProcessRenderPipeline);
  28456. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  28457. })(BABYLON || (BABYLON = {}));
  28458. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  28459. var BABYLON;
  28460. (function (BABYLON) {
  28461. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  28462. var VolumetricLightScatteringPostProcess = (function (_super) {
  28463. __extends(VolumetricLightScatteringPostProcess, _super);
  28464. /**
  28465. * @constructor
  28466. * @param {string} name - The post-process name
  28467. * @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)
  28468. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  28469. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  28470. * @param {number} samples - The post-process quality, default 100
  28471. * @param {number} samplingMode - The post-process filtering mode
  28472. * @param {BABYLON.Engine} engine - The babylon engine
  28473. * @param {boolean} reusable - If the post-process is reusable
  28474. */
  28475. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable) {
  28476. var _this = this;
  28477. if (samples === void 0) { samples = 100; }
  28478. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  28479. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  28480. this._screenCoordinates = BABYLON.Vector2.Zero();
  28481. /**
  28482. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  28483. * @type {boolean}
  28484. */
  28485. this.useCustomMeshPosition = false;
  28486. /**
  28487. * If the post-process should inverse the light scattering direction
  28488. * @type {boolean}
  28489. */
  28490. this.invert = true;
  28491. /**
  28492. * Array containing the excluded meshes not rendered in the internal pass
  28493. */
  28494. this.excludedMeshes = new Array();
  28495. this.exposure = 0.3;
  28496. this.decay = 0.96815;
  28497. this.weight = 0.58767;
  28498. this.density = 0.926;
  28499. var scene = camera.getScene();
  28500. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(scene.getEngine());
  28501. // Configure mesh
  28502. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  28503. // Configure
  28504. this._createPass(scene, ratio.passRatio || ratio);
  28505. this.onApply = function (effect) {
  28506. _this._updateMeshScreenCoordinates(scene);
  28507. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  28508. effect.setFloat("exposure", _this.exposure);
  28509. effect.setFloat("decay", _this.decay);
  28510. effect.setFloat("weight", _this.weight);
  28511. effect.setFloat("density", _this.density);
  28512. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  28513. };
  28514. }
  28515. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  28516. var mesh = subMesh.getMesh();
  28517. var defines = [];
  28518. var attribs = [BABYLON.VertexBuffer.PositionKind];
  28519. var material = subMesh.getMaterial();
  28520. // Render this.mesh as default
  28521. if (mesh === this.mesh) {
  28522. defines.push("#define BASIC_RENDER");
  28523. }
  28524. // Alpha test
  28525. if (material) {
  28526. if (material.needAlphaTesting() || mesh === this.mesh)
  28527. defines.push("#define ALPHATEST");
  28528. if (material.opacityTexture !== undefined)
  28529. defines.push("#define OPACITY");
  28530. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28531. attribs.push(BABYLON.VertexBuffer.UVKind);
  28532. defines.push("#define UV1");
  28533. }
  28534. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28535. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  28536. defines.push("#define UV2");
  28537. }
  28538. }
  28539. // Bones
  28540. if (mesh.useBones) {
  28541. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  28542. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  28543. defines.push("#define BONES");
  28544. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  28545. }
  28546. // Instances
  28547. if (useInstances) {
  28548. defines.push("#define INSTANCES");
  28549. attribs.push("world0");
  28550. attribs.push("world1");
  28551. attribs.push("world2");
  28552. attribs.push("world3");
  28553. }
  28554. // Get correct effect
  28555. var join = defines.join("\n");
  28556. if (this._cachedDefines !== join) {
  28557. this._cachedDefines = join;
  28558. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler", "opacitySampler"], join);
  28559. }
  28560. return this._volumetricLightScatteringPass.isReady();
  28561. };
  28562. /**
  28563. * Sets the new light position for light scattering effect
  28564. * @param {BABYLON.Vector3} The new custom light position
  28565. */
  28566. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  28567. this._customMeshPosition = position;
  28568. };
  28569. /**
  28570. * Returns the light position for light scattering effect
  28571. * @return {BABYLON.Vector3} The custom light position
  28572. */
  28573. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  28574. return this._customMeshPosition;
  28575. };
  28576. /**
  28577. * Disposes the internal assets and detaches the post-process from the camera
  28578. */
  28579. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  28580. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  28581. if (rttIndex !== -1) {
  28582. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  28583. }
  28584. this._volumetricLightScatteringRTT.dispose();
  28585. _super.prototype.dispose.call(this, camera);
  28586. };
  28587. /**
  28588. * Returns the render target texture used by the post-process
  28589. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  28590. */
  28591. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  28592. return this._volumetricLightScatteringRTT;
  28593. };
  28594. // Private methods
  28595. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  28596. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  28597. return true;
  28598. }
  28599. return false;
  28600. };
  28601. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  28602. var _this = this;
  28603. var engine = scene.getEngine();
  28604. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  28605. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28606. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28607. this._volumetricLightScatteringRTT.renderList = null;
  28608. this._volumetricLightScatteringRTT.renderParticles = false;
  28609. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  28610. // Custom render function for submeshes
  28611. var renderSubMesh = function (subMesh) {
  28612. var mesh = subMesh.getRenderingMesh();
  28613. if (_this._meshExcluded(mesh)) {
  28614. return;
  28615. }
  28616. var scene = mesh.getScene();
  28617. var engine = scene.getEngine();
  28618. // Culling
  28619. engine.setState(subMesh.getMaterial().backFaceCulling);
  28620. // Managing instances
  28621. var batch = mesh._getInstancesRenderList(subMesh._id);
  28622. if (batch.mustReturn) {
  28623. return;
  28624. }
  28625. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  28626. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  28627. engine.enableEffect(_this._volumetricLightScatteringPass);
  28628. mesh._bind(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode);
  28629. var material = subMesh.getMaterial();
  28630. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  28631. // Alpha test
  28632. if (material && (mesh === _this.mesh || material.needAlphaTesting() || material.opacityTexture !== undefined)) {
  28633. var alphaTexture = material.getAlphaTestTexture();
  28634. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  28635. if (_this.mesh.material && alphaTexture)
  28636. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  28637. if (material.opacityTexture !== undefined)
  28638. _this._volumetricLightScatteringPass.setTexture("opacitySampler", material.opacityTexture);
  28639. }
  28640. // Bones
  28641. if (mesh.useBones) {
  28642. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices());
  28643. }
  28644. // Draw
  28645. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._volumetricLightScatteringPass.setMatrix("world", world); });
  28646. }
  28647. };
  28648. // Render target texture callbacks
  28649. var savedSceneClearColor;
  28650. var sceneClearColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  28651. this._volumetricLightScatteringRTT.onBeforeRender = function () {
  28652. savedSceneClearColor = scene.clearColor;
  28653. scene.clearColor = sceneClearColor;
  28654. };
  28655. this._volumetricLightScatteringRTT.onAfterRender = function () {
  28656. scene.clearColor = savedSceneClearColor;
  28657. };
  28658. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  28659. var index;
  28660. for (index = 0; index < opaqueSubMeshes.length; index++) {
  28661. renderSubMesh(opaqueSubMeshes.data[index]);
  28662. }
  28663. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  28664. renderSubMesh(alphaTestSubMeshes.data[index]);
  28665. }
  28666. for (index = 0; index < transparentSubMeshes.length; index++) {
  28667. renderSubMesh(transparentSubMeshes.data[index]);
  28668. }
  28669. };
  28670. };
  28671. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  28672. var transform = scene.getTransformMatrix();
  28673. var pos = BABYLON.Vector3.Project(this.useCustomMeshPosition ? this._customMeshPosition : this.mesh.position, BABYLON.Matrix.Identity(), transform, this._viewPort);
  28674. this._screenCoordinates.x = pos.x / this._viewPort.width;
  28675. this._screenCoordinates.y = pos.y / this._viewPort.height;
  28676. if (this.invert)
  28677. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  28678. };
  28679. // Static methods
  28680. /**
  28681. * Creates a default mesh for the Volumeric Light Scattering post-process
  28682. * @param {string} The mesh name
  28683. * @param {BABYLON.Scene} The scene where to create the mesh
  28684. * @return {BABYLON.Mesh} the default mesh
  28685. */
  28686. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  28687. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  28688. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  28689. mesh.material = new BABYLON.StandardMaterial(name + "Material", scene);
  28690. return mesh;
  28691. };
  28692. return VolumetricLightScatteringPostProcess;
  28693. })(BABYLON.PostProcess);
  28694. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  28695. })(BABYLON || (BABYLON = {}));
  28696. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  28697. var BABYLON;
  28698. (function (BABYLON) {
  28699. var LensRenderingPipeline = (function (_super) {
  28700. __extends(LensRenderingPipeline, _super);
  28701. /**
  28702. * @constructor
  28703. * @param {string} name - The rendering pipeline name
  28704. * @param {object} parameters - An object containing all parameters (see below)
  28705. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  28706. * @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)
  28707. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  28708. Effect parameters are as follow:
  28709. {
  28710. chromatic_aberration: number; // from 0 to x (1 for realism)
  28711. edge_blur: number; // from 0 to x (1 for realism)
  28712. distortion: number; // from 0 to x (1 for realism)
  28713. grain_amount: number; // from 0 to 1
  28714. grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  28715. dof_focus_depth: number; // depth-of-field: focus depth; unset to disable
  28716. dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  28717. dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  28718. dof_gain: boolean; // depth-of-field: depthOfField gain (default: 1)
  28719. dof_threshold: boolean; // depth-of-field: depthOfField threshold (default: 1)
  28720. blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  28721. }
  28722. Note: if an effect parameter is unset, effect is disabled
  28723. */
  28724. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  28725. var _this = this;
  28726. if (ratio === void 0) { ratio = 1.0; }
  28727. _super.call(this, scene.getEngine(), name);
  28728. // Lens effects can be of the following:
  28729. // - chromatic aberration (slight shift of RGB colors)
  28730. // - blur on the edge of the lens
  28731. // - lens distortion
  28732. // - depth-of-field 'bokeh' effect (shapes appearing in blured areas, stronger highlights)
  28733. // - grain/dust-on-lens effect
  28734. // Two additional texture samplers are needed:
  28735. // - depth map (for depth-of-field)
  28736. // - grain texture
  28737. /**
  28738. * The chromatic aberration PostProcess id in the pipeline
  28739. * @type {string}
  28740. */
  28741. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  28742. /**
  28743. * The depth-of-field PostProcess id in the pipeline
  28744. * @type {string}
  28745. */
  28746. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  28747. this._scene = scene;
  28748. // Fetch texture samplers
  28749. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  28750. if (parameters.grain_texture) {
  28751. this._grainTexture = parameters.grain_texture;
  28752. }
  28753. else {
  28754. this._createGrainTexture();
  28755. }
  28756. // save parameters
  28757. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  28758. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  28759. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  28760. this._distortion = parameters.distortion ? parameters.distortion : 0;
  28761. this._highlightsGain = parameters.dof_gain ? parameters.dof_gain : 1;
  28762. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  28763. this._dofDepth = parameters.dof_focus_depth !== undefined ? parameters.dof_focus_depth : -1;
  28764. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  28765. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  28766. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  28767. // Create effects
  28768. this._createChromaticAberrationPostProcess(ratio);
  28769. this._createDepthOfFieldPostProcess(ratio);
  28770. // Set up pipeline
  28771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () {
  28772. return _this._chromaticAberrationPostProcess;
  28773. }, true));
  28774. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () {
  28775. return _this._depthOfFieldPostProcess;
  28776. }, true));
  28777. // Finish
  28778. scene.postProcessRenderPipelineManager.addPipeline(this);
  28779. if (cameras) {
  28780. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  28781. }
  28782. }
  28783. // public methods
  28784. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) {
  28785. this._edgeBlur = amount;
  28786. };
  28787. LensRenderingPipeline.prototype.disableEdgeBlur = function () {
  28788. this._edgeBlur = 0;
  28789. };
  28790. LensRenderingPipeline.prototype.setGrainAmount = function (amount) {
  28791. this._grainAmount = amount;
  28792. };
  28793. LensRenderingPipeline.prototype.disableGrain = function () {
  28794. this._grainAmount = 0;
  28795. };
  28796. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) {
  28797. this._chromaticAberration = amount;
  28798. };
  28799. LensRenderingPipeline.prototype.disableChromaticAberration = function () {
  28800. this._chromaticAberration = 0;
  28801. };
  28802. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) {
  28803. this._distortion = amount;
  28804. };
  28805. LensRenderingPipeline.prototype.disableEdgeDistortion = function () {
  28806. this._distortion = 0;
  28807. };
  28808. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  28809. this._highlightsGain = amount;
  28810. };
  28811. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  28812. this._highlightsThreshold = amount;
  28813. };
  28814. LensRenderingPipeline.prototype.setFocusDepth = function (amount) {
  28815. this._dofDepth = amount;
  28816. };
  28817. LensRenderingPipeline.prototype.disableDepthOfField = function () {
  28818. this._dofDepth = -1;
  28819. };
  28820. LensRenderingPipeline.prototype.setAperture = function (amount) {
  28821. this._dofAperture = amount;
  28822. };
  28823. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  28824. this._dofPentagon = true;
  28825. };
  28826. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  28827. this._dofPentagon = false;
  28828. };
  28829. LensRenderingPipeline.prototype.enableNoiseBlur = function () {
  28830. this._blurNoise = true;
  28831. };
  28832. LensRenderingPipeline.prototype.disableNoiseBlur = function () {
  28833. this._blurNoise = false;
  28834. };
  28835. /**
  28836. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  28837. */
  28838. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  28839. if (disableDepthRender === void 0) { disableDepthRender = false; }
  28840. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  28841. this._chromaticAberrationPostProcess = undefined;
  28842. this._depthOfFieldPostProcess = undefined;
  28843. this._grainTexture.dispose();
  28844. if (disableDepthRender)
  28845. this._scene.disableDepthRenderer();
  28846. };
  28847. // colors shifting and distortion
  28848. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  28849. var _this = this;
  28850. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], [], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28851. this._chromaticAberrationPostProcess.onApply = function (effect) {
  28852. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  28853. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28854. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28855. };
  28856. };
  28857. // colors shifting and distortion
  28858. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  28859. var _this = this;
  28860. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  28861. "gain",
  28862. "threshold",
  28863. "focus_depth",
  28864. "aperture",
  28865. "pentagon",
  28866. "maxZ",
  28867. "edge_blur",
  28868. "chromatic_aberration",
  28869. "distortion",
  28870. "blur_noise",
  28871. "grain_amount",
  28872. "screen_width",
  28873. "screen_height"
  28874. ], ["depthSampler", "grainSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  28875. this._depthOfFieldPostProcess.onApply = function (effect) {
  28876. effect.setBool('pentagon', _this._dofPentagon);
  28877. effect.setBool('blur_noise', _this._blurNoise);
  28878. effect.setFloat('maxZ', _this._scene.activeCamera.maxZ);
  28879. effect.setFloat('grain_amount', _this._grainAmount);
  28880. effect.setTexture("depthSampler", _this._depthTexture);
  28881. effect.setTexture("grainSampler", _this._grainTexture);
  28882. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  28883. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  28884. effect.setFloat('distortion', _this._distortion);
  28885. effect.setFloat('focus_depth', _this._dofDepth);
  28886. effect.setFloat('aperture', _this._dofAperture);
  28887. effect.setFloat('gain', _this._highlightsGain);
  28888. effect.setFloat('threshold', _this._highlightsThreshold);
  28889. effect.setFloat('edge_blur', _this._edgeBlur);
  28890. };
  28891. };
  28892. // creates a black and white random noise texture, 512x512
  28893. LensRenderingPipeline.prototype._createGrainTexture = function () {
  28894. var size = 512;
  28895. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  28896. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  28897. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  28898. var context = this._grainTexture.getContext();
  28899. var rand = function (min, max) {
  28900. return Math.random() * (max - min) + min;
  28901. };
  28902. var value;
  28903. for (var x = 0; x < size; x++) {
  28904. for (var y = 0; y < size; y++) {
  28905. value = Math.floor(rand(0.42, 0.58) * 255);
  28906. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  28907. context.fillRect(x, y, 1, 1);
  28908. }
  28909. }
  28910. this._grainTexture.update(false);
  28911. };
  28912. return LensRenderingPipeline;
  28913. })(BABYLON.PostProcessRenderPipeline);
  28914. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  28915. })(BABYLON || (BABYLON = {}));
  28916. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map